FastAPI interview question · Most asked
How would you improve the throughput of a FastAPI service?
Summary
Profile first, then: use async drivers end to end, avoid blocking calls in async def, reuse HTTP clients and DB pools, cache hot reads (Redis), offload heavy work to queues, optimize serialization, and scale workers horizontally.
Longer Answer
Common hotspots are DB queries (indexes, N+1), per-request client creation (create one httpx.AsyncClient in lifespan), and large Pydantic payloads (use response_model thoughtfully, ORJSON, or return pre-serialized data). Tune the DB pool against worker count so you don't exhaust Postgres connections (use PgBouncer). Load test with Locust/k6 and watch event loop lag.
Key Points
- No blocking calls in async paths
- Shared clients and pools via lifespan
- Cache + queue offloading
- Pool sizing vs DB connection limits
- Load test and measure event loop lag
More most-asked FastAPI questions
- How do `yield` dependencies work and why are they used for database sessions?
- What is FastAPI and what makes it different from Flask or Django?
- Walk through what happens to a request in FastAPI, from the ASGI server to the response.
- 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?
- How does dependency injection with `Depends` work in FastAPI?
- When should an endpoint be `async def` versus plain `def` in FastAPI?