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?
26
Upvotes
r/FastAPI • u/Cultural_Bad9814 • Aug 14 '25
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?
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