FastAPI Is Fast Only While async Endpoints Never Block the Event Loop
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 defendpoint runs on the event loop. While itawaits (an async database driver,httpx.AsyncClient), the loop serves other requests. - A plain
defendpoint 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
- FastAPI MOC - hub for FastAPI notes.
- FastAPI documentation: Concurrency and async / await - when to use
deforasync def, and the threadpool. - FastAPI documentation: Features - Starlette and Pydantic foundations, automatic docs, the performance claim.
- FastAPI documentation: First Steps -
/docsand/redoc.
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()insideasync 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.