Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 5 · Lab · 30 min · revision 1

Fixing a slow endpoint under load, one antipattern at a time

Load-test a FastAPI endpoint backed by PostgreSQL with an open-loop generator, find each of four planted antipatterns with a measurement (a py-spy profile, Server-Timing spans, pg_stat_statements and the sessions counter), fix one at a time and compare percentiles, throughput and per-request work after every change.

Contentsand lesson path

What you will learn

  • Recognize data-access antipatterns (chatty I/O, extraneous fetching, busy database, monolithic persistence, no caching) from traces and query metrics, and choose a structural fix for each.
  • Recognize compute and traffic antipatterns (synchronous I/O, improper instantiation, busy front end, noisy neighbor, retry storm) and fix them with non-blocking calls, shared clients and pools, offloading to workers, resource isolation and retry budgets.
  • Locate the bottleneck tier with a load test and distributed traces, then verify a fix with before-and-after latency percentiles, throughput and saturation.

01. Goal and setup

You will run a small order-history API that returns correct answers but hides four antipatterns from the previous lessons. You put it under a fixed load, find one cause with a measurement, fix only that, run the same load again and compare, until the endpoint keeps up comfortably. The rule is the one from lesson 01: no change without a measurement that points at it.

You need Docker, Python 3.12 or later, curl, a bash shell (on Windows, WSL 2) and three terminals. The outputs below come from Docker 29.8.0, the postgres:17-alpine image (PostgreSQL 17.11), Python 3.12.13, FastAPI 0.163.1, uvicorn 0.54.0, httpx 0.28.1, psycopg 3.3.9, psycopg-pool 3.3.3 and py-spy 0.4.3; newer versions should behave the same. Everything listens on 127.0.0.1: the API on port 18730, PostgreSQL on 18731 and a slow exchange-rate service on 18732. The database lives in memory (--tmpfs).

Project layout at the end of step 4
perf-lab/
├── .venv/          Python virtual environment
├── seed.sql        tables and fixed data (step 1)
├── rates.py        the slow exchange-rate service, port 18732 (step 2)
├── app.py          the order-history API under test, port 18730 (step 2)
├── loadgen.py      open- and closed-loop load generator (step 3)
└── hot.py          summarises a py-spy profile (step 4)

02. Step 1: Create the environment and the database

Create the folder and a virtual environment and install the packages. py-spy is a sampling profiler: it reads a running program's Python call stack many times per second.

Terminal 3
mkdir perf-lab && cd perf-lab
python3.12 -m venv .venv  # or python3.13, python3.14: any version from 3.12 up
.venv/bin/python -m pip install -q \
  fastapi uvicorn httpx "psycopg[binary]" psycopg-pool py-spy
.venv/bin/python -c "import sys, fastapi, uvicorn, httpx, psycopg, psycopg_pool
print(sys.version.split()[0], fastapi.__version__, uvicorn.__version__,
      httpx.__version__, psycopg.__version__, psycopg_pool.__version__)"
.venv/bin/py-spy --version
Expected output (newer versions are fine)
3.12.13 0.163.1 0.54.0 0.28.1 3.3.9 3.3.3
py-spy 0.4.3

Save the schema and data as seed.sql: 1,000 customers with 60 orders each and three items per order, without randomness. The pg_stat_statements extension, which counts how often each statement runs, must be preloaded when the server starts; the docker run options below do that and keep statements such as SET out of the counts.

SQL · seed.sql
-- 1,000 customers, 60 orders each, 3 items per order.
-- No randomness, so every run works on the same data.
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
CREATE TABLE customers (id int PRIMARY KEY, name text NOT NULL);
CREATE TABLE orders (
  id          bigint PRIMARY KEY,
  customer_id int NOT NULL REFERENCES customers (id),
  created_at  timestamptz NOT NULL
);
CREATE TABLE order_items (
  order_id    bigint NOT NULL REFERENCES orders (id),
  sku         text NOT NULL,
  qty         int NOT NULL,
  price_cents int NOT NULL
);
INSERT INTO customers SELECT g, 'Customer ' || g FROM generate_series(1, 1000) g;
INSERT INTO orders
SELECT g, (g - 1) % 1000 + 1, timestamptz '2026-01-01' + g * interval '7 minutes'
FROM generate_series(1, 60000) g;
INSERT INTO order_items
SELECT o.id, 'SKU-' || (o.id * 7 + n) % 500, 1 + (o.id + n) % 3,
       500 + (o.id * 13 + n * 101) % 4500
FROM orders o, generate_series(1, 3) n;
CREATE INDEX orders_customer_created ON orders (customer_id, created_at DESC);
CREATE INDEX order_items_order ON order_items (order_id);
ANALYZE;
SELECT (SELECT count(*) FROM customers) AS customers,
       (SELECT count(*) FROM orders) AS orders,
       (SELECT count(*) FROM order_items) AS items;
Terminal 3
docker run -d --name perf-lab-pg -e POSTGRES_PASSWORD=lab -e POSTGRES_DB=shop \
  -p 127.0.0.1:18731:5432 --tmpfs /var/lib/postgresql/data postgres:17-alpine \
  -c shared_preload_libraries=pg_stat_statements \
  -c pg_stat_statements.track_utility=off
for i in $(seq 30); do
  docker exec perf-lab-pg pg_isready -h 127.0.0.1 -U postgres -d shop -q && break
  sleep 1
done
docker exec -i perf-lab-pg psql -X -U postgres -d shop < seed.sql
docker exec perf-lab-pg postgres --version
Expected output (after the container ID that docker prints; a newer 17.x is fine)
CREATE EXTENSION
CREATE TABLE
CREATE TABLE
CREATE TABLE
INSERT 0 1000
INSERT 0 60000
INSERT 0 180000
CREATE INDEX
CREATE INDEX
ANALYZE
 customers | orders | items  
-----------+--------+--------
      1000 |  60000 | 180000
(1 row)

postgres (PostgreSQL) 17.11

03. Step 2: Start the slow dependency and the API

The exchange-rate service stands in for a third-party API: it answers after 100 ms and counts its calls.

Python · rates.py
"""A slow exchange-rate service. It stands in for a third-party API."""

import asyncio

from fastapi import FastAPI

app = FastAPI()
calls = 0


@app.get('/rate/{currency}')
async def rate(currency: str) -> dict:
    global calls
    calls += 1
    await asyncio.sleep(0.1)  # 100 ms, like a call to a service on another continent
    return {'currency': currency, 'rate': 0.92}


@app.get('/calls')
async def count() -> dict:
    return {'calls': calls}

The API returns a customer's 20 newest orders with totals in euros. Each function hides one antipattern; try to name them before you measure. The handler times its three steps in a standard Server-Timing response header, a tiny trace; in production you would record such spans with OpenTelemetry, as in the instrumentation lab.

Python · app.py (the slow version)
"""Order history API. It returns correct answers, but four antipatterns hide in it."""

import json
import time
import urllib.request
from contextlib import asynccontextmanager

import psycopg
from fastapi import FastAPI, Response

DSN = 'postgresql://postgres:[email protected]:18731/shop'
RATES_URL = 'http://127.0.0.1:18732/rate/EUR'


@asynccontextmanager
async def lifespan(app: FastAPI):
    yield  # code before yield runs at start-up, code after it at shutdown


app = FastAPI(lifespan=lifespan)


@asynccontextmanager
async def db():
    conn = await psycopg.AsyncConnection.connect(DSN, autocommit=True)
    async with conn:
        yield conn


async def load_orders(conn: psycopg.AsyncConnection, customer_id: int) -> list[dict]:
    cur = await conn.execute(
        'SELECT id, created_at FROM orders WHERE customer_id = %s'
        ' ORDER BY created_at DESC LIMIT 20',
        (customer_id,),
    )
    orders = []
    for order_id, created_at in await cur.fetchall():
        cur = await conn.execute(
            'SELECT qty, price_cents FROM order_items WHERE order_id = %s', (order_id,)
        )
        items = await cur.fetchall()
        orders.append({
            'id': order_id,
            'created_at': created_at.isoformat(),
            'total_cents': sum(qty * price for qty, price in items),
        })
    return orders


async def get_rate() -> float:
    with urllib.request.urlopen(RATES_URL, timeout=5) as resp:
        return json.load(resp)['rate']


@app.get('/customers/{customer_id}/orders')
async def customer_orders(customer_id: int, response: Response) -> dict:
    spans: dict[str, float] = {}  # step name -> milliseconds, sent as Server-Timing
    start = time.perf_counter()
    async with db() as conn:
        spans['connect'] = (time.perf_counter() - start) * 1000
        start = time.perf_counter()
        orders = await load_orders(conn, customer_id)
        spans['queries'] = (time.perf_counter() - start) * 1000
    start = time.perf_counter()
    rate = await get_rate()
    spans['rates'] = (time.perf_counter() - start) * 1000
    for order in orders:
        order['total_eur'] = round(order['total_cents'] * rate / 100, 2)
    response.headers['Server-Timing'] = ', '.join(
        f'{name};dur={ms:.1f}' for name, ms in spans.items()
    )
    return {'customer_id': customer_id, 'orders': orders}
Terminals 1 and 2
# terminal 1: the slow dependency
.venv/bin/uvicorn rates:app --host 127.0.0.1 --port 18732 --log-level warning
# terminal 2: the API under test (Ctrl+C stops it; run it again after every fix)
.venv/bin/uvicorn app:app --host 127.0.0.1 --port 18730 --log-level warning

A performance fix must not change the answer, so record it now with a check function in terminal 3:

Terminal 3
# terminal 3, inside perf-lab: a check you will repeat after every fix
check() {
  curl -s http://127.0.0.1:18730/customers/7/orders | .venv/bin/python -c "
import json, sys; o = json.load(sys.stdin)['orders']
print(len(o), 'orders; newest:', o[0]['id'], o[0]['created_at'], o[0]['total_eur'])
print('sum of total_eur:', round(sum(x['total_eur'] for x in o), 2))"
}
check
Expected output
20 orders; newest: 59007 2026-10-14T20:09:00+00:00 153.24
sum of total_eur: 3111.93

04. Step 3: Measure the symptom with an open-loop load test

loadgen.py has two modes. The open loop sends requests on a fixed schedule, here 15 per second, whatever the server does, and times each one from the moment it was due. The closed loop runs simulated users who each send a request, wait for the reply and send the next. Its HTTP client is a few lines of asyncio streams, so the generator stays cheap; a generator lag above a few milliseconds means it fell behind its own schedule.

It also reads three counters before and after the run: statement calls from pg_stat_statements, sessions from pg_stat_database and the rate service call count. Divided by the number of requests, they give the work per request.

Python · loadgen.py
"""Load generator for the lab.

  python loadgen.py --rate 30 --seconds 10    open loop: requests leave on a fixed
                                              schedule, timed from when they were due
  python loadgen.py --closed 4 --seconds 10   closed loop: 4 users send, wait, repeat
"""

import argparse
import asyncio
import json
import math
import time

import psycopg

DB = 'postgresql://postgres:[email protected]:18731/shop'
SESSIONS = "SELECT sessions FROM pg_stat_database WHERE datname = 'shop'"
CALLS = """SELECT sum(calls), left(regexp_replace(query, '\\s+', ' ', 'g'), 62)
FROM pg_stat_statements WHERE query NOT LIKE '%pg_stat%' GROUP BY 2 ORDER BY 1 DESC"""
idle: list = []  # open connections to the app, with the time each was last used


async def get(port: int, path: str, reuse: bool = True) -> tuple[dict[str, str], bytes]:
    """A small HTTP/1.1 GET that can reuse connections; cheaper than a full client."""
    conn = None
    while reuse and idle and conn is None:
        reader, writer, used = idle.pop()
        if time.monotonic() - used < 3:  # uvicorn closes connections idle for 5 s
            conn = reader, writer
        else:
            writer.close()
    reader, writer = conn or await asyncio.open_connection('127.0.0.1', port)
    writer.write(f'GET {path} HTTP/1.1\r\nHost: lab\r\n\r\n'.encode())
    head = (await reader.readuntil(b'\r\n\r\n')).decode().split('\r\n')
    headers = dict(line.lower().split(': ', 1) for line in head[1:] if ': ' in line)
    body = await reader.readexactly(int(headers['content-length']))
    if reuse:
        idle.append((reader, writer, time.monotonic()))
    else:
        writer.close()
    if not head[0].startswith('HTTP/1.1 200'):
        raise ValueError(head[0])
    return headers, body


def pct(values: list[float], p: float) -> float:  # nearest-rank percentile
    ordered = sorted(values)
    return ordered[max(0, math.ceil(p / 100 * len(ordered)) - 1)]


async def one(i: int, due: float, out: list) -> None:
    try:
        async with asyncio.timeout(30):
            headers, _ = await get(18730, f'/customers/{i % 1000 + 1}/orders')
        spans = [s.split(';dur=') for s in headers['server-timing'].split(', ')]
        out.append((time.perf_counter() - due, {k: float(v) for k, v in spans}))
    except Exception:  # a timeout, a reset or a bad status: count it as an error
        out.append((time.perf_counter() - due, None))


async def open_loop(rate: float, seconds: float, out: list) -> tuple[float, float]:
    start, tasks, lag = time.perf_counter() + 0.1, [], 0.0
    for i in range(int(rate * seconds)):
        due = start + i / rate  # the schedule never waits for the server
        await asyncio.sleep(max(0.0, due - time.perf_counter()))
        lag = max(lag, time.perf_counter() - due)
        tasks.append(asyncio.create_task(one(i, due, out)))
    await asyncio.gather(*tasks)
    return start, lag


async def closed_loop(users: int, seconds: float, out: list) -> tuple[float, float]:
    start = time.perf_counter()

    async def user(i: int) -> None:
        while time.perf_counter() < start + seconds:
            await one(i, time.perf_counter(), out)  # timed from the actual send
            i += users

    await asyncio.gather(*(user(u) for u in range(users)))
    return start, 0.0


async def rate_lookups() -> int:
    return json.loads((await get(18732, '/calls', reuse=False))[1])['calls']


async def main(args: argparse.Namespace) -> None:
    db = await psycopg.AsyncConnection.connect(DB, autocommit=True)
    await db.execute('SELECT pg_stat_statements_reset()')
    sessions0 = (await (await db.execute(SESSIONS)).fetchone())[0]
    rates0, out = await rate_lookups(), []
    if args.closed:
        print(f'closed loop: {args.closed} users for {args.seconds:g} s')
        start, lag = await closed_loop(args.closed, args.seconds, out)
    else:
        print(f'open loop: {args.rate:g} req/s for {args.seconds:g} s')
        start, lag = await open_loop(args.rate, args.seconds, out)
    elapsed = time.perf_counter() - start
    rates = await rate_lookups() - rates0
    await asyncio.sleep(1.5)  # give PostgreSQL time to publish its session counter
    sessions = (await (await db.execute(SESSIONS)).fetchone())[0] - sessions0
    top = await (await db.execute(CALLS)).fetchall()
    await db.close()
    ok = [(seconds, spans) for seconds, spans in out if spans is not None]
    if not ok:
        print(f'all {len(out)} requests failed: is the API running on port 18730?')
        return
    lat = [seconds * 1000 for seconds, _ in ok]
    print(f'requests {len(out)}, errors {len(out) - len(ok)}, throughput '
          f'{len(ok) / elapsed:.1f} req/s, generator lag {lag * 1000:.0f} ms')
    marks = '  '.join(f'p{p} {pct(lat, p):.0f}' for p in (50, 90, 99))
    print(f'latency ms: {marks}  max {max(lat):.0f}')
    print('server-timing median ms: ' + '  '.join(
        f'{k} {pct([s[k] for _, s in ok], 50):.1f}' for k in ok[0][1]))
    n = len(out)
    print(f'per request: {sum(c for c, _ in top) / n:.2f} queries, '
          f'{sessions / n:.2f} new DB sessions, {rates / n:.2f} rate lookups')
    for calls, query in top[:2]:
        print(f'{calls:>8}  {query}')


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--rate', type=float, default=30)
    parser.add_argument('--seconds', type=float, default=10)
    parser.add_argument('--closed', type=int, default=0)
    asyncio.run(main(parser.parse_args()))
Terminal 3
.venv/bin/python loadgen.py --rate 15 --seconds 10
.venv/bin/python loadgen.py --closed 4 --seconds 10
Illustrative output (timings vary; each per request line should match exactly)
$ .venv/bin/python loadgen.py --rate 15 --seconds 10
open loop: 15 req/s for 10 s
requests 150, errors 0, throughput 8.3 req/s, generator lag 3 ms
latency ms: p50 4615  p90 7573  p99 8250  max 8444
server-timing median ms: connect 624.8  queries 3474.2  rates 102.4
per request: 21.00 queries, 1.00 new DB sessions, 1.00 rate lookups
    3000  SELECT qty, price_cents FROM order_items WHERE order_id = $1
     150  SELECT id, created_at FROM orders WHERE customer_id = $1 ORDER

$ .venv/bin/python loadgen.py --closed 4 --seconds 10
closed loop: 4 users for 10 s
requests 81, errors 0, throughput 7.8 req/s, generator lag 0 ms
latency ms: p50 495  p90 582  p99 672  max 672
server-timing median ms: connect 116.6  queries 288.3  rates 102.8
per request: 21.00 queries, 1.00 new DB sessions, 1.00 rate lookups
    1620  SELECT qty, price_cents FROM order_items WHERE order_id = $1
      81  SELECT id, created_at FROM orders WHERE customer_id = $1 ORDER

Write the symptom down in RED terms: at an offered 15 requests per second the endpoint completes only about 8, without errors, and its median latency is several seconds and growing, because requests arrive faster than they leave and the queue keeps lengthening.

The closed loop reports a p99 under a second against the same server. Four users who wait for each reply cannot send faster than the server answers, so it lowered its own rate and never measured the queue that real arrivals build: coordinated omission, seen directly. From here on, use only the open loop.

05. Step 4: Find the first cause with a profiler

Something saturates at about 8 requests per second. FastAPI runs async def handlers on one event loop per process, which runs one piece of code at a time, so look inside the process. --idle keeps samples in which the thread waits in a system call, such as a socket read; without it py-spy shows only CPU time. --format raw writes one line per call stack. hot.py charges each sample to the deepest app.py function on the stack, and skips samples taken at start-up or while the loop sat idle.

Python · hot.py
"""Summarise a py-spy raw profile: which function in app.py was on the stack most?

  python hot.py profile.txt
"""

import collections
import sys

samples: collections.Counter[str] = collections.Counter()
busy = idle = startup = 0
for line in open(sys.argv[1]):
    stack, _, count = line.rstrip().rpartition(' ')
    frames, n = stack.split(';'), int(count)
    if any(frame.startswith('<module> (app.py:') for frame in frames):
        startup += n  # app.py and its imports loading while the server starts
    elif 'Selector.select (selectors.py:' in frames[-1]:
        idle += n  # the event loop waiting for work: nothing to blame
    else:
        busy += n
        ours = [frame for frame in frames if '(app.py:' in frame]
        # charge each sample to the deepest app.py frame: our code that was running
        samples[ours[-1] if ours else 'outside app.py (server and framework)'] += n
print(f'{busy} samples with the loop busy or blocked '
      f'(not counted: {idle} idle, {startup} at start-up)')
for frame, count in samples.most_common(4):
    print(f'{count / busy:6.1%}  {frame}')
Terminals 2 and 3
# terminal 2: stop the API with Ctrl+C, then start it again under py-spy
.venv/bin/py-spy record --idle --format raw -o blocked.txt -- \
  .venv/bin/uvicorn app:app --host 127.0.0.1 --port 18730 --log-level warning
# terminal 3: as soon as check answers again, start the load
check
.venv/bin/python loadgen.py --rate 15 --seconds 10
# terminal 2: once loadgen.py has printed its results, press Ctrl+C there;
# py-spy stops the API and writes blocked.txt. Then, in terminal 3:
.venv/bin/python hot.py blocked.txt
Illustrative output of hot.py (shares vary; get_rate should be on top)
1838 samples with the loop busy or blocked (not counted: 246 idle, 173 at start-up)
 83.4%  get_rate (app.py:51)
  9.0%  db (app.py:25)
  4.2%  load_orders (app.py:38)
  2.7%  outside app.py (server and framework)

When not idle, the loop was mostly inside get_rate, far more than in the rest of app.py, on urllib.request.urlopen: a blocking network call in an async def function. While it waits 100 ms for the rate service no other request can run, so the process finishes at most about ten requests per second however idle its CPU is. That is synchronous I/O.

06. Step 5: Fix 1, synchronous I/O

In the imports at the top of app.py, delete import json and import urllib.request and add import httpx. Then replace lifespan and get_rate with the code below. The client is created once per process, at start-up, so the fix does not plant a new per-request client.

Python · app.py, replaces lifespan and get_rate
@asynccontextmanager
async def lifespan(app: FastAPI):
    app.state.rates = httpx.AsyncClient(timeout=5.0)  # one client per process
    yield
    await app.state.rates.aclose()


async def get_rate() -> float:
    resp = await app.state.rates.get(RATES_URL)  # await: the loop serves others
    resp.raise_for_status()
    return resp.json()['rate']
Terminals 2 and 3
# terminal 2: start the API again (Ctrl+C first if it is running)
.venv/bin/uvicorn app:app --host 127.0.0.1 --port 18730 --log-level warning
# terminal 3
check
.venv/bin/python loadgen.py --rate 15 --seconds 10
Illustrative output (timings vary; the check lines and the per request line should match exactly)
20 orders; newest: 59007 2026-10-14T20:09:00+00:00 153.24
sum of total_eur: 3111.93

open loop: 15 req/s for 10 s
requests 150, errors 0, throughput 14.9 req/s, generator lag 3 ms
latency ms: p50 150  p90 696  p99 1251  max 1374
server-timing median ms: connect 16.6  queries 13.9  rates 112.7
per request: 21.00 queries, 1.00 new DB sessions, 1.00 rate lookups
    3000  SELECT qty, price_cents FROM order_items WHERE order_id = $1
     150  SELECT id, created_at FROM orders WHERE customer_id = $1 ORDER

Same answer. Throughput matches the offered rate, the queue is gone, and the median fell from seconds to under 200 ms. The counters did not move: the fix changed how the loop waits, not the work per request, so on a slow machine p99 stays high while one core does all that work.

07. Step 6: Fix 2, no caching

With the queue gone, Server-Timing medians show rates at over 100 ms, several times connect or queries, and one lookup per request for a rate that changes a few times a day: no caching. Add import asyncio to the imports and replace get_rate again. The lock makes requests that find it expired wait for one refresh.

Python · app.py, replaces get_rate
_cached = {'rate': 0.0, 'expires': 0.0}
_refresh = asyncio.Lock()


async def get_rate() -> float:
    """Exchange rates change a few times a day, so a value up to 60 s old is fine."""
    if time.monotonic() < _cached['expires']:
        return _cached['rate']
    async with _refresh:  # one refresh at a time; the others wait, then reuse it
        if time.monotonic() >= _cached['expires']:
            resp = await app.state.rates.get(RATES_URL)
            resp.raise_for_status()
            _cached.update(rate=resp.json()['rate'], expires=time.monotonic() + 60)
    return _cached['rate']
Terminals 2 and 3
# terminal 2: Ctrl+C, then start the API again
.venv/bin/uvicorn app:app --host 127.0.0.1 --port 18730 --log-level warning
# terminal 3: no check this time, so the first request finds the cache empty
.venv/bin/python loadgen.py --rate 15 --seconds 10
Illustrative output (timings vary; the per request line should match exactly)
open loop: 15 req/s for 10 s
requests 150, errors 0, throughput 15.1 req/s, generator lag 3 ms
latency ms: p50 28  p90 37  p99 149  max 216
server-timing median ms: connect 13.2  queries 12.5  rates 0.0
per request: 21.00 queries, 1.00 new DB sessions, 0.01 rate lookups
    3000  SELECT qty, price_cents FROM order_items WHERE order_id = $1
     150  SELECT id, created_at FROM orders WHERE customer_id = $1 ORDER

One lookup in 150 requests, and the median dropped below 40 ms. The p99 stayed higher because the first requests after the restart waited for that refresh: the cost of a cold cache, which the stampede lesson reduces by warming and refreshing early. The cache lives in one process; several worker processes each keep their own copy.

08. Step 7: Fix 3, chatty I/O

Now connect and queries are similar; take the queries first, as the statements show the plainer waste: 3,000 calls of the items query for 150 requests, 20 per request, beside one orders query each. That is the N+1 form of chatty I/O. Replace load_orders with a version that fetches the items of all 20 orders at once:

Python · app.py, replaces load_orders
async def load_orders(conn: psycopg.AsyncConnection, customer_id: int) -> list[dict]:
    cur = await conn.execute(
        'SELECT id, created_at FROM orders WHERE customer_id = %s'
        ' ORDER BY created_at DESC LIMIT 20',
        (customer_id,),
    )
    orders = await cur.fetchall()
    cur = await conn.execute(  # one round trip for the items of all 20 orders
        'SELECT order_id, qty, price_cents FROM order_items WHERE order_id = ANY(%s)',
        ([order_id for order_id, _ in orders],),
    )
    totals: dict[int, int] = {}
    for order_id, qty, price in await cur.fetchall():
        totals[order_id] = totals.get(order_id, 0) + qty * price
    return [
        {'id': order_id, 'created_at': created_at.isoformat(),
         'total_cents': totals.get(order_id, 0)}
        for order_id, created_at in orders
    ]
Terminals 2 and 3
# terminal 2: start the API again (Ctrl+C first if it is running)
.venv/bin/uvicorn app:app --host 127.0.0.1 --port 18730 --log-level warning
# terminal 3
check
.venv/bin/python loadgen.py --rate 15 --seconds 10
Illustrative output (timings vary; the check lines and the per request line should match exactly)
20 orders; newest: 59007 2026-10-14T20:09:00+00:00 153.24
sum of total_eur: 3111.93

open loop: 15 req/s for 10 s
requests 150, errors 0, throughput 15.1 req/s, generator lag 4 ms
latency ms: p50 21  p90 27  p99 31  max 45
server-timing median ms: connect 12.2  queries 6.1  rates 0.0
per request: 2.00 queries, 1.00 new DB sessions, 0.00 rate lookups
     150  SELECT order_id, qty, price_cents FROM order_items WHERE order
     150  SELECT id, created_at FROM orders WHERE customer_id = $1 ORDER

Same answer, 2 statements per request instead of 21, and the queries span fell from about 12 ms to 7 ms. On one host round trips are cheap; across a network each of the 19 saved trips saves more.

09. Step 8: Fix 4, improper instantiation

connect is now the largest span, with 1.00 new DB sessions per request: each request pays for a TCP connection, a password exchange and a new PostgreSQL server process, then throws them away. That is improper instantiation. Add from psycopg_pool import AsyncConnectionPool to the imports and replace lifespan, which keeps the HTTP client from step 5, and db. The pool opens four connections at start-up and lends them out.

Python · app.py, replaces lifespan and db
pool = AsyncConnectionPool(DSN, min_size=4, max_size=10, open=False,
                           kwargs={'autocommit': True})


@asynccontextmanager
async def lifespan(app: FastAPI):
    app.state.rates = httpx.AsyncClient(timeout=5.0)  # from step 5
    await pool.open()  # connect once, at start-up
    yield
    await pool.close()
    await app.state.rates.aclose()


def db():
    return pool.connection()  # borrow a pooled connection; it goes back on exit
Terminals 2 and 3
# terminal 2: start the API again (Ctrl+C first if it is running)
.venv/bin/uvicorn app:app --host 127.0.0.1 --port 18730 --log-level warning
# terminal 3
check
.venv/bin/python loadgen.py --rate 15 --seconds 10
Illustrative output (timings vary; the check lines and the per request line should match exactly)
20 orders; newest: 59007 2026-10-14T20:09:00+00:00 153.24
sum of total_eur: 3111.93

open loop: 15 req/s for 10 s
requests 150, errors 0, throughput 15.1 req/s, generator lag 2 ms
latency ms: p50 3  p90 4  p99 10  max 10
server-timing median ms: connect 0.0  queries 1.4  rates 0.0
per request: 2.00 queries, 0.00 new DB sessions, 0.00 rate lookups
     150  SELECT order_id, qty, price_cents FROM order_items WHERE order
     150  SELECT id, created_at FROM orders WHERE customer_id = $1 ORDER

10. Step 9: Measure the headroom

At 15 requests per second the last fix saves only milliseconds; its value shows at a higher rate. Offer more than six times the load the original code could not handle:

Terminal 3
.venv/bin/python loadgen.py --rate 100 --seconds 10
Illustrative output (timings vary; the per request line should match exactly)
open loop: 100 req/s for 10 s
requests 1000, errors 0, throughput 100.1 req/s, generator lag 4 ms
latency ms: p50 3  p90 5  p99 9  max 12
server-timing median ms: connect 0.0  queries 1.4  rates 0.0
per request: 2.00 queries, 0.00 new DB sessions, 0.00 rate lookups
    1000  SELECT order_id, qty, price_cents FROM order_items WHERE order
    1000  SELECT id, created_at FROM orders WHERE customer_id = $1 ORDER
Illustrative summary of the runs above (open loop, 15 requests/s unless stated; the last three columns are per request)
run                       done/s  errors  p50 ms  p99 ms  queries  sessions  lookups
baseline                     8.3       0    4615    8250    21.00      1.00     1.00
fix 1: async rate call      14.9       0     150    1251    21.00      1.00     1.00
fix 2: cache the rate       15.1       0      28     149    21.00      1.00     0.01
fix 3: batch the items      15.1       0      21      31     2.00      1.00     0.00
fix 4: connection pool      15.1       0       3      10     2.00      0.00     0.00
fix 4 at 100 req/s         100.1       0       3       9     2.00      0.00     0.00

Each fix moved the number that pointed at its cause, and each time the bottleneck moved on: the event loop, the dependency, the statements, the connections. When you are done, stop terminals 1 and 2 with Ctrl+C and remove the database:

Terminal 3
# Ctrl+C in terminals 1 and 2, then:
docker rm -f -v perf-lab-pg

11. Check your understanding

Practice check · 3 questions

Reading the lab

Three questions about what you measured.

Q1. After fix 1, the API keeps up with 15 requests per second, yet each request still spends about 100 ms in the `rates` span. Why did making the call non-blocking not shorten that span?
Q2. A teammate repeats step 4 without `--idle`. In their summary, `db (app.py:25)` has the largest share and `get_rate` a much smaller one, so they want to add the connection pool first. What is wrong with their reading?
Q3. You deploy the fixed API as 8 uvicorn worker processes behind one port, and traffic is a steady 400 requests per second. With the cache from fix 2, about how many calls per minute reach the rate service?
Practice only: not graded, not saved, not evidence.

12. Apply it

Finish this skill's practice task with the lab as your sample service:

  1. Write its report: per fix, the antipattern, the measurement that named it, and p50, p99, throughput and database load before and after.
  2. Undo fix 4 only and raise the rate in steps (25, 50, 100, 150 requests per second) until throughput stops following it. Restore fix 4 and repeat. Which resource saturates first each time, and how did you show it?
  3. Make each request hold its connection during a slow call: add await asyncio.sleep(0.1) as the last line inside async with db() as conn:, and a /stats endpoint that returns pool.get_stats(). Restart the API and run 50 requests per second, then restart and run 150. Compare requests_queued and requests_wait_ms, explain the difference with Little's law, and say why moving the slow call out of the block beats a bigger pool.

13. Review prompt

Without looking back: state the original symptom in RED terms and why the closed loop hid it; name the four antipatterns in order, with the measurement that found each and the number each fix changed; explain why fix 1 removed the queue but not the 100 ms wait, and why fix 4 looked small at 15 requests per second.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check