FastAPI Is Fast Only While async Endpoints Never Block the Event Loop

In progress

FastAPI's speed comes from two libraries it builds on: Starlette, an ASGI toolkit that serves many requests concurrently on one event loop, and Pydantic, which parses and validates data from type hints. The concurrency only holds while code inside async def endpoints waits with await; one blocking call there stops every other request handled by that worker.

What Each Layer Brings

Layer Provides
Starlette (ASGI) routing, requests and responses, async request handling
Pydantic validation and conversion of request data from type hints; 422 responses with a JSON list of errors
FastAPI ties both to Python type hints and generates an OpenAPI schema, served as Swagger UI at /docs and ReDoc at /redoc

FastAPI also ships security helpers (OAuth2 password flow, HTTP Basic, API keys) that plug into the OpenAPI docs. They are building blocks, not a user system: storing users and checking passwords stay your job.

How def and async def Endpoints Run

  • An async def endpoint runs on the event loop. While it awaits (an async database driver, httpx.AsyncClient), the loop serves other requests.
  • A plain def endpoint runs in a threadpool, so blocking calls inside it don't freeze the loop.

Where the Speed Claim Applies

FastAPI's documentation places it among the fastest Python frameworks, on par with Node.js and Go. That is a property of the I/O-bound case: many requests waiting on networks and databases. CPU-heavy work (image processing, large computations) gains nothing from the event loop and belongs in worker processes or a task queue.

References

Review cards

Flashcard A `requests.get()` call inside an `async def` endpoint takes two seconds. What happens to the worker's other requests, and what are the two fixes?

They all wait: the call blocks the event loop until it returns. Use an async client such as httpx.AsyncClient, or declare the endpoint with plain def so it runs in the threadpool.

Quiz For which workload does FastAPI's "on par with Node.js and Go" claim hold?
  • Many requests waiting on databases and other services
  • Image processing and other CPU-heavy work
  • Endpoints that call time.sleep() inside async def
  • Any workload, whatever the endpoints do

The event loop helps while requests wait on I/O. CPU-heavy work gains nothing from it, and a blocking call in async def freezes the worker.