← Back to FastAPI, page 2

fastapi-0039 · Hard senior

How do you make a FastAPI service faster under load? What would you measure and change first?

Measure first with load tests and tracing to see whether time goes to the database, outbound calls, serialisation or Python code. The biggest wins are usually in I/O: fewer and faster queries, connection pooling, caching, and concurrency for independent calls. On the FastAPI side, declare response models or return types so FastAPI serialises with Pydantic's Rust core directly to JSON bytes, keep responses small with pagination, avoid blocking the event loop, and tune worker counts from measurements.

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-spy or pyinstrument.

Typical bottlenecks and fixes, roughly in order of impact:

  1. 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.
  2. Outbound calls: reuse one httpx.AsyncClient per process (connection pooling, keep-alive), set timeouts, run independent calls concurrently with asyncio.gather and a semaphore, cache results.
  3. Caching: Redis for computed results, HTTP caching headers (Cache-Control, ETag) so clients and CDNs skip requests.
  4. Serialisation: when a return type or response_model is set, current FastAPI serialises through Pydantic directly to JSON bytes, which is fast; ORJSONResponse and UJSONResponse are now deprecated for that reason. Without a declared model, FastAPI falls back to jsonable_encoder plus json.dumps, which is slower. Avoid building big intermediate dicts; return only fields clients use.
  5. Event loop health: no blocking calls in async def; offload CPU work.
  6. Payload size: GZipMiddleware (with minimum_size) for large JSON; compress at the proxy if possible.
  7. 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