Lab: Prove the Fix, Then Push Past Capacity
Seed PostgreSQL with fixed data, locate a slow query, prove one index fix with before-and-after k6 runs, then add a per-client token bucket (429 with Retry-After) and an in-flight cap (fast 503) and push the service past capacity while health checks stay fast.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Start PostgreSQL and seed the orders
- Step 2: Write the overload guards and test them
- Step 3: Wire the guards into the service
- Step 4: Write a load test that separates outcomes
- Step 5: Measure the baseline and locate the bottleneck
- Step 6: Apply one fix and rerun the same test
- Step 7: Push past capacity with a noisy client
- Step 8: Check recovery after the surge
- Check your understanding
- Apply it
- Review prompt
Lessons of API Performance & Profiling
- Percentiles, Throughput and Little's Law Concept · 20 min
- Lab: A Reproducible Load Test Lab · 30 min
- Profiling a Slow Endpoint Worked example · 25 min
- Targeted Fixes and Overload Guards Concept · 25 min
- Lab: Prove the Fix, Then Push Past Capacity Lab · 30 min
- Check: Diagnose from the Numbers Knowledge check · 8 questions
What you will learn
- Apply one targeted fix (query or index change, pool or worker sizing, payload reduction, caching or moving work to a job) and record before-and-after results.
- Locate a bottleneck with a profiler, database query timings and pool or worker saturation metrics instead of guessing.
- Protect a service from overload with per-client rate limits that answer 429 with Retry-After, caps on concurrent in-flight work, and load shedding that keeps health checks and critical routes responsive, and demonstrate it with a load test past capacity.
01. Goal and setup
You will run an orders service against a seeded PostgreSQL table. First you find why an endpoint is slow and prove one fix with the same load test before and after. Then you give every API key its own rate limit, so a noisy client gets 429 Too Many Requests while others carry on, and exceed the service's capacity to check that the excess gets a quick 503 while admitted requests and the health check stay fast.
You need: Docker, Python 3.12 or later, k6 v1.0 or later and about 300 MB of free memory. Tested with postgres:18-alpine (PostgreSQL 18.6), FastAPI 0.163.1, Uvicorn 0.54.0, psycopg 3.3.9, psycopg-pool 3.3.3 and k6 v2.4.0.
One honest shortcut: after its query, the endpoint waits 40 ms with asyncio.sleep. That stands in for a call to another service, such as a pricing API, which we assume can serve only four calls at a time; the in-flight cap of 4 protects it. This keeps capacity low, about 90 requests per second, so one laptop can exceed it. Timings below come from real runs on one shared machine; compare your own runs with each other.
capacity-lab/
├── seed.sql step 1: 1,000,000 orders, the same on every run
├── guards.py step 2: token bucket and in-flight cap
├── test_guards.py step 2: tests for the token bucket
├── app.py step 3: the orders service
└── benchmark-test.js step 4: the k6 test02. Step 1: Start PostgreSQL and seed the orders
The container keeps its data in memory (--tmpfs). The seed computes every column from the row number, not random(), so the table is identical on every run. There is deliberately no index on customer_id yet.
mkdir capacity-lab && cd capacity-lab
python3 -m venv .venv && source .venv/bin/activate
pip install "fastapi==0.163.1" "uvicorn==0.54.0" "psycopg[binary]==3.3.9" \
"psycopg-pool==3.3.3" pytest
docker run -d --name perf-pg -e POSTGRES_PASSWORD=lab -e POSTGRES_DB=shop \
-p 127.0.0.1:5433:5432 --tmpfs /var/lib/postgresql postgres:18-alpine
# -h 127.0.0.1: wait for the real server, not the one used during set-up
until docker exec perf-pg pg_isready -h 127.0.0.1 -U postgres -q; do sleep 1; done-- 1,000,000 orders for 20,000 customers; no random(), so every run is identical
DROP TABLE IF EXISTS orders;
CREATE TABLE orders (
id bigint PRIMARY KEY,
customer_id integer NOT NULL,
created_at timestamptz NOT NULL,
total_cents integer NOT NULL
);
INSERT INTO orders
SELECT g,
(g * 7919) % 20000 + 1,
timestamptz '2026-01-01 00:00+00' + g * interval '30 seconds',
(g * 37) % 50000 + 100
FROM generate_series(1::bigint, 1000000) AS g;
ANALYZE orders;
SELECT count(*) AS orders, count(DISTINCT customer_id) AS customers,
sum(total_cents) AS sum_cents
FROM orders;docker exec -i perf-pg psql -v ON_ERROR_STOP=1 -U postgres -d shop < seed.sqlNOTICE: table "orders" does not exist, skipping
DROP TABLE
CREATE TABLE
INSERT 0 1000000
ANALYZE
orders | customers | sum_cents
---------+-----------+-------------
1000000 | 20000 | 25099500000
(1 row)03. Step 2: Write the overload guards and test them
A per-client rate limit asks "is this client sending more than its share?" and answers 429 Too Many Requests (RFC 6585). A concurrency cap asks "is the server full right now?" and answers 503 Service Unavailable. Both send Retry-After, the number of seconds a client should wait before trying again (RFC 9110).
The rate limit is a token bucket per API key. Each key starts with 20 tokens; every request spends one, and tokens come back at 20 per second, up to 20. A client can therefore burst 20 requests at once but cannot sustain more than 20 per second. When the bucket is empty, take returns how long until one token is back, rounded up to whole seconds because Retry-After carries an integer. The clock is a parameter, so tests can move time by hand.
The cap is the semaphore from the previous lesson, with one rule: if no slot is free, reject at once instead of waiting in a queue.
"""Overload guards: a per-client token bucket and an in-flight cap."""
import asyncio
import math
import time
class TokenBucket:
"""Each key may make `rate` requests per second, with bursts up to `burst`."""
def __init__(self, rate: float, burst: int, clock=time.monotonic):
self.rate, self.burst, self.clock = rate, burst, clock
self.buckets: dict[str, tuple[float, float]] = {} # key -> (tokens, at)
def take(self, key: str) -> int:
"""Spend one token. Return 0 if allowed, else seconds to wait."""
now = self.clock()
tokens, last = self.buckets.get(key, (self.burst, now))
tokens = min(self.burst, tokens + (now - last) * self.rate) # refill
if tokens >= 1:
self.buckets[key] = (tokens - 1, now)
return 0
self.buckets[key] = (tokens, now)
# Time until one whole token is back, rounded up to whole seconds,
# because Retry-After carries an integer number of seconds
return max(1, math.ceil((1 - tokens) / self.rate))
class InFlightCap:
"""Admit at most `limit` requests at once; never queue the rest."""
def __init__(self, limit: int):
self.sem = asyncio.Semaphore(limit)
def full(self) -> bool:
# Safe without a lock: no await between this check and the acquire
return self.sem.locked()from guards import TokenBucket
class FakeClock:
"""A clock the test moves by hand, so the result never depends on timing."""
def __init__(self):
self.now = 0.0
def __call__(self) -> float:
return self.now
def test_noisy_key_is_limited_and_others_are_not():
clock = FakeClock()
bucket = TokenBucket(rate=20, burst=20, clock=clock)
burst = [bucket.take("noisy") for _ in range(21)]
assert burst[:20] == [0] * 20 # the burst allowance is spent
assert burst[20] == 1 # 21st request: wait 1 s (Retry-After: 1)
assert bucket.take("quiet") == 0 # another key has its own bucket
def test_tokens_refill_over_time():
clock = FakeClock()
bucket = TokenBucket(rate=20, burst=20, clock=clock)
for _ in range(20):
bucket.take("noisy")
assert bucket.take("noisy") == 1
clock.now += 0.05 # 1 token comes back every 1/20 s
assert bucket.take("noisy") == 0
assert bucket.take("noisy") == 1python -m pytest -q -p no:cacheprovider test_guards.py.. [100%]
2 passed in 0.22sThe first test is the negative case: the 21st request in a burst is refused with a one-second wait, and another key is not affected. The second shows that the limit is a rate, not a ban. Both guards keep their state in one Python process; with several workers or instances, each counts separately, so a real deployment keeps the buckets in a shared store such as Redis or limits at the API gateway.
04. Step 3: Wire the guards into the service
The middleware runs before any route, and its order matters. /healthz skips both guards, so the orchestrator sees a live process under load. The rate limit comes next: a client over its quota should be told so even when the server has room. The cap comes last, and both rejections happen before a database connection is taken, so they cost almost nothing. The pool has one connection per slot, so an admitted request never waits for one.
"""Orders service for the capacity lab."""
import asyncio
import os
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from psycopg_pool import AsyncConnectionPool
from guards import InFlightCap, TokenBucket
DSN = os.environ.get("DATABASE_URL", "postgresql://postgres:[email protected]:5433/shop")
DEPENDENCY_MS = int(os.environ.get("DEPENDENCY_MS", "40"))
MAX_IN_FLIGHT = 4 # also the pool size: admitted requests never wait for a connection
pool = AsyncConnectionPool(
DSN, min_size=MAX_IN_FLIGHT, max_size=MAX_IN_FLIGHT, open=False
)
limiter = TokenBucket(rate=20, burst=20) # per API key
cap = InFlightCap(MAX_IN_FLIGHT)
@asynccontextmanager
async def lifespan(app: FastAPI):
await pool.open(wait=True)
yield
await pool.close()
app = FastAPI(lifespan=lifespan)
def problem(status: int, title: str, retry_after: int) -> JSONResponse:
return JSONResponse(
{"title": title, "status": status},
status_code=status,
headers={"Retry-After": str(retry_after)},
media_type="application/problem+json",
)@app.middleware("http")
async def overload_guards(request: Request, call_next):
if request.url.path == "/healthz": # probes skip both guards
return await call_next(request)
# 1. Per-client rate limit: this client is over its own quota
key = request.headers.get("x-api-key") or request.client.host
wait = limiter.take(key)
if wait:
return problem(429, "Rate limit exceeded for this API key", wait)
# 2. Concurrency cap: the server is full, whoever is asking
if cap.full():
return problem(503, "Server at capacity", 1)
async with cap.sem:
return await call_next(request)
@app.get("/healthz")
async def healthz() -> dict:
return {"status": "ok"} # no database call: it must answer under load
@app.get("/api/v1/customers/{customer_id}/orders")
async def recent_orders(customer_id: int) -> dict:
async with pool.connection() as conn:
cur = await conn.execute(
"SELECT id, created_at, total_cents FROM orders WHERE customer_id = %s"
" ORDER BY created_at DESC LIMIT 20",
(customer_id,),
)
rows = await cur.fetchall()
await asyncio.sleep(DEPENDENCY_MS / 1000) # stands in for a pricing-service call
return {"customer_id": customer_id, "orders": [r[0] for r in rows]}uvicorn app:app --host 127.0.0.1 --port 8000 --no-access-logcurl -s http://127.0.0.1:8000/healthz; echo
curl -s -H "X-API-Key: demo" http://127.0.0.1:8000/api/v1/customers/42/orders \
| python3 -m json.tool | head -5{"status":"ok"}
{
"customer_id": 42,
"orders": [
984839,
964839,05. Step 4: Write a load test that separates outcomes
During overload, most responses are rejections that take about a millisecond. Mixed with successes in one http_req_duration, they drag the percentiles down and hide slow successes. So the script records each outcome in its own custom Trend metric: admitted_duration (200), limited_duration (429) and shed_duration (503), and count in summaryTrendStats shows how many of each.
The users scenario rotates over 50 API keys; even at 200 requests per second each key sends only 4 per second, under its quota. The optional noisy scenario sends all its requests with one key. The health scenario calls /healthz five times a second. A 5-second warm-up runs first and never counts, because every threshold is scoped to a scenario tag. RATE and NOISY_RATE come from -e options.
import http from "k6/http";
import { check } from "k6";
import exec from "k6/execution";
import { Trend } from "k6/metrics";
const BASE_URL = __ENV.BASE_URL || "http://127.0.0.1:8000";
const RATE = Number(__ENV.RATE || 20); // well-behaved traffic, req/s
const NOISY_RATE = Number(__ENV.NOISY_RATE || 0); // one client over its quota
// One Trend per outcome, so fast rejections cannot hide slow successes
const admitted = new Trend("admitted_duration", true);
const limited = new Trend("limited_duration", true); // 429
const shed = new Trend("shed_duration", true); // 503
function arrival(rate, fn, startTime, duration) {
return {
executor: "constant-arrival-rate", exec: fn, rate, timeUnit: "1s",
startTime, duration, preAllocatedVUs: 50, maxVUs: 200,
};
}
const scenarios = {
warmup: arrival(Math.max(1, RATE / 5), "users", "0s", "5s"),
users: arrival(RATE, "users", "5s", "20s"),
health: arrival(5, "health", "5s", "20s"),
};
if (NOISY_RATE > 0) scenarios.noisy = arrival(NOISY_RATE, "noisy", "5s", "20s");export const options = {
scenarios,
summaryTrendStats: ["count", "p(50)", "p(95)", "p(99)", "max"],
thresholds: {
"admitted_duration{scenario:users}": ["p(95)<70", "p(99)<150"],
"shed_duration{scenario:users}": ["p(95)<20"], // rejections must be cheap
"http_req_duration{scenario:health}": ["p(95)<20"],
"http_reqs{scenario:users,status:429}": ["count==0"], // quiet keys never limited
},
};
if (NOISY_RATE > 0) {
// The noisy key must hit its own limit; the count shows in the summary
options.thresholds["http_reqs{scenario:noisy,status:429}"] = ["count>0"];
}
function record(res) {
check(res, {
"200, 429 or 503": (r) => [200, 429, 503].includes(r.status),
"rejections carry Retry-After": (r) =>
r.status === 200 || r.headers["Retry-After"] !== undefined,
});
const trend = { 200: admitted, 429: limited, 503: shed }[res.status];
if (trend) trend.add(res.timings.duration);
}
function getOrders(apiKey) {
const customer = (exec.scenario.iterationInTest * 7) % 20000 + 1;
const url = `${BASE_URL}/api/v1/customers/${customer}/orders`;
record(http.get(url, { headers: { "X-API-Key": apiKey } }));
}
// 50 quiet keys: at 200 req/s each key sends 4 req/s, under its 20 req/s quota
export function users() { getOrders(`user-${exec.scenario.iterationInTest % 50}`); }
export function noisy() { getOrders("noisy-1"); }
export function health() { http.get(`${BASE_URL}/healthz`); }The thresholds are the goal for this endpoint: admitted requests p95 under 70 ms and p99 under 150 ms, rejections p95 under 20 ms, the health check p95 under 20 ms, and no 429 for the quiet keys. k6 tags every request with status, so http_reqs{scenario:users,status:429} counts exactly those.
06. Step 5: Measure the baseline and locate the bottleneck
k6 run --quiet -e RATE=20 benchmark-test.js admitted_duration{scenario:users}
✗ 'p(95)<70' p(95)=85.82ms
✓ 'p(99)<150' p(99)=107.25ms
...
admitted_duration....: count=421 p(50)=73.25ms p(95)=85.82ms p(99)=107.23ms
{ scenario:users }.: count=400 p(50)=73.12ms p(95)=85.82ms p(99)=107.25ms
shed_duration........: count=0 p(50)=0s p(95)=0s p(99)=0sAt only 20 requests per second the p95 misses its goal. Then check shed_duration. In the run above it is count=0, and the 40 ms wait is about half the 73 ms median. On a slower or busier machine you may instead see hundreds of 503s even at this low rate, because each slow query holds one of the four slots for longer. Either way the guards react to the slow query; they do not cause it. Ask the database where the time goes:
docker exec perf-pg psql -U postgres -d shop -c "EXPLAIN (ANALYZE, BUFFERS)
SELECT id, created_at, total_cents FROM orders WHERE customer_id = 42
ORDER BY created_at DESC LIMIT 20;" Limit (actual time=48.007..54.147 rows=20.00 loops=1)
-> Gather Merge (actual time=48.005..54.141 rows=20.00 loops=1)
Workers Launched: 2
-> Sort (actual time=42.819..42.821 rows=13.67 loops=3)
-> Parallel Seq Scan on orders (... rows=16.67 loops=3)
Filter: (customer_id = 42)
Rows Removed by Filter: 333317
Execution Time: 54.248 msThree processes each read a third of the table, discarding 333,317 rows each, to find 50 orders: a sequential scan that grows with the table, not with the result.
07. Step 6: Apply one fix and rerun the same test
Add one index that matches the query: equality on customer_id, then order by created_at. Change nothing else, so any difference comes from this index. Then repeat the EXPLAIN from step 5 and the same k6 command.
docker exec perf-pg psql -U postgres -d shop \
-c "CREATE INDEX idx_orders_cust ON orders (customer_id, created_at);"
k6 run --quiet -e RATE=20 benchmark-test.jsCREATE INDEX
-> Index Scan Backward using idx_orders_cust on orders (... rows=20.00 loops=1)
Execution Time: 0.330 ms
...
admitted_duration{scenario:users}
✓ 'p(95)<70' p(95)=45.75ms
✓ 'p(99)<150' p(99)=47.09ms
...
{ scenario:users }.: count=400 p(50)=43.72ms p(95)=45.75ms p(99)=47.09msRecord the pair (same rate, data and machine): p50 73 → 44 ms, p95 86 → 46 ms, p99 107 → 47 ms, 400 admitted requests in both. Had you also changed the pool size in this cycle, the pair could not tell you which change helped.
08. Step 7: Push past capacity with a noisy client
By Little's law, a cap of 4 slots with about 44 ms per request admits at most 4 ÷ 0.044 ≈ 90 requests per second. Now send 200 per second from the quiet keys, more than twice that, plus 40 per second from one noisy key whose quota is 20.
k6 run --quiet -e RATE=200 -e NOISY_RATE=40 benchmark-test.js admitted_duration{scenario:users}
✓ 'p(95)<70' p(95)=45.52ms
✓ 'p(99)<150' p(99)=47.65ms
http_req_duration{scenario:health}
✓ 'p(95)<20' p(95)=4.41ms
http_reqs{scenario:noisy,status:429}
✓ 'count>0' count=381
http_reqs{scenario:users,status:429}
✓ 'count==0' count=0
shed_duration{scenario:users}
✓ 'p(95)<20' p(95)=1.5ms
...
✓ rejections carry Retry-After
admitted_duration....: count=1967 p(50)=43.37ms p(95)=45.62ms p(99)=47.62ms
{ scenario:users }.: count=1679 p(50)=43.31ms p(95)=45.52ms p(99)=47.65ms
limited_duration.....: count=381 p(50)=1.01ms p(95)=2.08ms p(99)=3.45ms
shed_duration........: count=2654 p(50)=825.05µs p(95)=1.71ms p(99)=2.69ms
{ scenario:users }.: count=2322 p(50)=800.35µs p(95)=1.5ms p(99)=2.64msRead it by outcome:
- The noisy key got 381 responses with
429: of its 800 requests, only its 20-token burst and 20 per second passed the limiter. Quiet keys got no 429: one client's excess used nobody else's quota. - Of the roughly 4,000 quiet requests (4,001 in this run), 1,679 were admitted and 2,322 were shed with
503, about 84 admitted per second, close to the 90 that Little's law predicted. - Admitted requests kept the same p95 as at 20 requests per second (46 ms), because the cap never let more than four run at once.
- Rejections took about a millisecond, the health check stayed under 5 ms at p95, and every rejection carried
Retry-After.
Without the cap, all 240 requests per second would queue at a pricing service that serves four at a time, slowing every client and causing retries.
09. Step 8: Check recovery after the surge
After the surge, the service must also return to normal without a restart. Rerun the normal load at once, with Uvicorn still running.
k6 run --quiet -e RATE=20 benchmark-test.js admitted_duration{scenario:users}
✓ 'p(95)<70' p(95)=46.4ms
✓ 'p(99)<150' p(99)=48.41ms
...
shed_duration........: count=0 p(50)=0s p(95)=0s p(99)=0sThe latencies match the post-fix run and nothing is shed (0s means no samples). When you are done, stop Uvicorn with Ctrl+C and run docker rm -f perf-pg.
10. Check your understanding
11. Apply it
This lab is the second half of the skill project. On your own service:
- Profile the slowest endpoint, apply one fix, and attach before-and-after summaries (same rate, same seeded data) to the pull request.
- Add a per-client limit keyed on whatever identifies a client in your API (API key, account, token), with the counts in a shared store if you run more than one process.
- Size the in-flight cap from Little's law and your measured time per request, and keep health checks outside it and free of database calls.
- Push past capacity and report admitted, limited and shed counts and latencies separately, plus health check latency and a recovery run.
- Make your clients honour
Retry-Afterand add random jitter; many HTTP libraries do not by default.
12. Review prompt
Without looking back, explain how you proved that the index, and nothing else, made the endpoint faster. Describe how a token bucket decides between 200 and 429 and how it computes Retry-After, why the rate limit and the in-flight cap return different status codes, and which four numbers from the stress run show that the overload protection worked.
References
- Grafana k6 documentation: Create custom metrics
- Grafana k6 documentation: Stress testing
- RFC 6585, section 4: 429 Too Many Requests
- RFC 9110, section 10.2.3: Retry-After
- Amazon Builders' Library: Using load shedding to avoid overload
- PostgreSQL documentation: Using EXPLAIN
- Kubernetes documentation: Configure liveness, readiness and startup probes
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.