Skip to main content

FastAPI Application Lifespan States

This state diagram illustrates the lifecycle of a FastAPI application, from its initial construction to its final termination.

The process begins with the Initialization phase, where the FastAPI instance is created and its default configuration (like OpenAPI and documentation routes) is set up via the setup() method.

Once the application is started by an ASGI server (like Uvicorn), it enters the Lifespan Startup phase. Here, the application executes its startup logic. This can be either the modern lifespan context manager (code before the yield) or the legacy on_startup event handlers, which are wrapped in a _DefaultLifespan class for backward compatibility.

After successful startup, the application transitions to the Running state, where it is ready to serve HTTP and WebSocket requests. During this state, the application's state object is available for sharing data across requests.

When the server receives a shutdown signal (like SIGTERM), the application enters the Lifespan Shutdown phase. It executes the teardown logic (code after the yield in the lifespan context manager or on_shutdown handlers). Finally, the application reaches the Terminated state and the process ends.

The diagram also accounts for potential failures during the startup phase, which lead to a Startup Failed state, preventing the application from serving requests.

Key Architectural Findings:

  • FastAPI uses Starlette's lifespan protocol implementation, which follows the ASGI specification.
  • The lifespan parameter in FastAPI accepts an asynchronous context manager that handles both startup and shutdown.
  • Legacy on_startup and on_shutdown event handlers are still supported and are internally managed by a _DefaultLifespan context manager.
  • Lifespan contexts can be nested and merged when using include_router, allowing sub-routers to have their own lifecycle logic.
  • The application state can be initialized during the startup phase of the lifespan and is then accessible throughout the application's life.
  • The setup() method is called during __init__ to register default routes for OpenAPI and interactive documentation (Swagger UI/ReDoc).
Loading diagram...