Use FastAPI's lifespan context manager to create and dispose shared clients or pools once at startup and shutdown, expose them via app.state, and keep request-scoped cleanup in dependencies with yield.
Learn why the FastAPI lifespan context manager is the preferred choice over deprecated on_event handlers for managing async startup and shutdown resources.
FastAPI's lifespan context manager replaces deprecated on_event handlers for startup/shutdown. Learn how to share a single pooled httpx.AsyncClient across requests, wire it through dependency injection, and avoid common testing pitfalls.
Learn how FastAPI’s lifespan event handler centralises startup and shutdown logic, with a worked example using a SQLAlchemy async connection pool and notes on version and server requirements.
Choose FastAPI's lifespan context manager over legacy on_event handlers for reliable startup/shutdown of database pools, caches, and telemetry. This guide compares mechanisms, shows a production-ready pattern with nested async context managers, and provides validation steps.
Use FastAPI lifespan context managers to initialize app-scoped resources once at startup and guarantee cleanup on shutdown, exposing them via dependency injection without globals.