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.
Please feel free to have a look at this one. You can do a lot more stuff; this is just a foundation.
The main difference is that lifespan runs once when the app starts and once when it shuts down. DI deps usually run per request or whenever you inject them. Lifespan’s great for stuff you want to set up once and keep around for the whole lifetime of the app.
EDIT: Reddit keeps blocking my comment, I guess because of the code block. I tried at least 1000 times to write this :D. It shouldn't have been that hard!
I usually just create these things as async tasks and cancel them after the yield. Also sometimes my classes need the eventloop e.g to delegate some synchronous calls to an executor and if they have the reference to the current eventloop that reduces the callstack overhead over calling asyncio.to_thread() (because that calls get_event_loop or get_running_loop under the hood, can’t remember which one), so I initialize them in the lifespan method
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