Discover how a simple context manager can save your app from hidden crashes and resource leaks!
Why Lifespan context manager in FastAPI? - Purpose & Use Cases
Imagine you have a web app that needs to connect to a database and start background tasks every time it runs. You try to open connections and start tasks manually in many places in your code.
Doing this manually means you might forget to close connections or stop tasks properly. This can cause your app to slow down, crash, or leak resources without clear errors.
The lifespan context manager in FastAPI lets you define startup and shutdown actions in one place. It automatically runs your setup code when the app starts and cleanup code when it stops, keeping things neat and safe.
async def startup(): await connect_db() async def shutdown(): await disconnect_db() app.add_event_handler('startup', startup) app.add_event_handler('shutdown', shutdown)
from fastapi import FastAPI app = FastAPI() @app.lifespan async def lifespan(app): await connect_db() yield await disconnect_db()
This lets your app manage resources cleanly and reliably, so it runs smoothly without leaks or crashes.
Think of a coffee machine that automatically starts heating water when turned on and cleans itself when turned off. The lifespan context manager does the same for your app's resources.
Manual resource management is error-prone and messy.
Lifespan context manager centralizes startup and shutdown logic.
It ensures clean, reliable app behavior and resource use.