Lifespan Context vs Startup Event: Safe Recovery After a Failed Upgrade
0 reputation · 08 Jan 2021, 10:42 UTC
Choosing a Lifecycle Hook for Upgrade Safety
When deploying a FastAPI application, a failed upgrade can leave resources—such as database connections or external services—in an inconsistent state. FastAPI exposes two primary mechanisms for initializing and cleaning up resources: the lifespan context manager and the legacy @app.on_event('startup') / @app.on_event('shutdown') decorators. Both can be used to orchestrate pre‑start and post‑shutdown logic, but they differ in ordering guarantees, startup latency, and cleanup reliability.
The lifespan context guarantees that the shutdown block runs only after the startup block completes, even if an exception occurs during startup. In contrast, the older event decorators offer no explicit ordering, and a failure in a startup event may leave other events or dependencies partially initialized.
Given the need to recover cleanly from a mid‑upgrade crash, which approach provides a more robust foundation for safe rollback?
Specific Questions
- Does the
lifespancontext manager ensure that all resources opened in itsstartupblock are guaranteed to be closed in theshutdownblock, even if the startup block raises an exception? - How does the startup event decorator’s lack of ordering affect the ability to roll back partially applied migrations or open connections during a failed upgrade?
- What measurable impact does each approach have on application readiness time and the risk of orphaned resources in a production deployment?