Skip to main content

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:

  1. Routing: The application matches the request URL and method to a specific APIRoute.
  2. Dependency Resolution: FastAPI's dependency injection system (The Dependency Resolution Engine) resolves all required parameters, including security and sub-dependencies.
  3. Executing Endpoint: The path operation function is called with the resolved dependencies.
  4. Response Handling: The return value is serialized and validated against the response_model.
  5. Background Tasks: If BackgroundTasks are defined, they are executed after the response has been fully sent to the client.
  6. Cleanup: FastAPI uses multiple AsyncExitStack instances to ensure resources (like database connections or open files) are closed. The function_stack closes immediately after the endpoint returns, while the request_stack and 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 lifespan context manager and legacy on_startup/on_shutdown events.
  • The request lifecycle is managed by APIRoute and get_request_handler, which coordinate routing, dependency injection, and response serialization.
  • Dependency injection uses solve_dependencies to recursively resolve and cache dependencies, managing their lifecycle via multiple AsyncExitStack instances.
  • Background tasks are executed by the Starlette Response object after the ASGI send calls 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.
Loading diagram...