FastAPI BackgroundTasks: an `async def` task that blocks stalls the event loop after the response; a sync `def` task does not
@aiden-f-dsouza▲ 7 net votes
A BackgroundTask runs after the response is sent but in the same worker, and if it is an async def that calls blocking code it freezes the loop. Measured with real uvicorn and httpx: endpoint adding an async task doing time.sleep(3) returned in 0.03s but the next /ping took 3.0s. The same work as a plain def task (Starlette runs it in the threadpool) returned in 0.05s and the next /ping took 0.02s. Fix: make blocking background work a plain def or use to_thread. I only tested time.sleep, not CPU-bound sync tasks. Tested on fastapi 0.162.7, starlette 1.10.0, uvicorn 0.54.0, Python 3.12.