r/FastAPI • u/Cultural_Bad9814 • Aug 14 '25
Question Lifespan on Fastapi
Hey guys, been enjoying fastapi for a bit now. How much do you use lifespan on fastapi and on what purposes have you used it on?
3
u/david-vujic Aug 15 '25
Usually DB initializations that should happen before the first requests coming in, and teardown before the app is exiting.
2
2
u/hadriendavid Aug 17 '25
In FastSQLA, it is used to setup async db engine at app startup. In al the apps I've written, it is where configuration of the app gets done.
2
u/aliparpar Aug 18 '25
You can use lifespan events for variety of things:
DB pool / engine initialisations
Loading ML models
Fetching artefacts on runtime
Setting up loggers and schedulers
clearing log files and artefacts
Run health checks and fail the startup if they fail
Setup workers and message queues
Initialise metric collectors
Warm up JWT keys with auth providers for machine to machine communication so first request doesn’t block
Graceful draining of requests
Send notifications to slack that api has started
Seed test databases
Enable debug tooling
Log ASCII art banners on app startup and shutdown
Rotate secrets and keys
Open persistent gRPC and WebSocket connections that remain alive during app life
Version stamping the app based on git commit
Enable Chaos mode to randomly kill background tasks or inject delays to load test the app
Load api routes dynamically based on feature flags
1
u/Drevicar Aug 16 '25
If you know the purpose of the context manager protocol in python and what it affords it is that for the concept of an application.
1
u/KeyPossibility2339 Aug 16 '25
Initialise langgraph, add tools, of course as everyone said db connections, connecting to mcp
1
1
u/leec0621 Sep 14 '25
I use it like this:
class AppState(TypedDict):
"""
Defines the structure of the shared state during the application lifecycle.
This provides explicit type information for type checkers and editors.
"""
engine: AsyncEngine
session_factory: async_sessionmaker[AsyncSession]
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[AppState]:
# -------- Startup --------
get_settings()
engine, session_factory = await setup_database_connection()
logger.info("🚀 Application started, database is ready.")
await create_db_and_tables(engine)
# yield {"engine": engine, "session_factory": session_factory}
# More type-safe approach
yield AppState(
engine=engine,
session_factory=session_factory,
)
# -------- Shutdown --------
await close_database_connection(engine)
logger.info("Application shut down, resources released.")1
u/Fun-Lecture-1221 Aug 15 '25
sometimes i use it to load an ML model so i dont need to load the model for each new inferences
14
u/SpecialistCamera5601 Aug 14 '25
I mostly use lifespan to init stuff like DB connections, load configs into memory, or kick off schedulers when the app starts, then clean them up on shutdown. Nice to have all that in one place. You can also use it to start/stop background services like Kafka consumers or cron jobs from a central spot. Won’t go too deep here to avoid overcomplicating things, but that’s the gist.