Application Lifecycle & Dependency Management
Overview
The application uses Reflex’sregister_lifespan_task API to run startup validation and cleanup logic. This mirrors FastAPI’s lifespan pattern using @asynccontextmanager, adapted for the Reflex framework. All lifecycle and dependency-injection logic lives in app/api/deps.py, keeping app/app.py as a thin wiring layer.
Architecture
Startup Sequence
1. Config Validation
Loadsget_app_config() and get_llm_config() from app/hydra_config.py. This forces Hydra to resolve all ${oc.env:...} references, surfacing missing environment variables immediately rather than on first user request. Logs the resolved app name, database URL (truncated), LLM model, and provider.
2. Service Registration
Calls_register_services() which populates ServiceRegistry:
3. Service Initialization
CallsServiceRegistry.initialize_all() which invokes initialize() on each registered service:
- LLMService — calls
LLMClientManager.get_client()to eagerly build the multi-provider fallback chain. Validates API keys and provider availability at boot time. - ChatService — checks that its LLM dependency is available.
4. Health Check
CallsServiceRegistry.health_check_all() and logs results. This provides observability into which services started successfully.
Shutdown Cleanup
CallsLLMClientManager.reset() to release cached LLM connections and provider resources.
Service Registry
TheServiceRegistry (app/api/services/registry.py) is a class-level registry for managing service lifecycle:
| Method | Purpose |
|---|---|
register(name, service) | Register a BaseService instance |
get(name) | Retrieve a service by name (raises KeyError if missing) |
initialize_all() | Call initialize() on all registered services |
health_check_all() | Run health_check() on all services, return {name: bool} |
list_services() | List registered service names |
Adding a New Service
- Create a class extending
BaseServiceinapp/api/services/:
- Register it in
_register_services()inapp/api/deps.py:
- Add a
Depends()callable if needed by FastAPI routes:
Dependency Injection
FastAPI Routes
UseDepends() callables from app/api/deps.py:
Reflex State Handlers
Userx.session() (synchronous) for database access, managed by Reflex’s internal session factory configured via db_url in rxconfig.py:
Configuration Source
All configuration flows through the Hydra system:Reflex Lifespan API
Reflex wraps FastAPI internally. Theregister_lifespan_task method accepts an @asynccontextmanager function: