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 5 of 6 · Concept · 20 min · revision 1

Why scaling flattens: contention, coherency and the tail

Model sub-linear scaling with Amdahl's law and the Universal Scalability Law, fit the model to throughput samples, see how fan-out turns a backend's rare slow calls into common slow requests, and choose mitigations such as partitioning and hedged requests.

Contentsand lesson path

What you will learn

  • Explain sub-linear scaling (contention and coherency) and tail-latency amplification under fan-out, and name mitigations.

01. Why it matters

In the lab, four instances served one cart correctly. Would forty instances serve ten times as many carts? Almost never exactly. As you add nodes, each one usually adds a little less than the one before, and past some point adding nodes makes the whole system slower. The same forces stretch the slowest responses, and when one request fans out to many servers, those slowest responses become what users see.

Two effects explain why the gain shrinks. Contention is waiting for something that only one node can use at a time. Coherency is the work nodes do to keep each other up to date. This lesson models both, fits the model to measurements, then turns to the tail: why fan-out amplifies rare slowness.

02. Contention, coherency and the Universal Scalability Law

Contention comes from serial points: a single database primary, a global lock, a leader that hands out IDs, one hot row or cache key. Suppose a fraction σ (sigma) of the work must pass through such a point while the rest runs in parallel. Then the speed-up with N nodes is N ÷ (1 + σ(N − 1)). This is Amdahl's law. With σ = 0.03, 3% of the work is serial and the speed-up can never exceed 1 ÷ σ ≈ 33, however many nodes you add. The curve has a ceiling, but it never goes down.

Real systems often do worse: throughput peaks and then falls. Neil Gunther's Universal Scalability Law (USL) adds a second term for coherency:

C(N) = N ÷ (1 + σ(N − 1) + κN(N − 1))

Here C(N) is throughput with N nodes relative to one node, σ is contention as before and κ (kappa) is the coherency cost; Gunther's page writes the same two coefficients as α and β. The coherency term grows with N(N − 1), roughly the number of pairs of nodes, because in the worst case every node has to exchange updates with every other one: cache invalidations, distributed locks, membership chatter, replicated counters, transactions that span partitions. With κ = 0 the USL is exactly Amdahl's law. With any κ above zero the curve has a peak at N* = √((1 − σ) ÷ κ), and beyond it each extra node lowers total throughput. The speed of one node does not appear in that formula, so faster nodes leave the peak in place only if σ and κ stay the same. Usually they do not: when the nodes compute faster but the shared lock, database or network does not, the shared parts take a larger share of each request, σ and κ grow, and the peak moves to fewer nodes. The script below compares the three shapes for one set of assumed parameters:

Python · usl_model.py
"""Relative capacity C(N) under three models. The parameters are assumptions."""

SIGMA, KAPPA = 0.03, 0.0005  # contention (serial share), coherency (crosstalk)


def usl(n: int, sigma: float, kappa: float) -> float:
    return n / (1 + sigma * (n - 1) + kappa * n * (n - 1))


print('nodes  linear  amdahl   usl')
for n in (1, 2, 4, 8, 16, 32, 48, 64, 128):
    print(f'{n:>5}  {n:>6}  {usl(n, SIGMA, 0):>6.1f}  {usl(n, SIGMA, KAPPA):>5.1f}')
print(f'USL peak near N = {((1 - SIGMA) / KAPPA) ** 0.5:.0f} nodes')
print(f'Amdahl ceiling = {1 / SIGMA:.1f} x one node, never reached')
Expected output (a model with assumed parameters, not a measurement)
nodes  linear  amdahl   usl
    1       1     1.0    1.0
    2       2     1.9    1.9
    4       4     3.7    3.6
    8       8     6.6    6.5
   16      16    11.0   10.2
   32      32    16.6   13.2
   48      48    19.9   13.6
   64      64    22.1   13.0
  128     128    26.6    9.9
USL peak near N = 44 nodes
Amdahl ceiling = 33.3 x one node, never reached

With 3% contention alone, 64 nodes still deliver about 22 times one node. Add a small coherency cost, 0.05% per pair of nodes, and the same 64 nodes deliver 13 times, less than 48 nodes did. Up to 8 nodes the Amdahl and USL columns barely differ, so small tests can hardly tell contention from coherency. The serial part limits the gain; crosstalk between nodes can reverse it.

03. Fitting the model to your measurements

Measure throughput at several node counts, such as 1, 2, 4, 8 and more, with enough load that each configuration is saturated, and let each run settle before you read it. Divide by the one-node throughput, then estimate σ and κ by regression. The equation rearranges into a form that is linear in the two coefficients, so ordinary least squares is enough and no library is needed:

Python · usl_fit.py
"""Fit sigma and kappa to throughput samples. The samples are made up for practice."""

samples = {1: 400, 2: 772, 4: 1405, 8: 2440, 16: 3530, 24: 4100, 32: 4180}

# With C = X(N) / X(1) and x = N - 1, the USL rearranges to
#   N / C - 1 = sigma * x + kappa * x * (x + 1)
# which is linear in sigma and kappa, so ordinary least squares solves it.
rows = []
for n, x_n in samples.items():
    if n == 1:
        continue
    x, c = n - 1, x_n / samples[1]
    rows.append((x, x * (x + 1), n / c - 1))
saa = sum(a * a for a, _, _ in rows)
sab = sum(a * b for a, b, _ in rows)
sbb = sum(b * b for _, b, _ in rows)
say = sum(a * y for a, _, y in rows)
sby = sum(b * y for _, b, y in rows)
det = saa * sbb - sab * sab
sigma = (say * sbb - sby * sab) / det
kappa = (sby * saa - say * sab) / det
print(f'sigma = {sigma:.3f}, kappa = {kappa:.5f}')


def gain(n: float) -> float:  # model throughput at n nodes, relative to one node
    return n / (1 + sigma * (n - 1) + kappa * n * (n - 1))


if sigma >= 1 or max(gain(n) for n in samples) < 1.1:  # flat in the measured range
    print('no gain from more nodes: one shared serial point limits the whole set-up')
elif abs(sigma) < 0.001 and abs(kappa) < 0.00001:
    print('close to linear: no contention or coherency cost seen in this range')
elif sigma < 0:  # superlinear effects, or too few and noisy points
    print('sigma < 0: superlinear or noisy data; this simple fit cannot place a peak')
elif kappa <= 0:  # contention only, as in Amdahl's law
    print(f'no coherency cost seen: levels off near {samples[1] / sigma:,.0f} req/s')
else:
    peak_n = ((1 - sigma) / kappa) ** 0.5
    peak_x = samples[1] * gain(peak_n)
    print(f'model peak: about {peak_n:.0f} nodes, about {peak_x:,.0f} req/s')
Expected output
sigma = 0.039, kappa = 0.00085
model peak: about 34 nodes, about 4,196 req/s

The samples are invented for this exercise. The fit says contention is about 3.9%, coherency about 0.085% per pair, and the peak sits near 34 nodes at roughly 4,200 requests/s. Not every fit has a peak, and the script says why. A σ of 1 or more means throughput does not grow with nodes at all: one shared serial point limits the whole set-up, and more node counts on that set-up will not change it. A κ of zero or below means no coherency cost shows in the measured range, so throughput levels off as in Amdahl's law. A negative σ usually means too few or noisy points, though real superlinear effects, such as a combined cache that grows with the nodes, can cause it too; this simple fit does not handle them. Use a good fit in three ways: to estimate where more nodes stop paying for themselves, to decide where to look (a large σ points to a serial bottleneck, a large κ to crosstalk between nodes), and to check whether a fix worked, by fitting again afterwards. Do not predict far beyond the largest N you measured, and remember that the model never says which resource is contended; profiles and metrics do.

04. The tail: fan-out turns rare slowness into the common case

Many requests fan out: a search page queries 50 index partitions in parallel, a dashboard calls 20 services. Such a request is as slow as its slowest call. If each call is slow with a small probability p, independently of the others, the chance that a request waiting on n calls meets at least one slow call is 1 − (1 − p)^n:

Python · fanout.py
# Chance that a request waiting on n parallel calls meets at least one slow call,
# when each call is slow with probability p and calls are independent.
for p in (0.01, 0.001):
    row = '  '.join(f'n={n:<3} {1 - (1 - p) ** n:6.1%}' for n in (1, 10, 50, 200))
    print(f'p={p:<5}  {row}')
Expected output
p=0.01   n=1     1.0%  n=10    9.6%  n=50   39.5%  n=200  86.6%
p=0.001  n=1     0.1%  n=10    1.0%  n=50    4.9%  n=200  18.1%

With 1% of calls slow, a request that fans out to 50 calls is slow 39.5% of the time, and at 200 calls 86.6%. A backend's rare tail becomes the front end's normal experience, which is why fan-out systems are judged by high percentiles such as p99, not by averages. Dean and Barroso's paper The Tail at Scale lists where the slowness comes from: resources shared on one machine, background work and garbage collection, queueing at many layers, and hardware that throttles itself. Notice what does not help. Adding instances does not remove variability, and splitting data into more partitions raises the fan-out. Moderate utilisation does help, because lesson 02 showed queueing delay rising steeply near saturation, and that delay lands hardest on the tail.

05. Mitigations

Contention and coherency are cured by design changes. Shrink the serial part: partition the hot thing, batch updates, keep per-node counters and merge them every few seconds when a slightly stale total is acceptable, and replace one global lock with many narrower ones. Cut crosstalk: avoid shared mutable state that every node must keep in sync, prefer one owner per piece of data over copies that must all be invalidated, and choose partition keys so that most requests touch one partition.

For the tail, The Tail at Scale describes techniques that accept variability and work around it:

  • Hedged requests. Send the request to one replica; if no answer has arrived by about the 95th-percentile latency, send a copy to another replica and use whichever answers first. Only the slowest few per cent get a second copy, so the extra load stays small.
  • Tied requests. Queue the request on two servers at once, and let each tell the other when it starts work, so the second copy is cancelled.
  • Micro-partitions and selective replication. Use many more partitions than machines, so load can move in small pieces, and keep extra copies of the hottest ones.
  • Latency-induced probation and good-enough results. Stop sending traffic to a server that is unusually slow for a while, and, where the product allows, answer with the results that arrived before a deadline.

The simulation below shows hedging under its key assumption: replicas hiccup independently of each other and of the request.

Python · hedging_sim.py
"""Simulated latencies for one backend call, with and without a hedged copy.

Model, not a measurement: 97% of calls take about 10-30 ms; 3% hit a hiccup
(a pause, a busy disk) that adds 200-400 ms. Replicas hiccup independently.
"""

import random

random.seed(42)
N = 200_000


def one_call() -> float:
    ms = random.uniform(10, 30)
    if random.random() < 0.03:
        ms += random.uniform(200, 400)
    return ms


def pct(values: list[float], p: float) -> float:
    return sorted(values)[int(p / 100 * len(values)) - 1]


plain = [one_call() for _ in range(N)]
hedge_after = pct(plain, 95)  # send a second copy only if no answer by p95
hedged, extra = [], 0
for first in plain:
    if first <= hedge_after:
        hedged.append(first)
    else:
        extra += 1
        hedged.append(min(first, hedge_after + one_call()))

print(f'hedge after {hedge_after:.0f} ms; extra calls: {extra / N:.1%}')
for p in (50, 95, 99, 99.9):
    print(f'p{p:<4}  plain {pct(plain, p):5.0f} ms   hedged {pct(hedged, p):5.0f} ms')
Expected output (a simulation with a fixed seed, not a measurement)
hedge after 30 ms; extra calls: 5.0%
p50    plain    20 ms   hedged    20 ms
p95    plain    30 ms   hedged    30 ms
p99    plain   354 ms   hedged    53 ms
p99.9  plain   413 ms   hedged    60 ms

In this model, hedging after the 95th percentile adds 5% more calls and cuts p99 from 354 ms to 53 ms. Two warnings. If a request is slow because of what it asks for, such as a very large report, its copy is just as slow and hedging only adds load. And a hedged request may be executed twice, so hedge only operations that are safe to repeat: reads, or writes made idempotent.

06. Check your understanding

Practice check · 3 questions

Sub-linear scaling and the tail

Three questions about the models and the mitigations.

Q1. A fit of throughput measurements gives σ = 0.02 and κ = 0.0002. According to the USL, roughly where does adding nodes stop increasing throughput?
Q2. A USL fit of your service gives σ = 0.01 and κ = 0.002, so throughput peaks near 22 nodes, and you need more. Which change is most likely to move that peak to a larger node count?
Q3. A team adds hedged requests to a reporting API. Load rises by about 5%, but p99 barely moves. The slowest requests turn out to be exports of very large reports. Why did hedging not help?
Practice only: not graded, not saved, not evidence.

07. Apply it

Finish the practice task of this skill. With the cart service from the lab, run python client.py bench 4000 16 against one to six instances (STORE=pg ./fleet.sh start N), three times each, and keep the median throughput for each count. Put the six numbers into usl_fit.py and read off σ, κ and the peak. On one machine the instances share CPU cores, one proxy process and one PostgreSQL server, and bench waits for each response, so expect a flat curve and the message that more nodes bring no gain: that is contention you can name. Measuring the instances themselves would need more load-generating machines and a database on its own host. Write down one change that would lower σ and one that would lower κ for this service, and compare them with your lesson 01 note.

08. Review prompt

Without looking back: define contention and coherency, with two real sources of each; write the USL and explain which term makes throughput fall rather than level off; describe how to fit it to measurements and two things a fit can and cannot tell you; explain why fan-out turns a backend's p99 into a common case for the front end; and describe hedged requests, the assumption they rely on and one situation where they do not help.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

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