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
View all comments
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.