Lesson 55 of 59Production
Performance and Scaling
Measure before you optimise, fix the database first, then scale with workers, processes and more machines without running out of connections.
"The API is slow" is not something you can fix. "GET /orders has a p95 of 1.4 seconds, and 1.1 of those are 51 database queries" is. Performance work goes wrong when people guess: they rewrite code in async, add a cache, or double the server size, and the real bottleneck is untouched. This lesson follows the order seniors use: measure, fix the biggest cost (usually the database), cache what is safe to cache, then scale out with processes and machines, keeping an eye on the limit that bites everyone eventually: database connections.
Measure first
Start from the observability lesson's numbers: which routes are slow, at which percentile, since when. Then find where the time goes inside one slow request. A trace shows the split between database, external calls and your own code. When the time is in your Python code, reach for a profiler.
- cProfile ships with Python. It records every function call and reports how many times each ran and how long it took in total.
python -m cProfile -s cumulative script.pyprints a table;-o out.profsaves a file you can explore with a viewer such as SnakeViz. It adds overhead, so use it locally or in a benchmark. - py-spy is a sampling profiler. It peeks at a running process many times per second and records which function was executing, without changing or restarting your code.
py-spy top --pid 1234shows a live view;py-spy record -o profile.svg --pid 1234writes a flame graph where the widest bars are where the time goes. Its overhead is low enough for a staging server or, carefully, production.
Profilers answer two questions: which function is slow each time, and which is called far too often. The second is the more common surprise. Here is the core idea of a deterministic profiler like cProfile, built with a decorator:
Press Run (⌘ Enter) to see what happens.load_customer runs 500 times for only 50 distinct customers. Each call is fast, but together they dominate. The fix is not a faster load_customer; it is calling it 50 times, or once.
The database is usually the bottleneck
In a typical API, most of a request's time is spent waiting on the database. The databases lesson introduced the N+1 query and its fix with selectinload or joinedload. To catch N+1s, turn on SQL logging in development (create_engine(url, echo=True), or set the sqlalchemy.engine logger to INFO) and count the statements per request. A test that asserts a list endpoint runs a fixed number of queries, whatever the page size, stops N+1s from coming back.
Other common database wins:
- Index the columns you filter, join and sort on, and confirm with
EXPLAIN ANALYZEthat the query uses them. - Select less. Fetching 40 columns to show 3 wastes I/O and memory. Load only what the response needs.
- Paginate everything and cap the page size. For deep pages, keyset pagination (
WHERE id > :last_seen ORDER BY id LIMIT 20) stays fast whereOFFSET 100000has to walk past every skipped row. - Batch writes. One
INSERTwith 500 rows beats 500 single inserts and 500 round trips.
Cache what is safe to cache
Caching trades freshness for speed. Pick the cheapest layer that works:
- HTTP caching.
Cache-Control: public, max-age=60on a response lets browsers and CDNs reuse it without asking you at all. AnETaglets clients revalidate cheaply and get304 Not Modified. - In-process.
functools.lru_cacheor a small dict is perfect for data that never changes while the process runs, like parsed config. Each worker has its own copy, so it is wrong for anything that must be consistent across workers. - Shared cache. Redis holds results for all workers and machines, with a TTL, using the cache-aside pattern from the Redis lesson.
Cache data that is read far more often than it changes, and expensive to compute. Do not cache per-user data under a shared key, and always decide how stale is acceptable before choosing a TTL.
Match each problem to the tool or technique that addresses it.
Async where it helps
Async helps when a request spends its time waiting: calling three external APIs can take as long as the slowest one with asyncio.gather, not the sum. It does not make a single query faster, and it does nothing for CPU-heavy work, which blocks the event loop and every other request on it. Rules of thumb: use async def with async libraries (httpx.AsyncClient, an async database driver); use plain def for routes that call blocking libraries, so FastAPI runs them in a thread pool; move CPU-heavy or slow jobs to a task queue.
Workers and processes
A single Python process runs Python code on one CPU core at a time because of the GIL. To use a four-core machine, run several worker processes, each with its own event loop and memory:
fastapi run app/main.py --workers 4# or Gunicorn as the process manager, with Uvicorn workersgunicorn app.main:app -k uvicorn_worker.UvicornWorker -w 4 --bind 0.0.0.0:8000The Gunicorn worker class lives in the uvicorn-worker package; older guides use uvicorn.workers.UvicornWorker. Gunicorn adds mature process management (restarting crashed workers, graceful reloads), while Uvicorn's own --workers is simpler and often enough. Start with about one worker per core and measure. In Kubernetes or ECS, a common pattern is one worker per container and more containers, so the orchestrator handles restarts and scaling.
Horizontal scaling
Vertical scaling means a bigger machine; it is simple and has a ceiling. Horizontal scaling means more copies of the app behind a load balancer. It only works if the app is stateless: no sessions, uploads or caches that matter in local memory or on local disk, because the next request may land on a different copy. Keep state in Postgres, Redis and object storage, and any copy can serve any request. Autoscaling then adds and removes copies based on CPU or request rate.
Stateless containers behind a load balancer. Need more capacity? Add containers.
Database connection limits
Each SQLAlchemy engine keeps a pool: by default up to pool_size connections (5) plus max_overflow extras (10) under load. That is per process. So the worst case is:
containers × workers per container × (pool_size + max_overflow)
PostgreSQL's default max_connections is 100, and managed databases often set it from the instance size. Scale out carelessly and new connections are refused, and the errors appear exactly when traffic peaks. Fixes: smaller per-process pools, a pooler like PgBouncer (or your provider's built-in pooling), and a cap on autoscaling.
A bigger pool is not automatically faster either. If queries are slow, more connections means more queries competing for the same CPU and disk. Here is what a pool does when more requests arrive than it has connections:
Press Run (⌘ Enter) to see what happens.With 2 connections, the last request waits for nine others ahead of it on its connection. With 20, nobody waits, but only if the database can really run 20 queries at once at full speed. Past that point, the queue simply moves into the database.
How many database connections can this deployment open in the worst case?
containers = 3 workers_per_container = 4 pool_size, max_overflow = 5, 10 print(containers * workers_per_container * (pool_size + max_overflow))
Load testing with Locust
You cannot know your capacity until you push the system. Locust describes user behaviour in plain Python and simulates many users at once:
from locust import HttpUser, between, task
class Shopper(HttpUser):
wait_time = between(1, 3) # seconds between actions, like a real user
@task(5)
def browse(self):
self.client.get("/products?limit=20")
@task(1)
def view_order(self):
self.client.get("/orders/1", headers={"Authorization": "Bearer test-token"})locust -f locustfile.py --host https://staging.example.com# headless, for CI or a quick run: 200 users, 20 new per second, 5 minuteslocust -f locustfile.py --host https://staging.example.com --headless -u 200 -r 20 -t 5mLocust's web UI plots requests per second, failures and latency percentiles as users ramp up. Watch for the knee: the point where p95 latency climbs sharply while throughput stops growing. That is your capacity for this setup. Test against staging with production-like data, never against production without warning, and change one thing at a time between runs.
Order a sound approach to making a slow API faster.
- Tap the steps below in the right order.
- profiler
- A tool that measures where a program spends time, by recording calls (cProfile) or sampling (py-spy).
- flame graph
- A chart of sampled call stacks where the widest bars show the functions using the most time.
- worker process
- One of several copies of the app on a machine, each with its own event loop, so all CPU cores are used.
- horizontal scaling
- Adding more copies of a stateless app behind a load balancer instead of buying a bigger machine.
- connection pool
- A set of open database connections reused across requests. One per process, with a size limit.
- PgBouncer
- A lightweight pooler that lets many app connections share a small number of real PostgreSQL connections.
- load test
- Simulating many users to measure throughput and latency and find the point where the system degrades.