Skip to content

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.

18 min read0/4 questions

"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.py prints a table; -o out.prof saves 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 1234 shows a live view; py-spy record -o profile.svg --pid 1234 writes 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:

Pythontiny_profiler.py
import functoolsimport timefrom collections import defaultdict stats = defaultdict(lambda: [0, 0.0]) # name -> [calls, total seconds] def profile(fn): @functools.wraps(fn) def wrapper(*args, **kwargs): start = time.perf_counter() try: return fn(*args, **kwargs) finally: stats[fn.__name__][0] += 1 stats[fn.__name__][1] += time.perf_counter() - start return wrapper @profiledef load_customer(customer_id): return sum(i * customer_id for i in range(2000)) # pretend this is a query @profiledef format_row(order_id, customer): return f"order {order_id}: {customer}" @profiledef list_orders(n): return [format_row(i, load_customer(i % 50)) for i in range(n)] list_orders(500)for name, (calls, total) in sorted(stats.items(), key=lambda kv: -kv[1][1]): print(f"{name:14} calls={calls:4} total={total * 1000:6.1f} ms")
Output
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.

Quick check
A production API is slow and you suspect CPU-heavy Python code. Why might you choose py-spy over cProfile?
Need a nudge? A hint rules out a wrong answer.

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 ANALYZE that 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 where OFFSET 100000 has to walk past every skipped row.
  • Batch writes. One INSERT with 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=60 on a response lets browsers and CDNs reuse it without asking you at all. An ETag lets clients revalidate cheaply and get 304 Not Modified.
  • In-process. functools.lru_cache or 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 the pairs0/5 matched

Match each problem to the tool or technique that addresses it.

Choose an item, then its match on the other side.

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:8000

The 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.

Scaling out, and the limit it hits
Load balancer: spreads requestsLoad balancerspreads requestsContainer 1: 4 workersContainer 14 workersContainer 2: 4 workersContainer 24 workersPgBouncer: connection poolerPgBouncerconnection poolerPostgreSQL: max_connectionsPostgreSQLmax_connectionsRedis: shared cacheRedisshared cachepooledpooledfew real conns

Stateless containers behind a load balancer. Need more capacity? Add containers.

1/4

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:

Pythonpool_queue.py
import heapq def simulate(requests, pool_size, query_ms): free_at = [0] * pool_size # when each connection is next free heapq.heapify(free_at) latencies = [] for arrival in requests: start = max(arrival, heapq.heappop(free_at)) # wait for a free connection finish = start + query_ms heapq.heappush(free_at, finish) latencies.append(finish - arrival) return latencies burst = [0] * 20 # 20 requests arrive at the same momentfor pool in (2, 5, 20): lat = simulate(burst, pool, query_ms=100) print(f"pool={pool:2} fastest={min(lat)} ms slowest={max(lat)} ms")
Output
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.

Predict the outputPython

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))
Need a nudge? Hints walk you through it.

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:

locustfile.py
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 5m

Locust'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.

Put it in order5 steps

Order a sound approach to making a slow API faster.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
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.