Lifespan Management
Relevant source files
The following files were used as context for generating this wiki page:
- uvicorn/lifespan/on.py
- uvicorn/lifespan/off.py
- uvicorn/_types.py
- tests/test_lifespan.py
- uvicorn/config.py (Inferred from usage in
uvicorn/lifespan/on.pyandtests/test_lifespan.py) - uvicorn/protocols/http/httptools_impl.py
Lifespan Management in Uvicorn refers to the mechanism that allows an ASGI application to perform setup and cleanup operations during the server's startup and shutdown phases. This is achieved through the ASGI Lifespan protocol, which provides a dedicated scope for long-running background tasks and shared state management.
The system ensures that the application is fully initialized before it begins accepting connections and that it has the opportunity to gracefully close resources (such as database connections or thread pools) before the process terminates.
Sources: uvicorn/lifespan/on.py:35-43, uvicorn/_types.py:76-79, README.md:104-106
Architecture and Components
The lifespan system is primarily implemented through two handler classes that are selected based on the server configuration.
Lifespan Handlers
LifespanOn: The active implementation of the lifespan protocol. It manages anasyncio.Queuefor communicating with the application and usesasyncio.Eventobjects to synchronize startup and shutdown transitions.LifespanOff: A "no-op" implementation used when lifespan management is explicitly disabled or when the application does not support it in "auto" mode. It provides the same interface asLifespanOnbut performs no actions.
Sources: uvicorn/lifespan/on.py:29, uvicorn/lifespan/off.py:9, tests/test_lifespan.py:46-52
Lifespan State
Uvicorn introduces a state dictionary within the lifespan scope. This state is intended to be shared across the entire application's lifetime. Protocols like HTTP and WebSockets receive a copy of this state or a reference to it in their respective scopes, allowing the application to access resources initialized during the lifespan startup phase.
Sources: uvicorn/lifespan/on.py:44, uvicorn/_types.py:79, tests/test_lifespan.py:192-205
Communication Protocol
The lifespan handler communicates with the ASGI application using specific event types defined in the ASGI specification.
Event Flow Diagram
The following diagram illustrates the sequence of messages between the Uvicorn Lifespan Handler and the ASGI Application.
Event Types
| Event Type | Direction | Description |
|---|---|---|
lifespan.startup | Handler -> App | Sent when the server is ready to start up. |
lifespan.startup.complete | App -> Handler | Sent by the app when initialization is finished. |
lifespan.startup.failed | App -> Handler | Sent by the app if initialization fails; prevents server start. |
lifespan.shutdown | Handler -> App | Sent when the server is beginning to shut down. |
lifespan.shutdown.complete | App -> Handler | Sent by the app when cleanup is finished. |
lifespan.shutdown.failed | App -> Handler | Sent by the app if cleanup fails. |
Sources: uvicorn/_types.py:157-178, uvicorn/lifespan/on.py:87-111
Implementation Details
The LifespanOn Main Loop
The core logic of LifespanOn resides in its main method, which is spawned as an independent task. It creates the LifespanScope and awaits the application callable.
# uvicorn/lifespan/on.py:74-85
async def main(self) -> None:
try:
app = self.config.loaded_app
scope: LifespanScope = {
"type": "lifespan",
"asgi": {"version": self.config.asgi_version, "spec_version": "2.0"},
"state": self.state,
}
await app(scope, self.receive, self.send)
except BaseException as exc:
self.error_occurred = True
# ... error handling ...
finally:
self.startup_event.set()
self.shutdown_event.set()
Sources: uvicorn/lifespan/on.py:74-95
Error Handling and "Auto" Mode
If the lifespan setting is set to "auto", Uvicorn will attempt to use the lifespan protocol but will gracefully fallback if the application raises an exception during the initial handshake. If the setting is "on", any exception in the lifespan protocol is treated as a fatal error, and the server will exit.
Sources: uvicorn/lifespan/on.py:53-56, tests/test_lifespan.py:91-105
Synchronization and State Transitions
The handler uses internal flags and events to ensure valid state transitions. For instance, a lifespan.shutdown.complete message is only valid if the startup_event has already been set.
Configuration Options
Lifespan behavior is controlled via the Config object, typically passed through the CLI or programmatic entry points.
| Option | Type | Default | Description |
|---|---|---|---|
lifespan | str | "auto" | Lifespan implementation to use: "auto", "on", or "off". |
asgi_version | str | "3.0" | The version of the ASGI spec to report in the lifespan scope. |
Sources: uvicorn/config.py, uvicorn/lifespan/on.py:79, tests/test_lifespan.py:10-15
Conclusion
Lifespan Management is a critical component of the Uvicorn server, providing a structured way for applications to manage their lifecycle. By adhering to the ASGI Lifespan protocol, Uvicorn ensures that applications can safely initialize and dispose of resources, contributing to the overall stability and reliability of the web service.