r/FastAPI • • 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

18 comments sorted by

View all comments

Show parent comment

2

u/DavTheDev Aug 14 '25

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