Part 01 · Thinking About Scale

Finding the Bottleneck

CPUMemoryI/ODatabasedocker stats

The shop is slow at 500 RPS. Find the one resource that's saturated before changing anything.

⏱ 9 min · Station 5 of 93

The problem

At 550 requests per second the shop's p95 climbs to about 60 ms, and a little past 600 it breaks. Three people have three fixes ready: "add app servers", "move to a bigger database server", "rewrite the product page in a faster language". At most one of them is right, and two of them cost real money.

Before changing anything, find out which resource runs out first. That resource is the bottleneck, and it's the only place where adding capacity helps.

The idea

Every request passes through a chain of resources: the app's CPU, its connection pool, the network, the database's CPU, its disk, its locks. The system can't go faster than the slowest link at that load. Finding it is a short, repeatable method:

  1. Reproduce the slowness with a load test at the rate where it hurts.
  2. Look at utilization of each resource while the test runs: which one is near 100%?
  3. Look for saturation: where is work waiting? (Requests queued in front of something, connections waiting for a pool, a CPU run queue.)
  4. Drill into the busy resource: which work is using it? For a database, which queries take the most total time?
  5. Confirm it: remove or relieve that bottleneck and run the same test. If capacity jumps, you found it. If not, keep looking.

Systems engineers call steps 2 and 3 the USE method: Utilization, Saturation, Errors, for every resource.

How it works

In the lab, two tools cover most of it:

  • docker stats shows each container's CPU and memory right now. Since each container is pinned to one CPU thread, 100% means that thread is full.
  • pg_stat_statements, a PostgreSQL extension, keeps a running total for every distinct query: how many times it ran, total time, average time. Sorting by total time (not average) shows what the database spends its life on. A 50 ms query called 10 times matters less than a 2 ms query called 16,000 times.

What to expect from each kind of bottleneck:

What's fullWhat you see
App CPUapp container near 100%, database mostly idle
Database CPUdatabase near 100%, app idle and waiting on queries
Connection poolneither CPU full, requests waiting for a connection
Disklow CPU, high I/O wait, slow queries that read a lot
Locklow CPU everywhere, a few rows everyone updates, queries waiting on each other

Our shop is designed to hit the second row first.

Predict first

At 550 requests/s the shop's p95 is 59 ms. Which change raises its capacity the most?

Visual

k6loadshop apiGo, 1 CPU threadPostgreSQL1 CPU threadCPU 12%CPU 85%CPU 24%CPU 32%waitwaitwait550 req/s1200 req/s95% of db time: one query+ index on (category, sold)550/s: the app is mostly idle, the database CPU is nearly fullrequests queue in front of the database: p95 59 msfix the bottleneck: 1200/s with p95 1.6 ms, database at 32%
CPU of each part under load. At 550 requests/s the database's one CPU thread is nearly full and requests wait in front of it, while the app sits at 12%. After one index: 1,200 requests/s, database at 32%.

Common misconception

"The slow part is the code that runs on every request." The code that runs everywhere is the code you see, so it gets blamed. In our shop the Go handler, the JSON encoding and the HTTP server together use 12% of one CPU at 550 requests per second. The time goes into one database query that the code merely calls.

"Look at the slowest query." The slowest single query is often a rare report. What limits throughput is the query with the highest total time: calls × average. Ours averages only 2.4 ms, but runs on every page view.

Try it

Measured on the lab (Intel i3-10110U, 4 threads, 7 GB RAM; PostgreSQL and the shop each pinned to one CPU thread).

find.sh turns on pg_stat_statements, warms up, resets the statistics, runs 30 seconds at 550 requests per second, takes one docker stats sample halfway, and then lists the three queries with the most total time:

cd ../../lab
psql() { docker compose exec -T db psql -U shop -q "$@"; }
psql -c "CREATE EXTENSION IF NOT EXISTS pg_stat_statements" -c "SELECT pg_stat_statements_reset()" >/dev/null
./k6.sh product.js -e RATE=80 -e DURATION=20s >/dev/null 2>&1   # warm up
psql -c "SELECT pg_stat_statements_reset()" >/dev/null
echo '$ ./k6.sh product.js -e RATE=550 -e DURATION=30s   (and, 15 s in, docker stats)'
./k6.sh product.js -e RATE=550 -e DURATION=30s 2>/dev/null &
sleep 15
docker stats --no-stream --format 'table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}' syslab-api-1 syslab-db-1
wait
echo
echo '$ psql: top queries by total time'
psql -c "SELECT calls, round(total_exec_time)::int AS total_ms, round(mean_exec_time::numeric, 2) AS mean_ms,
                round(100 * total_exec_time / sum(total_exec_time) OVER ())::int AS pct,
                left(regexp_replace(query, '\s+', ' ', 'g'), 60) AS query
           FROM pg_stat_statements WHERE query ILIKE '%products%' OR query ILIKE '%reviews%'
          ORDER BY total_exec_time DESC LIMIT 3"
$ ./k6.sh product.js -e RATE=550 -e DURATION=30s   (and, 15 s in, docker stats)
NAME           CPU %     MEM USAGE / LIMIT
syslab-api-1   11.85%    17.5MiB / 256MiB
syslab-db-1    84.65%    112.1MiB / 512MiB
requests   16465 (548.8/s)
failed     0.00%
latency    avg 11 ms  p50 2.0 ms  p95 59 ms  p99 112 ms  max 186 ms
dropped    36 (k6 could not start them in time)
vus max    69

$ psql: top queries by total time
 calls | total_ms | mean_ms | pct |                            query                            
-------+----------+---------+-----+--------------------------------------------------------------
 16465 |    39460 |    2.40 |  95 | SELECT id, name, price FROM products WHERE category = $1 AND
 16465 |     1337 |    0.08 |   3 | SELECT coalesce(avg(rating), 0)::float8, count(*) FROM revie
 16465 |      839 |    0.05 |   2 | SELECT name, category, price, stock FROM products WHERE id =
(3 rows)

Reading it:

  • docker stats: database 85%, app 12%. The app's thread is mostly idle, waiting on the database. (The sample is one instant; 85% at that moment, close to full on average.)
  • p95 59 ms and 36 dropped iterations: requests are already queueing.
  • One query is 95% of the database's time: the "customers also bought" query, 16,465 calls at 2.4 ms each, 39 seconds of CPU in a 30-second test. The other two queries together are 5%.

So the bottleneck is the database CPU, and almost all of that is one query. Now confirm it. confirm.sh adds an index that lets PostgreSQL read the 8 best sellers of a category directly instead of scanning all 20,000 products, re-runs the ramp, and removes the index again at the end:

cd ../../lab
psql() { docker compose exec -T db psql -U shop -q "$@"; }
echo '$ psql -c "CREATE INDEX products_category_sold ON products (category, sold DESC)"'
psql -c "CREATE INDEX products_category_sold ON products (category, sold DESC)"
./k6.sh product.js -e RATE=80 -e DURATION=10s >/dev/null 2>&1
./ramp.sh product.js "550 800 1000 1200" 20s
echo
echo '$ docker stats during 1200/s'
./k6.sh product.js -e RATE=1200 -e DURATION=20s >/dev/null 2>&1 &
sleep 10
docker stats --no-stream --format 'table {{.Name}}\t{{.CPUPerc}}' syslab-api-1 syslab-db-1
wait
psql -c "DROP INDEX products_category_sold"   # back to the slow page for the next lessons
$ psql -c "CREATE INDEX products_category_sold ON products (category, sold DESC)"
 rate  got/s      p50      p95      p99  failed  dropped
  550     550   0.4 ms   1.1 ms   3.1 ms   0.0%       0
  800     800   0.4 ms   1.0 ms   3.5 ms   0.0%       0
 1000    1000   0.4 ms   1.2 ms   4.8 ms   0.0%       0
 1200    1200   0.6 ms   1.6 ms   8.8 ms   0.0%       0

$ docker stats during 1200/s
NAME           CPU %
syslab-api-1   23.80%
syslab-db-1    32.07%
Without the indexWith the index
Capacityabout 560/smore than 1,200/s (we stopped there)
p95 at 550/s59 ms1.1 ms
Database CPU85% at 550/s32% at 1,200/s

Confirmed: relieve the bottleneck and capacity more than doubles, p95 drops 50 times. At 1,200 per second nothing is close to full anymore; the next bottleneck will show up at a higher rate.

We drop the index at the end on purpose. The caching and load-balancing lessons need a product page that is expensive to build, and Part 5 (Scaling the Database) comes back to indexing properly.

Trade-offs

  • Measuring takes minutes; guessing wrong takes weeks. Each of the three "obvious" fixes would have cost more than this whole lesson and done nothing.
  • Bottlenecks move. Fix one and the next one appears at a higher load. Re-run the method after every change instead of assuming the old answer still holds.
  • pg_stat_statements has a small cost (a few percent at most) and is on in most production PostgreSQL setups. Its numbers are cumulative, so reset or compare snapshots around a test.
  • One sample of docker stats is a snapshot. Good for a first look; for real decisions use metrics over time (the Reliability course sets up Prometheus and Grafana).

Key takeaway

Find the bottleneck before you scale: reproduce the load, check utilization and saturation of each resource, find which work uses the full one, and confirm by relieving it. Adding capacity anywhere else costs money and changes nothing.

Practice

Objective: find a different bottleneck with the same method.

Challenge: the shop's /work?ms=5 endpoint burns 5 ms of CPU in the app and never touches the database. Predict its capacity and which container fills up. Then ramp it: ./ramp.sh product.js "100 150 180 220" 20s -e PATH_TPL="/work?ms=5", and take a docker stats sample at the highest rate.

Expected result: a capacity number you predicted before running, and a docker stats line that shows which container is the bottleneck.

Hint 1

Which resource does each request use, and how much of it?

Hint 2

The app has one CPU thread. 5 ms of CPU per request means at most how many requests per second?

Hint 3

1,000 ms / 5 ms = 200. Expect the cliff a little before it, because the HTTP handling itself also costs some CPU.

Solution
 rate  got/s      p50      p95      p99  failed  dropped
  100     100   5.3 ms   5.4 ms   5.8 ms   0.0%       0
  150     150   5.2 ms   5.3 ms   5.5 ms   0.0%       0
  180     180   5.1 ms   5.3 ms   6.0 ms   0.0%       0
  220     197   711 ms  1271 ms  1296 ms   0.0%     206

$ docker stats during 220/s
NAME           CPU %
syslab-api-1   100.70%
syslab-db-1    0.00%

Up to 180 requests per second, p95 stays at about 5.3 ms: just the work. At 220, only 197 got through, p95 is 1.3 seconds, and the app container is at 100% CPU while the database does nothing. The capacity is just under 200 per second, as predicted from 1,000 / 5. Here the bottleneck is the app's CPU, so adding app servers would help: that's exactly what Part 2 does.

Interview check

Q: Your API's p95 latency doubled at peak. Walk me through how you'd find the cause.

Model answer

First reproduce or observe it at peak load, then go resource by resource: CPU, memory, connection pools, database, network, any downstream service. For each, check utilization and saturation (is something near 100%, is work waiting in a queue). Once I see the full resource, I drill into what uses it: the top queries by total time, a CPU profile of the app, the slowest dependency in traces. Then I confirm by relieving it (an index, a cache, more capacity at that point) and re-running the same load. I don't add servers before I know the bottleneck.

Q: Why sort database queries by total time rather than by average time?

Model answer

Throughput is limited by where the database spends its time overall. Total time = calls × average, so a cheap query that runs on every page view can dominate, while a slow query that runs once an hour barely matters for capacity. The slow rare query might matter for its own users' latency, but it's not what makes the whole system fall over.

Station stamp

Finish the chapter

Done reading? Press Complete to save your progress. XP is Pro-only — on Pro this chapter is worth +10 XP.

Go Pro to earn XP →