Event Loop and Blocking Calls
noun
say it: “ih-VENT loop and BLOK-ing KAWLZ” /ɪˈvɛnt lup ænd ˈblɑkɪŋ ˈkɔlz/
In FastAPI, the rule that a slow call that isn't async, such as time.sleep, inside an async def route freezes every request, because they all share one event loop.
What is Event Loop and Blocking Calls?
Async endpoints share one event loop. A slow, non-async call (like time.sleep or a blocking database driver) inside async def freezes every request. Use async libraries, or a plain def endpoint, which FastAPI runs in a thread.
# Bad: freezes the whole server for 5 seconds
@app.get('/slow')
async def slow():
time.sleep(5)
# Good
@app.get('/slow')
async def slow():
await asyncio.sleep(5)
In a sentence
- “Tom's notes on the event loop and blocking calls say: no requests.get inside async def.”
- “A plain def route avoids the trouble with the event loop and blocking calls, since FastAPI runs it in a thread.”
Level: Master · More FastAPI terms at this level
Updated