FastAPI interview question · Most asked
Explain coroutines, the event loop and tasks in Python asyncio, as they relate to FastAPI.
Summary
A coroutine (async def) is a pausable function; the event loop runs coroutines, switching between them whenever one awaits I/O; a Task wraps a coroutine so it runs concurrently. FastAPI runs each async def request handler as a coroutine on Uvicorn's event loop.
Longer Answer
Concurrency comes from cooperative yielding at await points, so a single thread can serve thousands of waiting requests. If a coroutine never awaits (CPU work) or calls blocking functions, nothing else can run. asyncio.create_task() schedules work concurrently, but tasks started inside a request without tracking can be garbage-collected or outlive the request.
Key Points
- Coroutines yield control at
await - Single-threaded cooperative scheduling
- Tasks run coroutines concurrently
- Blocking code stalls the whole loop
More most-asked FastAPI questions
- How does dependency injection with `Depends` work in FastAPI?
- Walk through what happens to a request in FastAPI, from the ASGI server to the response.
- What is FastAPI and what makes it different from Flask or Django?
- How do `yield` dependencies work and why are they used for database sessions?
- How does FastAPI distinguish path, query and body parameters?
- How does FastAPI use Pydantic for request validation?
- What does `response_model` (or a return annotation) do in FastAPI?
- When should an endpoint be `async def` versus plain `def` in FastAPI?