Python / FastAPI Basics Interview Questions
How do you measure and improve the performance of a FastAPI application?
FastAPI is already one of the fastest Python frameworks, but real-world performance depends on database queries, serialisation, and concurrency patterns. These are the key tools and techniques.
# 1. Measure with locust load testing # pip install locust # locustfile.py from locust import HttpUser, task, between class APIUser(HttpUser): wait_time = between(0.1, 1) @task(3) def list_items(self): self.client.get("/items") @task(1) def create_item(self): self.client.post("/items", json={"name": "test", "price": 1.0}) # locust -f locustfile.py --host=http://localhost:8000
# 2. Add request timing middleware import time from fastapi import FastAPI, Request app = FastAPI() @app.middleware("http") async def timing_middleware(request: Request, call_next): start = time.perf_counter() response = await call_next(request) elapsed = time.perf_counter() - start response.headers["X-Response-Time"] = f"{elapsed:.4f}s" if elapsed > 0.5: # log slow requests print(f"SLOW: {request.url.path} took {elapsed:.3f}s") return response
| Area | Tip |
|---|---|
| DB queries | Use async SQLAlchemy, add indexes, use select_in_loading for relationships |
| Serialisation | Pydantic v2 is ~5x faster than v1; avoid model_dump() in hot paths |
| Concurrency | Use async def for I/O-bound routes; avoid blocking calls in async context |
| Connection pools | Set pool size based on worker count × connections-per-worker |
| Response size | Use response_model_exclude_unset=True to reduce payload size |
| Caching | Cache expensive queries with Redis; use HTTP Cache-Control headers |
More Related questions...