ealeng

Episode 05 of 55 · Queues and capacity

More workers, same speed: the GIL, lock ceilings and the bottleneck

32 threads finished no more requests a second than 1. A locked database row stopped at about 275 a second however many workers it got. And making half of a two-stage pipeline twice as fast changed almost nothing. Three ways adding workers fails, the one rule behind the lock (1 ÷ time inside it), and how to find the bottleneck by looking at how busy each stage is and where requests wait.

Lab 03 · Queues, Utilization and Capacity14 min read
Video transcript7:32

0:00Cold open

0:01

I gave my service thirty-two workers instead of one.

0:06

It finished no more requests per second. Not one more.

0:11

Then I made half of the work twice as fast.

0:15

Almost nothing changed. Why?

0:20Intro

0:21

Hands-on system design, part five.

0:25

Today: why more workers can add nothing, and how to find the part that’s really slow.

0:31Meet Lucía

0:32

I’m Lucía, a platform engineer.

0:35

Last time, I worked out how many workers my service needs.

0:40

Today’s question: when does adding workers stop helping?

0:45

Picture a sandwich shop. Each order is a request. Each cook is a worker.

0:51

The number that matters is how many orders the shop finishes each second. That’s called throughput.

0:58

To measure it, I keep every cook busy: two customers per cook, so no cook ever waits for an order.

1:0701 · What you need

1:08

To run it yourself: Python with a few packages, Docker for the app and its database, and a setup script.

1:16

The tests check the math against simulations. They take a few seconds.

1:22

No cloud, and no API keys.

1:2702 · More cooks

1:28

First test: work that keeps a cook busy the whole time. Pure computing, no waiting.

1:34

With one worker, the shop finished about one hundred eighty orders a second.

1:40

So with thirty-two workers, what do you think happened?

1:46

Nothing. About one hundred seventy a second. No faster than one worker.

1:53

These workers were threads: helpers inside one Python program.

1:5903 · One knife

2:00

Think of a kitchen with thirty-two cooks and only one knife. Only the cook holding the knife can work.

2:08

In Python, that knife is called the GIL. Only one thread at a time can run Python code.

2:15

The fix: separate Python programs, called processes. Each one has its own knife.

2:2304 · A knife each

2:24

Same work, now with processes.

2:28

Eight workers finished about nine hundred sixty a second. Five times as many as one.

2:35

After that, each extra worker added less and less. Thirty-two reached about thirteen hundred.

2:43

Each point is a single run, so a dip like the one at sixteen can be noise.

2:49

So more workers helped here, a lot, but not forever. Past twelve, something else became the limit.

2:5705 · One order book

2:59

Third test: work that changes one shared row in the database.

3:04

First, ten milliseconds of waiting, like calling another service. It shares nothing.

3:11

Then it updates one row. From here on, that row is locked: no one else can change it.

3:18

Inside the lock, it waits one millisecond.

3:22

And the commit, which saves the change, lets go of the lock.

3:27

In the sandwich shop, it’s one order book. Every order gets written in it, one cook at a time.

3:3506 · The ceiling

3:37

With one worker: about sixty orders a second.

3:41

With eight: about two hundred eighty.

3:45

And then it stopped. Twelve, sixteen, thirty-two workers: still about two hundred seventy-five.

3:53

Why there? Only one request can hold the lock at a time.

3:5907 · One millisecond?

4:00

If each request held it for one millisecond, the shop could do a thousand a second.

4:07

So I timed it. Each request held the lock for three point seven milliseconds. Not one.

4:15

Most of that was the one-millisecond wait. Timed on its own from the laptop, it took three and a half.

4:23

One second, divided by three point six five milliseconds: about two hundred seventy-four a second. Right at the ceiling.

4:32

However many workers you add, you can’t beat one divided by the time inside the lock.

4:4008 · Three answers

4:42

So, three kinds of work, and adding workers did three different things.

4:47

Threads: nothing, because there’s one knife. The fix is processes.

4:53

Processes: a lot, up to a point.

4:56

The locked row: nothing past eight workers. The fix is less time inside the lock, not more workers.

5:0509 · Two stations

5:07

Now a shop with two stations. Every order goes through both, one after the other.

5:13

Station A makes the sandwich. Four cooks, each with their own knife.

5:19

Station B toasts it: a toaster with only two slots. Toasting is just waiting.

5:26

I kept the shop full of orders. It finished about four hundred a second.

5:31

You want more. Which station would you make faster?

5:3810 · The wrong station

5:39

First, I made the cooks twice as fast.

5:43

About four hundred fifteen a second. Barely different.

5:48

Then I made the toaster twice as fast instead.

5:52

Eight hundred twenty-six a second. Double.

5:57

Four cooks can make twice as many sandwiches as two slots can toast. So the toaster sets the pace for the whole shop. It’s the bottleneck.

6:0811 · Find it without guessing

6:10

I found it by trying both. But you can find a bottleneck without changing anything.

6:16

Sign one: it’s the busiest station. The toaster was busy ninety-seven percent of the time. The cooks, less than half.

6:25

Sign two: it’s where orders wait. Sixty-eight milliseconds in front of the toaster. Almost nothing in front of the cooks.

6:34

Now both stations are nearly full: cooks ninety-eight percent busy, toaster ninety-six. The cooks became a limit too.

6:44

Fix one bottleneck, and the next one shows up.

6:49Back to Lucía

6:51

So, before I add workers, I ask three questions.

6:55

Is there one knife? Pure Python work in threads won’t go faster. Use processes.

7:02

Is there one order book? Time the lock. One second divided by that time is the ceiling.

7:09

Which station is the bottleneck? The busiest one, with orders waiting in front of it. Speed up only that.

7:17

More workers help only at the slowest station, and only if they can really work at the same time.Lucía: Find the bottleneck first.

7:24Summary

7:26

One knife, one order book, and the slowest station.

Key takeaways

  • ✓Throughput is requests finished per second. Measure it by keeping every worker busy: here a closed loop with 2 clients per worker, 8 seconds per point.
  • ✓Pure-Python computing in threads didn't scale at all: about 180 a second with 1 thread, 171 with 32, never more than 2% above one thread. Python's GIL lets only one thread run Python code at a time. The same work in separate processes did 5.3× at 8 workers.
  • ✓Processes scaled, but not forever: 959 a second at 8 workers, 1,258 at 12, 1,313 at 32 (12 → 32 added 4%). Each point is one run on a busy laptop, so the dip to 1,112 at 16 can be noise.
  • ✓A locked row capped throughput at about 274 a second from 8 workers on. The code asked for 1 ms inside the lock (a 1,000 a second ceiling), but each request held it 3.65 ms. However many workers you add, throughput can't pass 1 ÷ (time inside the lock). The fix is a shorter critical section, not more workers.
  • ✓A pipeline runs at the speed of its slowest stage. Speeding up the stage that wasn't the bottleneck moved throughput from 402 to 415 a second (noise); speeding up the bottleneck doubled it, to 826.
  • ✓Find the bottleneck without changing anything: it's the busiest stage (97% against 46%) and the one requests wait in front of (68 ms against 0.2 ms). Fix it and the next one shows up: the other stage went to 98% busy.
  • ✓Predict from service times measured under load. Times measured on an idle system made the toaster-like stage look 118% busy, which is impossible; with loaded times every prediction was within 5%.

The usual fix for a slow service is more workers. This chapter measures when that works and when it does nothing. The short version: 32 threads were no faster than 1, a locked database row stopped at the same rate past 8 workers, and making half of a pipeline twice as fast bought nothing until the right half was picked. Each failure has a different cause and a different fix, and each can be found by measuring rather than guessing.

The examples come from Lab 03 (Queues, Utilization and Capacity) of the system design labs, scripts 03_scaling.py (throughput as workers are added, for three kinds of work) and 04_bottleneck.py (a two-stage pipeline). The same lab's queueing models, the knee and the capacity plan (scripts 01, 02 and 05) are in Chapter 4. The setup is the same laptop as before (an Apple M4 Max, 16 cores, Docker Desktop with 16 virtual CPUs): a Python web app (FastAPI) with Postgres, both in Docker, and the load generator on the same machine. Other work kept the laptop busy during these runs (its load average, the number of processes wanting a core, was about 18 at the end of the scaling run), so the numbers are noisier than on a quiet machine. Read the shapes, not the last digit.

Throughput, measured by keeping every worker busy

Throughput is how many requests the service finishes each second. A worker is whatever runs one request at a time: a thread, a process, or a slot in a pool. The question is what each extra worker adds.

To measure the most a setup can do, every worker has to have work at all times. The lab uses a closed loop: a fixed number of clients, each sending its next request as soon as the last one returns. With 2 clients per worker, a worker never waits for a request to arrive. Each point runs 2 seconds of warm-up, then 8 seconds measured, at 1, 2, 4, 8, 12, 16, 24 and 32 workers, for three kinds of work:

Work What one request does
CPU work, threads 5 ms of pure-Python computing, in a pool of threads inside one Python process
CPU work, processes the same 5 ms, in a pool of separate Python processes
A locked row 10 ms of waiting that shares nothing (like calling another service), then an update to one database row, a 1 ms wait while holding its lock, and the commit
Workers CPU, threads CPU, processes A locked row
1 180 181 62
2 182 356 129
4 163 638 256
8 162 959 284
12 161 1,258 271
16 176 1,112 277
24 174 1,250 275
32 171 1,313 272

Requests a second, one run per cell. Three kinds of work, three different answers.

Try it · More workers, three kinds of workLab 03 · 03_scaling.py · 2 clients per worker, 8 s per point

5 ms of pure-Python computing per request, run in a pool of threads inside one Python process.

Workers

Requests a second
171
× one worker
0.95×
Step from 24 to 32
-1%
02004006008001,0001,2001,400124812162432
Measured If every worker added as much as the first

Flat: 180 a second with 1 thread, 171 with 32, and never more than 182. Only one thread at a time can run Python code (the GIL), so 32 threads take turns on one core's worth of work.

One run per point, closed loop: each client sends its next request as soon as the last returns, 2 clients per worker, 2 s of warm-up then 8 s measured. The USL curve is the lab's least-squares fit to these 8 points (on a flat line, as for threads, it means little). The lock time comes from a separate timing run with 1 worker (286 requests, median).

Threads: one core's worth of Python

With threads, 32 workers did 171 a second against 180 for one. The best point, 182 at 2 threads, is less than 2% above one thread.

The reason is the GIL, CPython's global interpreter lock: only one thread at a time can run Python code. Threads take turns holding it, so 32 threads computing in Python do one thread's worth of work. Threads still help when the work waits (a network call, a disk read, a sleep), because waiting releases the GIL. They never help pure-Python computing.

The fix is processes: separate Python programs, each with its own interpreter and its own GIL. (The lab's CPU work counts loop iterations rather than watching the clock, so a thread that only gets a slice of the GIL can't finish early and make threads look as if they scale.)

Processes: a lot, up to a point

The same work in processes went from 181 a second with 1 worker to 959 with 8 (5.3×). After that, each step added less: 1,258 at 12, then 1,313 at 32, only 4% more than 12. Past 12 workers something else became the limit, even though Docker had 16 virtual CPUs.

The lab's notes attribute this to the app's single main process, which hands every request to a worker process: one serial step that all requests go through (they measured it at 0.89 cores at 12 workers, a diagnostic not saved with the results). The noise is large too. The dip to 1,112 at 16 workers is one run, and the lab's notes record repeat runs at 32 workers between 1,313 and 1,731 a second. One run per point can show the shape; it can't tell 1,258 from 1,313.

A locked row: a ceiling you can compute

The third kind of work changes one shared row in Postgres. The UPDATE takes a row lock: until the transaction commits, no other request can change that row. Inside the lock the code waits 1 ms (pg_sleep(0.001)), then commits, which saves the change and lets go of the lock. The 10 ms before it shares nothing.

With 1 worker: 62 a second. With 8: 284. Then it stopped: 271 to 277 from 12 to 32 workers, about 274 on average.

The reason is that only one request can be inside the lock at a time. That part of the work, the critical section, runs one after another however many workers there are, so:

throughput ≤ 1 ÷ (time inside the lock)

At the 1 ms the code asks for, that's 1,000 a second, nowhere near the plateau. So the lock was timed (separately, with 1 worker, 286 requests): each request held it a median of 3.65 ms, not 1. Most of that is the "1 ms" wait itself: pg_sleep(0.001) timed on its own from the laptop took about 3.5 ms. And 1 s ÷ 3.65 ms ≈ 274 a second, right at the plateau.

Two lessons. Time what's inside the lock; the number in the code isn't the number the system runs. And more workers can't pass the ceiling. Only a shorter critical section moves it: do the slow part outside the transaction, spread the counter over several rows and sum them on read, or batch the updates.

Fitting a curve to scaling

The lab also fits each line with the Universal Scalability Law (USL), a model of throughput with n workers:

X(n) = λ₁·n ÷ (1 + σ(n − 1) + κ·n(n − 1))

λ₁ is one worker's throughput. σ (contention) is the share of the work that has to happen one at a time; it caps throughput the way the lock did. κ (coherence) is the cost of workers keeping each other in sync, which grows with every pair; with κ above zero, throughput peaks and then falls.

Work λ₁ σ κ Peak at One more worker adds < 5% of λ₁ after R²
CPU, processes 207 0.092 0.0013 26 18 0.98
CPU, threads 172 1.0 — — 1 0.01 (flat)
A locked row 87 0.19 0.0040 14 10 0.93

Threads get σ = 1: everything is serialized. The fit is useful for reading off "where does another worker stop paying off" before you buy it, but treat it as a summary of 8 noisy points, not a law. For the locked row it predicts a fall after 14 workers (258 a second at 32) that the data barely shows (272), and its λ₁ of 87 is well above the 62 measured with one worker. The lock's own rule, 1 ÷ 3.65 ms, explains the plateau better than the fit does.

Three kinds of work, three answers

Work What more workers did Why The fix
CPU, threads nothing one GIL processes, not threads
CPU, processes 5.3× at 8, then little a serial step (the dispatcher) remove the serial step
A locked row nothing past 8 one lock, held 3.65 ms less time inside the lock

Two stations: the bottleneck

Now a pipeline. Every request goes through two stages, one after the other:

  • Stage A: 4 ms of computing, in 4 processes.
  • Stage B: 4 ms of waiting, like a call to another service, with only 2 slots.

The lab kept it full with 32 clients and measured 402 a second. Then it made each stage twice as fast in turn:

Variant Measured A busy B busy Wait in front of A Wait in front of B
As built 402 46% 97% 0.2 ms 68.5 ms
A twice as fast 415 23% 97% 0.2 ms 68.6 ms
B twice as fast 826 98% 96% 10.4 ms 20.4 ms
Both twice as fast 730 41% 96% 0.2 ms 37.8 ms

Making A twice as fast bought 402 → 415, inside the noise. Making B twice as fast doubled throughput. A pipeline runs at the speed of its slowest stage, its bottleneck:

capacity of a stage = workers ÷ time per request
throughput          = the smallest stage capacity

As built, under load, A took 4.61 ms in 4 processes (4 ÷ 4.61 ms ≈ 867 a second) and B took 4.82 ms in 2 slots (2 ÷ 4.82 ms ≈ 415 a second). Four computing workers can do twice what two waiting slots can, so B sets the pace, and speeding up A changes nothing. (The "both twice as fast" run, 730 a second, came in below "B twice as fast"; B's loaded time happened to be longer in that run, 2.62 ms against 2.32.)

Try it · Which stage to speed upLab 03 · 04_bottleneck.py · 32 clients, every request goes through A then B

Asked for: A 4 ms of computing, B 4 ms of waiting.

Stage A

Computing, in 4 processes

Time per request4.61 ms
Capacity, 4 ÷ time867/s
Waiting in front0.2 ms
Busy46%
Stage Bsets the pace

Waiting (like a call to another service), 2 slots

Time per request4.82 ms
Capacity, 2 ÷ time415/s
Waiting in front68.5 ms
Busy97%
Measured
402/s
Predicted, slower stage
415/s
vs. as built
1.00×

Service times used for the prediction and the busy %

Prediction over the measurement by 3.3%. The stage near 100% busy, with requests waiting in front of it, is the one that sets the pace.

Capacity of a stage = workers ÷ time per request. The pipeline can't beat its slower stage. Busy = measured throughput × time per request ÷ workers. Idle times: 8 s at 50 requests a second; loaded times: the same saturated run that measured the throughput. One run per variant.

Find it without guessing

Trying each stage is one way. You can also find the bottleneck without changing anything, from two signs:

  • It's the busiest stage. A stage's utilization is the fraction of time its workers are busy: throughput × time per request ÷ workers. B: 402 × 4.82 ms ÷ 2 = 97%. A: 402 × 4.61 ms ÷ 4 = 46%. (Chapter 4 shows why latency climbs steeply as utilization nears 100%.)
  • It's where requests wait. On average a request waited 68.5 ms in front of B and 0.2 ms in front of A.

After B was made twice as fast, the signs moved: A went to 98% busy and requests started waiting 10 ms in front of it, while B stayed at 96%. Both stages are now nearly full. Fix one bottleneck and the next one shows up.

One more trap, which the lab hit while it was built. The first prediction used service times measured on an idle system. For "B twice as fast", B's 2 ms wait took 2.85 ms idle but 2.32 ms under load: an idle event loop wakes its timers late, a busy one nearly on time. With the idle time, B would have been 826 × 2.85 ms ÷ 2 = 118% busy, which is impossible. Predict from service times measured in the same loaded run. With loaded times, every prediction landed within 5% of the measurement (415 vs. 402, 428 vs. 415, 844 vs. 826, 765 vs. 730).

Caveats

  • One run per point, on a busy laptop. The load average was about 18 at the end of the scaling run and about 10 during the pipeline run. Repeat runs of one point differed by up to 30% (processes at 32 workers: 1,313 against 1,731 a second). Single dips, like processes at 16 workers, can be noise.
  • The lock timing is a separate run. The scaling run doesn't save how long the lock was held; it was timed afterwards with 1 worker (median 3.65 ms, mean 3.78). The lab's own notes give 3.6 ms held and 3.0 ms for pg_sleep alone, from a diagnostic that wasn't saved; the separate run measured 3.65 and about 3.5. Either way, 1 s ÷ time held lands at the plateau.
  • The dispatcher explanation for processes isn't in the saved results. The data show the plateau; the cause is the lab's diagnosis.
  • A closed loop measures capacity, not latency under real traffic. Clients wait for each reply, so the throughput is the most the setup can do; the latency at that point is the latency of a full queue (see Chapters 2 and 4).
  • The GIL result is for CPython with the GIL. Free-threaded Python builds remove that limit for threads, at some single-thread cost. Measure it the same way.

The checklist

  1. Measure throughput at several worker counts, with enough clients that no worker waits for work, and compare each step to what the first worker added.
  2. Is there one knife? Pure-Python computing in threads won't scale: use processes.
  3. Is there one order book? Find what runs one at a time (a lock, a hot row, a single dispatcher), time it, and compute 1 ÷ that time. That's the ceiling; only a shorter critical section moves it.
  4. Which stage is the bottleneck? Compute each stage's utilization (throughput × time per request ÷ workers) and measure where requests wait. Speed up only that stage.
  5. Use service times measured under load, in the same run, for predictions. A utilization above 100% means an input is wrong.
  6. After a fix, look again. The next bottleneck is usually close behind.
  7. Repeat the points you'll decide on. One run per point shows a shape, not a number.

Practice: find the limit

Write the lab's arithmetic: speedups over one worker, the ceiling a lock allows, the USL and its peak, where one more worker stops paying off, a stage's capacity and utilization, and the bottleneck of a pipeline. The tests use the recorded runs: 5.3× at 8 processes, 1 s ÷ 3.65 ms ≈ 274 against a plateau of 274, the fitted peaks at 26 and 14 workers, B at 97% busy, and A as the new bottleneck once B is twice as fast.

Try it · Practice in PythonRuns in your browser · ⌘/Ctrl + Enter to run
scaling_practice.py66 lines

Quiz

Try it · Check your understanding0 of 6 answered
  1. 1.A Python service does pure-Python computing in a pool of threads. Going from 1 thread to 32 will most likely…

  2. 2.Each request holds a lock on one database row for 4 ms. Roughly how many requests a second can the service finish, with 64 workers?

  3. 3.The lab's code asked for 1 ms inside the lock, yet throughput stopped near 275, not 1,000. What was the first thing to do?

  4. 4.A two-stage pipeline does 402 a second. Stage A is 46% busy with 0.2 ms of waiting in front of it; stage B is 97% busy with 68 ms of waiting. Which change helps?

  5. 5.After B was made twice as fast, throughput doubled and stage A went from 46% to 98% busy. What does that tell you?

  6. 6.A prediction built from service times measured on an idle system said one stage was 118% busy. What went wrong?

Check your understanding

Try each question before opening its answer.

Why did 32 threads finish no more pure-Python work than 1, and what would?

CPython's GIL lets only one thread at a time run Python code, so the threads take turns: 180 a second with 1 thread, 171 with 32. Separate processes each have their own GIL: 8 processes did 959 a second, 5.3× one. Threads still help work that waits, like network calls.

A service updates one shared row on every request and stops at about 275 a second. How do you explain it, and what fixes it?

Only one request can hold the row lock at a time, so throughput can't pass 1 ÷ (time inside the lock). Time it: here it was held 3.65 ms, not the 1 ms in the code, and 1 s ÷ 3.65 ms ≈ 274. More workers can't move that. A shorter critical section can: do the slow part outside the transaction, spread the counter over several rows, or batch the updates.

Processes scaled 5.3× to 8 workers, then 12 → 32 added only 4%, on a machine with 16 virtual CPUs. What would you check?

Something other than the cores is serializing the work. The lab's diagnosis was the single main process that hands each request to a worker (0.89 cores at 12 workers). Also repeat the runs: on the busy laptop, repeats at 32 workers ranged from 1,313 to 1,731 a second, so one run can't tell 1,258 from 1,313.

How do you find the bottleneck of a pipeline without changing anything?

Two signs: it's the busiest stage (utilization = throughput × time per request ÷ workers), and it's the stage requests wait in front of. Here B was 97% busy with 68.5 ms of waiting in front of it; A was 46% busy with 0.2 ms. Making A twice as fast gave 415 a second (noise); making B twice as fast gave 826.

You doubled the speed of the bottleneck stage and throughput doubled. Will doubling it again double throughput again?

Probably not. After B was made twice as fast, A went from 46% to 98% busy and requests began waiting in front of it: A's capacity (about 844 a second) became the lower one. Look again after every fix; the next bottleneck is usually close behind.

Your capacity model says a stage is 118% busy. What's wrong?

An input. No stage can be busy more than 100% of the time. In the lab the cause was a service time measured on an idle system: B's 2 ms wait took 2.85 ms idle and 2.32 ms under load. With times measured in the same loaded run, every prediction was within 5% of the measurement.

What do σ and κ mean in the Universal Scalability Law, and how far would you trust the fit here?

σ (contention) is the share of work done one at a time, like a lock or the GIL; it caps throughput. κ (coherence) is the cost of workers keeping each other in sync; it makes throughput peak and then fall. The fits (σ = 0.19 for the lock, 0.09 for processes, 1 for threads) summarize 8 single-run points. The lock fit predicts a fall after 14 workers that the data barely shows, so use it for "where does another worker stop paying off", and the 1 ÷ lock time rule for the ceiling.

Next up: Indexes: when they help and when they hurt. So far the database was a box with a service time. The next chapter opens it: why one index made a query 8,800× faster, another made it slower, and what every index costs each insert.

Learning something useful?

New labs, articles, and videos on evaluating and testing AI systems come out regularly. Follow along so you don't miss the next one.