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

← All FastAPI questions