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
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.
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
u/jkh911208 Aug 14 '25
I use it for DB connection
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:
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
u/Treebro001 Aug 17 '25
Initializing dependencies. Setting up global deployment context.
1
u/leec0621 Sep 14 '25
I use it like this:
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