FastAPI Application and Request Lifecycle States
This state diagram illustrates the dual lifecycle of a FastAPI application: the global application lifecycle and the per-request lifecycle.
Application Lifecycle
The application transitions from Uninitialized to Ready via the ASGI lifespan protocol. During the Starting phase, it executes the lifespan context manager (pre-yield) and any registered on_startup handlers. When the server signals shutdown, it enters the Stopping phase, executing on_shutdown handlers and the remainder of the lifespan context manager (post-yield).
Request Lifecycle
When the application is in the Ready state, it can process incoming HTTP requests. The request lifecycle is managed through several distinct stages:
- Routing: The application matches the request URL and method to a specific APIRoute.
- Dependency Resolution: FastAPI's dependency injection system (The Dependency Resolution Engine) resolves all required parameters, including security and sub-dependencies.
- Executing Endpoint: The path operation function is called with the resolved dependencies.
- Response Handling: The return value is serialized and validated against the
response_model. - Background Tasks: If BackgroundTasks are defined, they are executed after the response has been fully sent to the client.
- Cleanup: FastAPI uses multiple
AsyncExitStackinstances to ensure resources (like database connections or open files) are closed. Thefunction_stackcloses immediately after the endpoint returns, while therequest_stackand middleware stacks close after the response and background tasks are finished.
The diagram also highlights the role of Global Exception Handling in transitioning from various processing states to an error response state.
Key Architectural Findings:
- FastAPI application lifecycle is driven by the ASGI Lifespan protocol, supporting both the modern
lifespancontext manager and legacyon_startup/on_shutdownevents. - The request lifecycle is managed by
APIRouteandget_request_handler, which coordinate routing, dependency injection, and response serialization. - Dependency injection uses
solve_dependenciesto recursively resolve and cache dependencies, managing their lifecycle via multipleAsyncExitStackinstances. - Background tasks are executed by the Starlette
Responseobject after the ASGIsendcalls are completed, but before the final request-scoped exit stacks are unwound. - FastAPI distinguishes between 'function-scoped' and 'request-scoped' dependencies, closing the former immediately after the endpoint returns and the latter after the response is sent.