Course contents

15. Performance Engineering Lesson 6 of 8

Parallelism

See how parallel workers raise throughput until a serial part caps it (Amdahl’s law), and why fan-out latency is set by the slowest branch.

15 minAdvanced10 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Independent work scales almost linearly with workers until something shared becomes the bottleneck.
  • Amdahl’s law: with serial fraction s, speedup ≤ 1 ÷ (s + (1 − s) ÷ N) and never more than 1 ÷ s.
  • Shrinking or splitting the serial part raises the ceiling; adding workers in front of it only adds waiting.
  • A parallel fan-out is as slow as its slowest branch, so per-call tails become request-level medians.
  • Hedged requests, per-call deadlines and partial results shorten the tail at a small, bounded cost.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

Parallelism is doing several pieces of work at the same instant on separate execution resources: CPU cores, threads, processes, machines. It differs from concurrency, which is about structuring a program so many tasks are in progress at once (they may interleave on one core). Parallelism needs hardware that can actually run things simultaneously.

In system design it shows up in two forms:

  • Throughput parallelism: many independent requests or jobs processed side by side by a pool of workers.
  • Latency parallelism: one request split into parts that run at the same time (scatter-gather, fan-out to shards or services), then merged.

Why it exists

Single-core speed has grown slowly since the mid-2000s; core counts and machine counts have not. A modern server has dozens of cores, and a cluster has thousands. Using them requires splitting work. For latency-sensitive work such as search over a large index, splitting the data across shards and querying them in parallel is often the only way to answer within a budget.

How it works

Worker pools. A pool of N workers takes independent jobs from a queue. If jobs share nothing, capacity is roughly N ÷ (time per job): four workers at 50 ms per job finish about 80 jobs per second.

The serial part. Almost every workload has a part that cannot run in parallel: updating a shared counter under a lock, appending to a single log, a single-writer database row, merging results, the coordinator that hands out work. Amdahl’s law (1967) quantifies the effect for a fixed amount of work with serial fraction s:

speedup(N) = 1 / (s + (1 − s) / N)      limit as N → ∞: 1 / s

With s = 0.2, 4 cores give 2.5×, 16 cores 4×, and no number of cores more than 5×. With s = 0.05 the limit is 20×. For a stream of requests the same ceiling appears as a throughput cap: if every request needs 10 ms inside a section only one request can enter, the system completes at most 100 requests per second.

Worse than Amdahl. Coordination often grows with the number of workers: lock contention, cache-line bouncing between cores, more participants to synchronise. Gunther’s Universal Scalability Law adds a coherence term for this, which is why throughput curves can peak and then fall as you add workers.

Gustafson’s view. Amdahl assumes a fixed problem size. Gustafson’s law observes that with more processors people usually solve bigger problems in the same time, where the parallel part grows and the serial part does not. Both are true; they answer different questions (faster on the same work versus more work in the same time).

Fan-out and fan-in. A request split into N parallel calls finishes when the last call returns. If each call is slow with probability p, the request is slow with probability 1 − (1 − p)^N. With p = 1%: N = 4 → ~4%, N = 20 → ~18%, N = 100 → ~63%. This is the effect described in Dean and Barroso’s “The Tail at Scale” (2013).

When to use it

  • Independent requests or jobs (stateless web tiers, batch processing, media encoding, message consumers).
  • Data that partitions cleanly, so each worker or shard owns a disjoint part (sharded search, map-reduce style aggregation).
  • Latency budgets that a sequential chain of calls cannot meet, where the calls do not depend on each other.

When not to

  • When a shared resource is already the bottleneck: more workers only lengthen the line in front of it.
  • When calls depend on each other’s results; forcing them parallel means speculative work you may throw away.
  • When the parallel part is tiny compared with the overhead of splitting, dispatching and merging.
  • Very wide fan-outs on a latency-critical path, unless you also manage the tail.

Trade-offs

Choice You gain You pay
More workers Throughput, while work is independent Memory, contention, more coordination; nothing past the serial ceiling
Finer-grained locks A smaller serial part, higher ceiling Complexity, deadlock risk, harder reasoning about invariants
Wider fan-out (more shards) Less work per shard, more parallel capacity Higher chance that some branch is slow; more requests in total
Hedged requests Much shorter tail A few percent extra load; only safe for idempotent requests
Partial results Bounded latency Lower quality or completeness on some responses

Alternatives

  • Make the serial part faster: less work inside the critical section, lock-free or sharded data structures (striped counters), batching updates.
  • Avoid sharing: partition state so each worker owns its own part (per-core or per-partition designs, actor models).
  • Precompute: move work off the request path into background jobs, so less needs to run in parallel at request time.
  • Narrower fan-out: fewer, larger shards or a two-level aggregation tree, so each request waits on fewer branches.

Failure modes

  • Serial ceiling: adding cores or instances with no throughput gain because a lock, a single writer or a single hot row is saturated.
  • Contention collapse: throughput falls as workers are added because they spend their time fighting over the same lock or cache line.
  • Tail amplification: every backend meets its P99 target, yet most user requests are slow because each touches many backends.
  • Hedging storms: hedging without a delay, or retrying on top of hedging, multiplies load exactly when servers are already slow.
  • Unbounded fan-out: one request spawns hundreds of calls and exhausts connection pools or thread pools downstream.

In production

Profile before scaling: look at lock wait time, single-threaded stages (one consumer per partition, one leader), and per-core CPU, not only the average. For fan-out paths, track latency per branch and for the whole request, set a deadline per call below the request’s budget, and decide what to do when a branch misses it (fail, retry once on a replica, or return partial results). Hedge only idempotent reads, typically after the branch’s P95, and cap the hedge rate. Search engines and large key-value stores commonly use these techniques.

Common misconceptions

  • “Twice the cores, twice the speed.” Only for the parallel part. The serial part does not shrink, and coordination costs often grow.
  • “Parallel calls cost the average latency.” They cost the maximum: the slowest branch decides.
  • “If every backend meets its P99, users see P99 behaviour.” With fan-out, a backend’s P99 can become the user’s median.
  • “Concurrency and parallelism are the same.” Concurrency is about managing many tasks in progress; parallelism is about running them at the same instant.

Interview angle

When a design adds instances to scale, interviewers ask what is shared: a database primary, a global lock, a sequence generator, a single partition. Name the serial part and quote Amdahl’s limit (“if 5% is serial we cap at 20×”). For scatter-gather designs (search, feeds, aggregation), say that latency is the slowest branch, estimate tail amplification with 1 − (1 − p)^N, and propose deadlines, partial results and hedged requests for idempotent reads.

Model assumptions

Simplified model, not a benchmark. Jobs arrive randomly (Poisson). Each job needs about 40 ms of parallelisable work (lognormal, cv 0.3) plus about 10 ms (later 4 ms) inside a critical section; the critical section is modelled as a separate one-worker stage, and a worker stays busy while it waits for it. Workers stand in for cores or threads; utilisation is the fraction of busy workers, not CPU. The four shards have 8 workers each and a heavy-tailed service time (lognormal, mean 10 ms, cv 1.0); network hops take 1 ms. The aggregator calls all four shards at the same time and answers when the last one has answered, so a query takes as long as its slowest call; the tail figures (call P50, call P99, share of queries slower than a call’s P99) are measured on those simulated queries. The slow shard is the same shard working 8× slower. The hedge router asks Shard 4 and its replica at the same moment and passes on the first answer, so it duplicates every call; a real hedge waits about the call’s P95 before sending the copy and cancels the loser, which the model does not do. The 1 − (1 − p)^N figures assume independent calls. Numbers are illustrative.

The lesson as textEvery step of the simulation, written out.
  1. 1. One worker does everything

    A service processes jobs on one worker (think: one core, one thread). Each job needs about 40 ms of work that could run anywhere, plus about 10 ms inside a critical section: code that only one job at a time may run, such as updating a shared counter under a lock.

    With everything on one worker, a job ties it up for about 52 ms, so it can finish about 19 jobs per second. At 15 per second it is busy most of the time and jobs already wait in line now and then.

    Scene: Jobs arrive at about 15 per second at a single worker, which also enters a one-at-a-time critical section for each job. The worker is busy most of the time and nothing fails.

    Key idea: Sequential capacity = 1 ÷ time per job. Here about 19 jobs per second.

  2. 2. Twice the jobs, same single worker

    Jobs now arrive at 40 per second, more than twice what one worker can do. Throughput flattens at about 19 per second; the rest wait until the queue is full and are then rejected (red packets).

    The critical section is not the problem yet: it is busy only about a fifth of the time. The single worker is.

    Scene: Jobs arrive at 40 per second. The single worker completes only about 19 per second, its queue is full and many jobs are rejected.

    Key idea: Past its capacity a sequential worker cannot go faster: extra jobs wait or are rejected.

  3. 3. Split the work across four workers

    Run the parallelisable part on four workers at once. Independent jobs need no coordination, so capacity grows almost linearly: four workers can finish about 75 jobs per second.

    All 40 jobs per second now complete and the rejections stop. Watch the critical section, though: it is busy about 40% of the time now, because every job still passes through it one at a time.

    Scene: Four workers handle 40 jobs per second without rejections. The critical section is about 40% busy.

    Key idea: Independent work scales with workers: 4 workers ≈ 4× the throughput, as long as nothing shared gets in the way.

  4. 4. Sixteen workers hit the serial wall

    Demand grows to 150 jobs per second and we scale to 16 workers, enough for about 300 jobs per second of parallel work. Yet throughput stops at about 100.

    Every job needs 10 ms in the critical section, and only one job can be inside it. That is at most 1000 ÷ 10 = 100 jobs per second, no matter how many workers queue up in front of it. The workers spend their time waiting for the lock; the queue fills and jobs are rejected.

    Scene: Sixteen workers and 150 jobs per second, but throughput stays near 100 per second. The critical section is always busy, workers wait for it and jobs are rejected.

    Key idea: The part that cannot run in parallel sets a hard ceiling. Adding workers in front of it only adds waiting.

  5. 5. Amdahl's law: 64 cores change nothing

    Quadruple again to 64 workers. Throughput is still about 100 jobs per second.

    This is Amdahl’s law. If a fraction *s* of the work is serial, the speedup from *N* workers is at most 1 ÷ (*s* + (1 − *s*) ÷ *N*), and never more than 1 ÷ *s*, however large *N* gets. Here *s* = 10 ÷ 50 = 0.2, so the ceiling is 5×: from about 20 jobs per second on one worker to about 100. A 5% serial part caps you at 20×; 1% at 100×.

    Scene: With 64 workers throughput is still about 100 jobs per second: the critical section is the ceiling. Annotations show the serial fraction 0.2 and the 5× limit.

    Key idea: Speedup ≤ 1 ÷ serial fraction. With 20% serial work, no number of cores gets you past 5×.

  6. 6. Make the serial part smaller

    The only way through the ceiling is to shrink the serial part. Here the critical section is cut from 10 ms to 4 ms: move the slow work (formatting, I/O) out of the lock, or split one lock into many (one per account, a striped counter) so unrelated jobs stop queueing for each other.

    Back on 16 workers, the ceiling rises to 250 jobs per second. All 150 complete and the rejections stop. Saving 6 ms of serial code did what 48 extra cores could not.

    Scene: The critical section now takes 4 ms. Sixteen workers complete all 150 jobs per second without rejections.

    Key idea: Raise the ceiling by shrinking or splitting what is serial, not by adding workers.

  7. 7. Fan-out: one request, four shards

    Parallelism also cuts the latency of a single request. A search query is split across four shards that each hold a quarter of the index; the aggregator asks all four at the same time and merges the answers. Done one after another, the calls would add up; in parallel they overlap.

    But the reply can only leave when the last shard has answered. Shard 4 is having a bad day (a noisy neighbour on its host) and works 8× slower than the others. Watch the packets: three answers come back quickly, then the aggregator waits. The median query now takes about 60 ms, roughly Shard 4’s own time, although the other three shards answer in about 10 ms.

    Scene: Queries arrive at 20 per second. The aggregator sends each one to all four shards at once; Shards 1–3 answer quickly, Shard 4 is eight times slower, and the aggregator replies only after Shard 4. Median query latency is about 60 ms.

    Key idea: Parallel fan-out latency = the slowest branch, not the average branch.

  8. 8. Rare slow calls become common slow requests

    Shard 4 has recovered and traffic grows to 50 queries per second, so every shard gets 50 calls per second. A typical shard call takes about 9 ms, but about 1 in 100 takes 48 ms or more (its P99): the service time has a long tail, like real servers with GC pauses, cache misses and busy neighbours.

    Each query waits for the slowest of its four calls. If each call is slow with probability 1%, a query is slow with probability 1 − 0.99⁴ ≈ 4%, and here about 5% of queries take longer than a single call’s P99. The query P50 (21 ms) is already above the call P50. Widen the fan-out and it gets worse fast: 18% for 20 calls and 63% for 100. The P99 of one server becomes the P50 of the whole request.

    Scene: Queries arrive at 50 per second and fan out to all four healthy shards. A single shard call has a P50 of about 9 ms and a P99 of about 48 ms; about 5% of queries are slower than the call P99. An annotation shows that with 100 calls per query, 63% would be.

    Key idea: Fan-out turns per-call tail latency into typical request latency: P(slow) = 1 − (1 − p)^N.

  9. 9. Hedged requests: ask a second copy

    Shard 4 is slow again, and every query pays for it: P50 about 60 ms. One fix from Google’s “The Tail at Scale”: a hedged request. Send the call to a replica of the shard as well and take whichever answer arrives first; ignore or cancel the other.

    Here a small hedge router asks Shard 4 and its replica and answers as soon as one of them has (a quorum of 1 of 2). The replica is healthy, so it nearly always wins, and the query P50 drops back to about 22 ms. This version duplicates every call, doubling the load on Shard 4’s pair; real systems wait until about the call’s P95 before sending the copy, so only ~5% of calls are duplicated. Hedge only idempotent reads.

    Scene: Shard 4 is eight times slower again. A hedge router now sends each Shard 4 call to both Shard 4 and its replica and passes on the first answer. The replica wins almost every time and median query latency drops from about 60 ms to about 22 ms.

    Key idea: Hedging trades extra load for a much shorter tail; it only works for idempotent requests.

  10. 10. What parallelism buys, and what it cannot

    Parallel workers raise throughput until something shared becomes the bottleneck: a lock, a single writer, one database row, a global counter. Amdahl’s law puts a number on it: speedup ≤ 1 ÷ serial fraction. Real systems often do worse, because coordination (lock contention, cache-line bouncing, merging results) grows with the number of workers.

    Parallel fan-out cuts latency, but the slowest branch decides, so per-call tails get amplified. Keep fan-out narrow, set per-call deadlines, return partial results where acceptable (answer when 3 of 4 shards have, and say so), and hedge idempotent reads.

    Scene: Jobs flow at 150 per second through 16 workers and the 4 ms critical section, and queries at 50 per second through the hedged fan-out, all without errors. The critical section and the aggregator are highlighted as the two places where parallelism hits its limits.

    Key idea: Find the serial part before buying cores; measure the tail before fanning out.