Python / FastAPI 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 |
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
