How does FastAPI handle asynchronous path functions compared to synchronous ones?
FastAPI calls async def path functions on its own async event loop, while synchronous def path functions are run in a threadpool. Async path functions can pause on I/O waits, letting the server handle other requests during that time. A developer does not need to add await when FastAPI invokes an async endpoint.
FastAPI distinguishes path functions by their definition. If a path function is declared with async def, FastAPI runs it on the async event loop and coordinates it alongside other async tasks. Because such a function can use await on operations like asyncio.sleep or real I/O calls, the event loop can switch to other requests while the awaited operation is waiting. In contrast, normal def path functions are synchronous and are managed through a threadpool, so FastAPI handles them without requiring the developer to deal with thread details. As the source notes, the main benefit of async is avoiding long waits for I/O; async setup can even be a little slower, but it allows the web server to serve other requests during waits. FastAPI calls async path functions itself, so you do not need to add await anywhere for those endpoints.
Key points
- FastAPI runs async path functions on an async event loop.
- Synchronous def path functions are run in a threadpool managed by FastAPI.
- An async path function can await slow operations and let other requests proceed meanwhile.
- The developer does not need to add await when FastAPI calls an async def endpoint.
- Async code mainly helps avoid long I/O waits rather than making code compute faster.
Related questions
FastAPI: Modern Python Web Development
Bill Lubanovic;
First Edition · O'Reilly Media, Inc.