Map Your Throughput Curve: Find the Concurrency Sweet Spot
Run a local harness that logs pages per minute at rising worker counts. Plot your throughput curve and find where extra concurrency stops paying.
On this page
What a Throughput Curve Tells You That Latency Averages Don’t
Ask most engineers how fast their scraper runs and you get an average latency figure. “About 400 milliseconds per page.” That number is close to useless for capacity planning, because it says nothing about what happens when you add concurrency. A single worker at 400ms per page gives you 150 pages/min. Eight workers should give you 1,200 pages/min. It never does. Something always bends first: the event loop, the target’s rate limiter, your DNS resolver, the socket pool.
The fix is to stop thinking in latency and start thinking in throughput as a function of worker count. Run your fetcher at 1 worker, measure pages/min. Run it at 2, 4, 8, 16. Plot it. What you get is a curve with three distinct regimes, and the shape of that curve tells you exactly where to operate:
pages/min
640 | _______________
560 | ____/
480 | ___/
400 | __/
320 | /
240 | /
160 | /
80 | /
0 |/______________________________
1 2 4 8 16 32 64 128
workers
|linear |knee| plateau / decay
The left segment scales linearly — every doubling of workers doubles throughput. Then comes the knee, where gains flatten. Past that, the curve either plateaus or declines, and in the declining case you are actively paying more (CPU, proxy bandwidth, target goodwill) for less output.
Here’s what that looks like as numbers. This is the shape I see over and over on real pipelines, and your exact values will differ, but the regimes won’t:
| Workers | Pages/min | Marginal gain vs. prev. | p95 latency | Regime |
|---|---|---|---|---|
| 1 | 148 | — | 405 ms | Under-saturated |
| 2 | 292 | +97% | 410 ms | Under-saturated |
| 4 | 570 | +95% | 415 ms | Under-saturated |
| 8 | 1,090 | +91% | 460 ms | Under-saturated |
| 16 | 1,480 | +36% | 620 ms | Sweet spot |
| 32 | 1,555 | +5% | 1,180 ms | Oversaturated |
| 64 | 1,410 | −9% | 2,650 ms | Oversaturated |
Notice the p95 latency column. It degrades before throughput does. That is your early warning: the target (or your own harness) is queuing requests. If you only track average latency, the queueing hides in the tail and you find out about it when the 429s start. If you want a refresher on why tail latency lies to you, the timing harness breakdown covers the per-request decomposition in detail.
One more thing the curve gives you that averages can’t: a regression baseline. When you change a timeout or a connection setting and the curve moves, you know immediately whether the change helped. We’ll get to that at the end.
Building the Local Harness: A Worker Pool That Logs Pages per Minute
The harness is deliberately dumb. N workers pull URLs from a shared queue, fetch them, and log completions with timestamps. No clever scheduling, no backoff — we want the raw concurrency behavior on display.
# harness.py
import argparse
import csv
import time
import uuid
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass, field
from queue import Queue
from urllib.request import urlopen, Request
@dataclass
class RunConfig:
workers: int
run_id: str
log_path: str
base_url: str = "http://store.example.com:8000"
duration_s: int = 60
def fetch(url: str) -> int:
req = Request(url, headers={"User-Agent": "harness/1.0"})
with urlopen(req, timeout=30) as resp:
return resp.status
def worker(run: RunConfig, queue: Queue, log: list, stop_at: float):
while time.time() < stop_at:
try:
path = queue.get_nowait()
except Exception:
path = "/product/{n}".format(n=uuid.uuid4().hex[:8])
t0 = time.time()
status = fetch(run.base_url + path)
log.append({
"run_id": run.run_id,
"workers": run.workers,
"ts": time.time(),
"fetch_ms": round((time.time() - t0) * 1000, 1),
"status": status,
})
def run_ramp_step(workers: int, duration_s: int, log_path: str, base_url: str):
run = RunConfig(
workers=workers,
run_id=uuid.uuid4().hex[:8],
log_path=log_path,
base_url=base_url,
duration_s=duration_s,
)
queue = Queue()
for i in range(10_000):
queue.put("/product/{n}".format(n=i))
log = []
stop_at = time.time() + duration_s
with ThreadPoolExecutor(max_workers=workers) as pool:
futures = [pool.submit(worker, run, queue, log, stop_at) for _ in range(workers)]
for f in futures:
f.result()
with open(log_path, "a", newline="") as f:
writer = csv.DictWriter(f, fieldnames=["run_id", "workers", "ts", "fetch_ms", "status"])
if f.tell() == 0:
writer.writeheader()
writer.writerows(log)
return len(log)
if __name__ == "__main__":
p = argparse.ArgumentParser()
p.add_argument("--workers", type=int, required=True)
p.add_argument("--duration", type=int, default=60)
p.add_argument("--log", default="ramp.csv")
p.add_argument("--base-url", default="http://store.example.com:8000")
a = p.parse_args()
completed = run_ramp_step(a.workers, a.duration, a.log, a.base_url)
print("workers={w} completed={c} pages/min={rpm:.0f}".format(
w=a.workers, c=completed, rpm=completed * 60 / a.duration))
The logging line is the important part. Every completion gets a row with the run ID, the worker count, a timestamp, the fetch duration, and the HTTP status. Appending to CSV as we go means a crashed run still leaves its partial data on disk, which has saved me more than once.
Two design decisions worth defending. First, threads instead of asyncio: for an I/O-bound fetch loop, threads are less code and harder to get subtly wrong, and the GIL is irrelevant when every worker spends its life blocked on a socket. If you’re already on asyncio, the same harness maps directly onto a task-per-worker pattern — the measurement methodology is identical. Second, I log raw per-request rows rather than pre-aggregated per-minute counts. Raw rows let you compute p95, queue wait, and error rates later without re-running anything. Aggregate early and you throw away the evidence.
Generating a Realistic Test Target with store.example.com
If you point the harness at a server that responds instantly, you will measure your own loop overhead, not the system you care about. Real targets take hundreds of milliseconds, vary, and occasionally stall. So the mock target needs artificial delay with jitter, or the whole exercise is theater.
Here is a minimal server that serves the page set with a configurable delay distribution:
# mock_store.py
import random
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
PAGE_SET = {
"category": ["/category/{n}".format(n=n) for n in range(24)],
"product": ["/product/{n}".format(n=n) for n in range(5_000)],
}
# Per-route delay: uniform draw within a band, plus a slow tail
DELAY_MS = {
"category": (200, 400), # fast, small pages
"product": (350, 800), # slower, heavier pages
}
SLOW_TAIL_PROB = 0.05 # 5% of requests take 3-5x the base delay
SLOW_TAIL_MULTIPLIER = (3.0, 5.0)
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
route = "category" if self.path.startswith("/category") else "product"
lo, hi = DELAY_MS[route]
delay = random.uniform(lo, hi)
if random.random() < SLOW_TAIL_PROB:
delay *= random.uniform(*SLOW_TAIL_MULTIPLIER)
time.sleep(delay / 1000)
body = "<html><body><h1>{p}</h1></body></html>".format(p=self.path)
self.send_response(200)
self.send_header("Content-Type", "text/html")
self.end_headers()
self.wfile.write(body.encode())
def log_message(self, *args):
pass # keep stdout clean during measurement
if __name__ == "__main__":
ThreadingHTTPServer(("127.0.0.1", 8000), Handler).serve_forever()
The config that drives the test run:
# ramp_config.yaml
target:
host: "127.0.0.1:8000"
base_url: "http://store.example.com:8000" # store.example.com -> 127.0.0.1 in /etc/hosts
page_set:
category_pages: 24
product_pages: 5000
delay:
category: [200, 400] # ms, uniform
product: [350, 800] # ms, uniform
slow_tail: {prob: 0.05, multiplier: [3.0, 5.0]}
ramp:
worker_counts: [1, 2, 4, 8, 16, 32, 64, 128]
step_duration_s: 60
cooldown_s: 10 # settle between steps
Two details matter more than they look. The slow tail — 5% of requests taking 3-5x the base delay — is what drags your p95 away from your mean, which is exactly the behavior you need to see at high concurrency. A uniform-only delay model will make the knee look far cleaner than it ever is in production. And the 10-second cooldown between ramp steps prevents TCP connections and server-side state from one step bleeding into the next. Without it, your step-2 measurement inherits warm connections from step 1 and your curve lies.
One honest caveat: this mock has no rate limiter and no connection cap. That is deliberate for the first pass — you want to see your harness’s ceiling in isolation. Once you know that, you can add a token-bucket filter to the mock to simulate target-side throttling and re-run. Measure your own ceiling first, then the combined system.
Running the Ramp: Sweeping Worker Counts from 1 to 128
The protocol is simple but it has to be identical every time: for each worker count, run the harness for exactly 60 seconds, discard nothing, log everything, then cool down before the next step. A fixed duration per step (rather than “run until N pages”) matters because throughput at high worker counts is often bursty — the first 10 seconds can look great before the queueing kicks in.
#!/usr/bin/env bash
# ramp.sh — run the full sweep, one CSV, one row summary per step
set -euo pipefail
WORKERS=(1 2 4 16 32 64 128)
LOG=ramp.csv
: > "$LOG"
for w in "${WORKERS[@]}"; do
echo "=== workers=$w ==="
python harness.py --workers "$w" --duration 60 --log "$LOG"
sleep 10 # cooldown between steps
done
echo "raw rows written to $LOG"
Note the : > "$LOG" — start each ramp with a clean file, or you’ll average this run’s numbers with last week’s. If you want to keep history, copy the CSV to a timestamped filename first, then truncate.
Typical raw output for two steps looks like this:
=== workers=8 ===
workers=8 completed=1096 pages/min=1096
=== workers=64 ===
workers=64 completed=1412 pages/min=1412
And inside the CSV, the per-request rows:
run_id,workers,ts,fetch_ms,status
a1b2c3d4,8,1717000000.112,418.7,200
a1b2c3d4,8,1717000000.531,402.1,200
a1b2c3d4,64,1717000100.004,2410.5,200
a1b2c3d4,64,1717000100.006,2688.0,200
Read those last two rows carefully. At 64 workers, individual fetches take 2.4-2.7 seconds — six times the 400ms baseline — yet the step still completed 1,412 pages. Throughput barely moved from the 16-worker step while per-request latency exploded. That is the signature of queueing somewhere in the path, and it’s why the raw per-request log is worth the disk space: the aggregate pages/min number alone would have told you 64 workers “works.”
Plotting the Curve from Your Ramp Logs
Raw CSV is where the truth lives, but a plot is what you’ll actually stare at. Aggregation is one pass over the file:
# plot_curve.py
import csv
from collections import defaultdict
import matplotlib.pyplot as plt
def load_ramp(path):
per_workers = defaultdict(int)
run_durations = defaultdict(lambda: defaultdict(list))
with open(path) as f:
for row in csv.DictReader(f):
w = int(row["workers"])
per_workers[w] += 1
run_durations[w][row["run_id"]].append(float(row["ts"]))
points = {}
for w, runs in run_durations.items():
# pages/min per run, then average across runs
rates = [
len(ts_list) * 60 / (max(ts_list) - min(ts_list))
for ts_list in runs.values()
]
points[w] = sum(rates) / len(rates)
return points
points = load_ramp("ramp.csv")
workers = sorted(points)
ppm = [points[w] for w in workers]
fig, ax = plt.subplots(figsize=(8, 5))
ax.plot(workers, ppm, marker="o", label="measured")
# smoothed trend across the doubling steps
ax.plot(workers, [sum(ppm[max(0,i-1):i+2])/len(ppm[max(0,i-1):i+2])
for i in range(len(ppm))], label="smoothed", alpha=0.6)
ax.set_xscale("log", base=2)
ax.set_xticks(workers)
ax.set_xlabel("workers")
ax.set_ylabel("pages/min")
ax.set_title("Throughput curve: store.example.com ramp")
ax.legend()
ax.grid(True, alpha=0.3)
fig.savefig("throughput_curve.png", dpi=150)
The log-scale x-axis with ticks at each doubling is a small choice with a big payoff: linear scaling shows up as equal spacing between points on the left of the plot, and the knee is visually unmistakable. A linear axis compresses the interesting region (1-32 workers) into the left inch of the chart.
The table behind a typical plot, once you’ve aggregated:
| Workers | Pages/min | Shape signal |
|---|---|---|
| 1 | 148 | baseline |
| 2 | 292 | +97% — linear |
| 4 | 570 | +95% — linear |
| 8 | 1,090 | +91% — linear |
| 16 | 1,480 | +36% — knee |
| 32 | 1,555 | +5% — plateau |
| 64 | 1,410 | −9% — decay |
If your plot shows monotonic decay right from 2 workers, something in the harness itself is contended — a single shared lock, a global connection limit, DNS serialization. Fix that before drawing any conclusions about the target. A curve that decays from the start measures your bug, not your system.
Locating the Knee: Where Extra Workers Stop Paying
Now the operational question: which worker count do you actually run in production? My rule is blunt and I’ll defend it: the sweet spot is the largest worker count whose throughput gain over the previous doubling exceeded 15%. Not 5%, not 1% — 15%.
Here’s the computation:
# find_knee.py
def find_sweet_spot(points, min_gain=0.15):
workers = sorted(points)
sweet = workers[0]
for i in range(1, len(workers)):
prev, cur = workers[i - 1], workers[i]
gain = (points[cur] - points[prev]) / points[prev]
print("workers {p}->{c}: gain {g:+.1%}".format(
p=prev, c=cur, g=gain))
if gain >= min_gain:
sweet = cur
return sweet
points = {1: 148, 2: 292, 4: 570, 8: 1090, 16: 1480, 32: 1555, 64: 1410}
print("sweet spot:", find_sweet_spot(points))
Output:
workers 1->2: gain +97.3%
workers 2->4: gain +95.2%
workers 4->8: gain +91.2%
workers 8->16: gain +35.8%
workers 16->32: gain +5.1%
workers 32->64: gain -9.3%
sweet spot: 16
Why 15% and not something smaller? Because of what sits past the knee. At 32 workers in this example you gain 5% throughput — 75 pages/min — while your p95 latency goes from 620ms to 1.2s and your in-flight request count doubles. You are holding twice the concurrency, doubling your exposure to timeouts and target-side throttling, for a rounding error of throughput. That trade is bad on its own, and worse because high in-flight counts amplify every failure: when the target hiccups, 32 workers all fail at once instead of 16.
You might disagree with the threshold, and that’s fine — pick 10% or 20% for your own systems. What I will argue against is “run at max throughput regardless.” The absolute peak of the curve is not the operating point. It’s the point where you’ve spent your entire margin. Run at the knee, keep the headroom.
A worked example to make it concrete. Suppose your ramp gives 480 pages/min at 16 workers and 505 pages/min at 32. That’s a 5.2% gain for 2x the concurrency. Sweet spot: 16 workers. The 25 pages/min you’re leaving on the table costs almost nothing to recover with a second process or a longer run window — but the doubled in-flight exposure costs you every time the target has a bad minute.
Diagnosing the Bottleneck That Sets Your Ceiling
Finding the knee answers where to operate. The next question is why the ceiling is where it is, because that determines whether tuning can move it. Four culprits cover almost every plateau I’ve seen, and each has a distinct signature in the harness logs:
| Bottleneck | Signature in harness data | Signature on the host | Fix direction |
|---|---|---|---|
| CPU saturation (parsing, TLS) | fetch_ms grows with workers; queue wait near zero | top shows the process at ~100% of one core | Move parsing off the fetch path, or shard processes |
| Network / socket exhaustion | Timeouts climb; ECONNREFUSED/EMFILE errors appear | ss -s shows huge open-socket counts | Raise fd limits, add connection reuse (the socket-leak post covers detection) |
| Target-side rate limiting | Status 429s cluster at high worker counts; latency spikes before errors | Nothing wrong on your host | Lower concurrency or add per-target throttling — the target is telling you the ceiling |
| Harness lock contention | Queue wait time grows while fetch_ms stays flat | CPU low, but throughput plateaus anyway | Fix the harness: coarser queue, per-worker buffers |
The last two are easy to confuse, because both show “low CPU + flat throughput.” The discriminator is where the time goes. If a request spends 2 seconds in the queue before the fetch even starts, your harness is the problem. If it starts immediately and the fetch itself takes 2 seconds, the network or the target is the problem. So: log both.
# add queue-wait timing to the worker
def worker(run, queue, log, stop_at):
while time.time() < stop_at:
t_dequeued = time.time()
try:
path = queue.get_nowait()
except Exception:
path = "/product/{n}".format(n=uuid.uuid4().hex[:8])
t_start = time.time()
status = fetch(run.base_url + path)
t_done = time.time()
log.append({
"run_id": run.run_id,
"workers": run.workers,
"ts": t_done,
"queue_wait_ms": round((t_start - t_dequeued) * 1000, 1),
"fetch_ms": round((t_done - t_start) * 1000, 1),
"status": status,
})
With queue_wait_ms in the log, the diagnosis is one groupby away: at the plateau, if queue_wait_ms p50 is small and fetch_ms p95 is huge, the target or network is your ceiling. If queue_wait_ms grows with worker count, look at your own locks. In the ThreadPoolExecutor version above the queue rarely starves, but the moment you add a shared rate limiter or a single connection object, queue wait becomes the tell.
One diagnostic I run before trusting any plateau: point the harness at a second mock server on a different port. If throughput against two independent targets is the same as against one, the ceiling is yours. If it doubles, the ceiling was the target. Ten minutes of work, and it settles the argument.
Re-Running the Curve After Every Tuning Change
The curve is only useful if it’s current. Every time you touch a timeout, switch connection handling, change the page mix, or swap the HTTP client, the knee can move — and “we run at 16 workers” becomes a stale number that everyone still trusts. So make the ramp a script that anyone can run and that CI runs on every change to the fetch path.
# .github/workflows/ramp.yml
name: throughput-ramp
on:
push:
paths: ["scraper/**", "harness.py"]
workflow_dispatch: {}
jobs:
ramp:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: start mock target
run: python mock_store.py &
- name: run ramp
run: |
bash ramp.sh
python plot_curve.py
python find_knee.py
- name: archive results
uses: actions/upload-artifact@v4
with:
name: ramp-results-${{ github.sha }}
path: |
ramp.csv
throughput_curve.png
The artifacts are the point. Every commit that touches the fetch path gets a CSV and a plot attached, so “did this change help?” is answered by opening two artifacts instead of re-running anything. Keep the mock target versioned alongside the harness — if someone edits the delay distribution in mock_store.py, historical comparisons break unless you pin the mock too.
A before/after that shows why this is worth the CI minutes. On a pipeline I was tuning, the baseline curve put the knee at 16 workers / 480 pages/min. The fetcher was opening a fresh TCP connection per request. After enabling connection reuse (a persistent http.client.HTTPConnection per worker plus a Connection: keep-alive header), the same ramp put the knee at 24 workers / 610 pages/min:
| Config | Knee (workers) | Pages/min at knee |
|---|---|---|
| New connection per request | 16 | 480 |
| Connection reuse per worker | 24 | 610 |
That’s a 27% throughput gain from a change that would have been invisible in average latency — the per-request handshake cost was small relative to page time, but at scale it was what set the ceiling. Without the before/after curves, the change would have shipped with a shrug. If connection reuse is new territory for you, the connection-reuse measurement post shows how to count handshakes directly.
Two gotchas before you wire this up. First, keep the ramp out of your main CI test suite — a 60s-per-step sweep across eight worker counts is nine-plus minutes of wall time. Trigger it on path changes or manually. Second, resist the urge to run the ramp against a production target. The whole methodology assumes a target whose behavior you control. Point it at real infrastructure and you’re load-testing someone else’s server, which is both rude and a good way to get your IPs flagged.
Wrapping Up
The method in one paragraph: build a dumb worker pool, point it at a mock target with realistic delay jitter, sweep worker counts in doubling steps with a fixed window per step, log per-request rows, plot pages/min against workers, and pick the last step that cleared a 15% gain as your operating point. Then re-run the whole thing whenever the fetch path changes, and keep the artifacts.
The pieces that matter most, in order: the raw per-request log (everything else is recomputable from it), the slow-tail delay model in the mock (without it the knee is fiction), and the queue-wait vs. fetch-time split (it’s what turns “we’re slow” into a diagnosis). The plot itself is the least important artifact — it’s just the CSV wearing a chart.
One parting opinion: if you do this once and never again, you’ve still come out ahead, because “16 workers” beats “whatever the default was” every time. But the curve’s real value is as a regression signal. Latency averages drift and nobody notices. A knee that moves from 16 workers to 8 is a flashing light in a diff. Run it on every change, and your capacity decisions stop being folklore.
Related Articles
Prove Your Concurrency: Count In-Flight Requests Locally
Point your scraper at a local listener that logs request starts and ends, then compute real in-flight concurrency to verify your worker pool setup.
TechnicalMeasure Content Density: How Much of a Page Is Data
Run a local analyzer over a sample of scraped HTML to split bytes into scripts, styles, and extractable text — and see how much of each page is data.
TechnicalMeasure Link Rot: A Local Sampler for Your Oldest URLs
Build a small local sampler that re-checks your oldest scraped URLs, measures 404 and redirect rates, and tells you when a dataset needs refreshing.