Full answer
Start with numbers
- Load test with realistic traffic (Locust, k6, wrk) and record p50, p95, p99 latency, throughput and error rate.
- Trace requests (OpenTelemetry) to see time in the database, HTTP calls and application code.
- Profile hot paths with
py-spyorpyinstrument.
Typical bottlenecks and fixes, roughly in order of impact:
- Database: N+1 queries (eager load), missing indexes (
EXPLAIN ANALYZE), unbounded result sets (paginate), chatty transactions. Use a connection pool sized to the database's limits. - Outbound calls: reuse one
httpx.AsyncClientper process (connection pooling, keep-alive), set timeouts, run independent calls concurrently withasyncio.gatherand a semaphore, cache results. - Caching: Redis for computed results, HTTP caching headers (
Cache-Control,ETag) so clients and CDNs skip requests. - Serialisation: when a return type or
response_modelis set, current FastAPI serialises through Pydantic directly to JSON bytes, which is fast;ORJSONResponseandUJSONResponseare now deprecated for that reason. Without a declared model, FastAPI falls back tojsonable_encoderplusjson.dumps, which is slower. Avoid building big intermediate dicts; return only fields clients use. - Event loop health: no blocking calls in
async def; offload CPU work. - Payload size:
GZipMiddleware(withminimum_size) for large JSON; compress at the proxy if possible. - Process model: workers per CPU core, tuned by load test. Python 3.13+ and recent Pydantic releases also bring free speed-ups, so stay current.
Avoid premature micro-optimisation: replacing one JSON library rarely matters when a query takes 80 ms. Change one thing at a time and re-measure, and keep a performance test in CI for critical endpoints.
python
import asyncio
import time
from fastapi import FastAPI
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.testclient import TestClient
from pydantic import BaseModel
app = FastAPI()
app.add_middleware(GZipMiddleware, minimum_size=1000)
class Row(BaseModel):
roll_no: int
name: str
attendance: float
ROWS = [{"roll_no": i, "name": f"Student {i}", "attendance": 80 + i % 20} for i in range(2000)]
@app.get("/rows-typed", response_model=list[Row])
def rows_typed():
return ROWS
@app.get("/rows-untyped")
def rows_untyped():
return ROWS
async def fetch(service: str) -> str:
await asyncio.sleep(0.2) # an outbound call
return service
@app.get("/dashboard-sequential")
async def sequential():
return [await fetch(s) for s in ("fees", "library", "hostel")]
@app.get("/dashboard-concurrent")
async def concurrent():
return await asyncio.gather(*(fetch(s) for s in ("fees", "library", "hostel")))
def timed(client, path, **kw):
start = time.perf_counter()
r = client.get(path, **kw)
return r, time.perf_counter() - start
with TestClient(app) as c:
_, seq = timed(c, "/dashboard-sequential")
_, con = timed(c, "/dashboard-concurrent")
print("concurrent calls faster than sequential:", con < seq / 2)
r, _ = timed(c, "/rows-typed", headers={"Accept-Encoding": "gzip"})
print("gzip:", r.headers.get("content-encoding"), "| rows:", len(r.json()))
print("same data either way:", c.get("/rows-typed").json() == c.get("/rows-untyped").json())
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Timings are compared rather than printed, so the output is stable across machines. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): concurrent calls faster than sequential: True gzip: gzip | rows: 2000 same data either way: True
Key points
- Measure p95/p99 and trace before changing code
- Database and outbound I/O are usually the biggest wins
- Reuse HTTP clients; cache; run independent calls concurrently
- Declare response models: FastAPI serialises via Pydantic to JSON bytes
- ORJSONResponse is deprecated in current FastAPI; tune workers by load test
Common mistakes
- Optimising JSON libraries before checking database time
- Creating a new HTTP client per request
- Returning thousands of rows with no pagination
- Tuning worker counts by guesswork instead of load tests
- Measuring averages only and missing tail latency
Follow-ups
- How would you find which part of a slow endpoint takes the time?
- Why did FastAPI deprecate ORJSONResponse?
- How do you choose the number of workers for an async service?
Tips
- Start with measurement and tools
- Rank fixes by typical impact
- Know the current serialisation behaviour with response models