Sub topic 9
Fan-out and tail latency amplification
This chapter assumes you have read the chapters on percentiles and on latency budgets. You should be comfortable with p50, p99, and the idea that an end-to-end target is split across components. You also need basic Python and probability arithmetic: multiplying independent probabilities and raising them to a power.
What fan-out is
Fan-out means that one incoming request causes a service to send many requests to other services or shards. The original request is called the parent. The requests it creates are called children. Common examples:
- A search front end queries 50 index shards and merges the results.
- A home feed service calls a profile service, a ranking service, an ads service, and a recommendation service.
- A product page makes 30 calls to a catalog database to load related items.
There are two shapes of fan-out, and they behave differently.
| Shape | How children run | Parent latency | Example |
|---|---|---|---|
| Parallel, wait for all | At the same time | Slowest child, plus merge time | Search across shards |
| Sequential | One after another | Sum of the children | A chain of 5 dependent lookups |
| Parallel, wait for k of n | At the same time | The k-th fastest child | Quorum read from replicas |
This chapter focuses on parallel fan-out where the parent waits for all children. It is the case where tail latency is amplified most visibly.
Why the tail gets worse
A parent that waits for all children is as slow as its slowest child. Even if each child is usually fast, the chance that at least one of them is slow rises with the number of children.
Suppose each child call is slower than its p99 with probability 1% (it is "slow" 1 time in 100). If the children are independent, the chance that all n children are fast is 0.99 raised to the power n. The chance that at least one is slow is the complement.
# Chance that at least one of n parallel backend calls is slower than its p99
p_fast = 0.99
for n in (1, 10, 100):
p_slow_somewhere = 1 - p_fast ** n
print(n, round(p_slow_somewhere, 3))
# 1 0.01
# 10 0.096
# 100 0.634With 100 children, about 63% of parent requests include at least one child that is slower than the child's p99. The child's p99 has become closer to the parent's median experience. This is tail latency amplification: a rare event per child becomes a common event per parent.
Working out the percentile you need from each child
You can invert the formula. If the parent should meet its target for a fraction q of requests, and the parent waits for n independent children, each child must be fast with probability q raised to the power 1/n.
def required_child_quantile(parent_quantile: float, n: int) -> float:
"""Quantile each of n independent children must meet so that the
parent, which waits for all of them, meets parent_quantile."""
return parent_quantile ** (1 / n)
for n in (1, 10, 50, 100):
q = required_child_quantile(0.99, n)
print(n, f"{q * 100:.4f}%")
# 1 99.0000%
# 10 99.8995%
# 50 99.9799%
# 100 99.9900%To keep the parent p99 within a target with 100 children, each child must meet that target at about p99.99. A target phrased as "the database p99 is under 120 ms" is not enough if 100 database calls sit under one request. You would need a p99.99 target for the database, and p99.99 is much harder to measure and to achieve, because it needs many samples and is dominated by rare events such as pauses, retries, and cache misses.
The diagram shows the shape of the problem.
A simulation you can run
Formulas are easy to get wrong in direction, so check them with a simulation. The code below draws child latencies from a distribution with a long tail, takes the maximum of n children, and reports parent percentiles.
import math
import random
def percentile(samples, p):
ordered = sorted(samples)
rank = math.ceil(p / 100 * len(ordered))
return ordered[rank - 1]
def child_latency_ms(rng):
# Mostly about 10-20 ms, with a 1% chance of a slow call of 200-400 ms.
if rng.random() < 0.01:
return rng.uniform(200, 400)
return rng.uniform(10, 20)
def parent_latency_ms(rng, n):
return max(child_latency_ms(rng) for _ in range(n))
rng = random.Random(42)
trials = 20000
for n in (1, 10, 100):
samples = [parent_latency_ms(rng, n) for _ in range(trials)]
print(
f"n={n:3d} p50={percentile(samples, 50):6.1f} ms"
f" p99={percentile(samples, 99):6.1f} ms"
)The output varies slightly with the random seed, but the pattern is stable. With n=1 the median is about 15 ms and the p99 sits at the edge of the slow band. With n=10 the median is still near 15 ms, though about 1 request in 10 is now slow. With n=100 the median itself is in the slow band, around 200 ms or more, because most parent requests include at least one slow child. The median of the parent moved even though the typical child did not change.
Mitigations
You can attack the problem from four directions: reduce n, reduce the child tail, tolerate slow children, and set the targets correctly.
Reduce the fan-out
The cheapest fix is to call fewer things. Options include:
- Cache or denormalize data so that one lookup replaces many.
- Batch many small reads into one request to the same backend. This turns n calls into one call that does n units of work.
- Use a smaller number of larger shards if the sharding is finer than the data volume needs.
- Make calls that do not affect the visible result asynchronous, so the parent does not wait for them.
Hedged requests
A hedged request sends the same call to a second replica if the first has not answered within a delay. The parent uses whichever response arrives first. A typical delay is the child's p95 latency. Only about 5% of calls then send a second request, so the extra load is small, but most slow calls get a second chance.
import asyncio
import random
async def call_replica(name: str, rng: random.Random) -> str:
# Simulated backend: usually fast, occasionally very slow.
delay = 0.3 if rng.random() < 0.05 else 0.02
await asyncio.sleep(delay)
return name
async def hedged_call(rng: random.Random, hedge_after_s: float = 0.05) -> str:
first = asyncio.create_task(call_replica("replica-a", rng))
done, _ = await asyncio.wait({first}, timeout=hedge_after_s)
if done:
return first.result()
second = asyncio.create_task(call_replica("replica-b", rng))
done, pending = await asyncio.wait(
{first, second}, return_when=asyncio.FIRST_COMPLETED
)
for task in pending:
task.cancel()
return next(iter(done)).result()
async def main():
rng = random.Random(1)
print(await hedged_call(rng))
asyncio.run(main())Hedging has limits. It only helps when slowness is specific to one replica or one moment. If the backend is slow because it is overloaded, a second request adds load and makes the overload worse. Hedged calls must also be safe to repeat, so they suit reads and idempotent writes.
Partial results and deadlines
Some features can return a useful answer without every child. A search page can return results from 98 of 100 shards and mark the response as partial. A feed can drop the recommendations panel if it is late. Give each child a deadline that comes from the parent's latency budget, and decide in advance what the parent does when a deadline expires. Propagate the remaining deadline downward so that children stop work that no one is waiting for.
Tighter child targets
When you must wait for all children, derive the child target from the formula above rather than copying the parent target. State it explicitly, for example: "Each shard answers within 40 ms at p99.9, so that the 50-shard query answers within 40 ms plus merge time at p95 or better." Then check that you can measure at that quantile. Measuring p99.9 reliably needs thousands of samples per window, so a service with low traffic will see noisy values.
Common errors
- Using the average child latency to predict the parent. The parent depends on the maximum of the children, not the mean. A child with a 15 ms average and a rare 300 ms outlier produces a parent that is often near 300 ms.
- Adding p99 values. Percentiles do not add. Sequential stages and parallel fan-out combine differently, and neither is a simple sum of p99s.
- Forgetting the merge cost. The parent also spends time sending requests, waiting on connection pools, and combining results. This cost often grows with n.
- Assuming independence. If slow calls come from a shared cause, the model above is wrong in both directions. Measure the parent directly.
- Retrying without limits. Retries and hedges add load. A retry budget, such as allowing retries for at most 10% of calls, keeps a slow backend from receiving a storm of duplicates.
- Ignoring the load multiplier. Fan-out multiplies backend traffic. A parent rate of 2,000 requests per second with 50 children means 100,000 child requests per second. Size the child services for that rate, not for the parent rate.
Putting it into a target
A workable process for a fan-out path:
- Count the children per parent request, at peak, including retries and hedges.
- Choose the parent target, for example p99 under 300 ms.
- Compute the child quantile required with
required_child_quantile. - Decide whether the child can meet that quantile. If not, reduce n, add hedging, or allow partial results.
- Compute child request rate as parent rate times n, and size backends for it.
- Measure the parent latency end to end, and compare it with your prediction.
Exercise
A request fans out to 40 independent shards and waits for all of them. Each shard exceeds its p99 latency on 1% of calls. What fraction of parent requests includes at least one shard call slower than its p99? Then, what quantile must each shard meet if the parent should meet its target for 99% of requests?
Show answer
The chance that all 40 calls are fast is 0.99^40, which is about 0.669. So about 1 − 0.669 = 0.331, or 33%, of parent requests include at least one slow call. For the second part, each shard must meet its target with probability 0.99^(1/40), which is about 0.99975, so the shards need a p99.975 target (roughly p99.98).
Exercise
A parent service handles 500 requests per second, and each request makes 20 parallel calls to a database. The database p99 is 30 ms and its average is 8 ms. Why is "the database meets its p99 target of 30 ms" not enough to promise a parent p99 of about 30 ms, and how many database requests per second must the database handle?
Show answer
The parent waits for the slowest of 20 calls. If each call exceeds 30 ms on 1% of requests, about 1 − 0.99^20 ≈ 18% of parent requests include a call slower than 30 ms, so the parent p99 will be above 30 ms. The database must handle 500 × 20 = 10,000 requests per second, plus any retries or hedged calls.