Tail latency and overload
Why p99 decides the experience at scale, how to tolerate slow replicas with hedged requests, and how to survive demand beyond capacity with bounded queues, load shedding, retry budgets, adaptive limits and an eye on metastable failures.
ConceptApplied19 min readUpdated
- 8 code samples
- 7 interviewer follow-ups
- 3 self-checks
On this page9 sectionsHLDSenior depth
Read first: Latency, throughput and queues, Rate limiting
- Explain why the tail dominates at scale, using the fan-out math.
- Use hedged requests and the other tail-tolerance techniques, and state what each costs.
- Describe what happens past capacity: queues, zombie work, retry amplification and metastable failures.
- Choose among bounded queues, deadlines, load shedding, adaptive LIFO, retry budgets, client-side throttling and adaptive concurrency limits.
- Answer "a service is overloaded, what do you do?" in order.
7 code samples (162 lines), collapsed so the explanation stays in focus.
Two problems sit behind most large-scale latency incidents. The first is the tail: a small fraction of slow requests that, across thousands of servers and millions of users, decides what people experience. The second is overload: demand beyond capacity, where a small slowdown can turn into an outage because queues and retries feed on themselves. Both are queueing problems, and the first lesson in this section gave you the vocabulary. This lesson is about what to do.
A service where 1% of requests are slow looks healthy on a dashboard. Now let a user request wait for n such calls in parallel. The chance that at least one is slow is 1 - 0.99^n:
| Parallel calls per request | Requests that hit a slow call |
|---|---|
| 1 | 1% |
| 10 | 9.6% |
| 100 | 63% |
| 1,000 | more than 99.99% |
With 100 calls, a component's p99 is what most users get. This is why large systems manage p99.9 and beyond, and why average latency tells you almost nothing about them.
The slowness is rarely a bug. In their paper "The Tail at Scale", Jeff Dean and Luiz Barroso list ordinary sources of variability in shared, complex systems: contention for shared resources (other tenants, other processes), background work (garbage collection, compactions, index merges, log flushes), queueing at several layers, power and thermal limits, network retransmissions, cache misses and maintenance activity. You cannot remove all of them, so large systems are built to tolerate them, the way they tolerate failed machines.
The paper groups the techniques by how fast they act.
| Technique | How it works | Cost and conditions |
|---|---|---|
| Hedged request | Send the request to one replica. If it has not answered within about the 95th percentile of the expected latency, send a copy to a second replica, use whichever answer arrives first and cancel the other | About 5% extra requests by construction. The call must be safe to repeat (idempotent) and replicas must slow down independently |
| Tied request | Send to two replicas at once, each told about the other. When one starts executing, it tells the other to drop the request | Removes most duplicate work, but needs cancellation between servers. Good against queueing delay |
| Micro-partitions | Many more partitions than machines, so load and recovery move in small pieces | More metadata to manage |
| Selective replication | Extra replicas for hot items | Storage and consistency work for those items |
| Latency-induced probation | Stop sending real traffic to a machine that is slow right now, keep probing it, and return it when it recovers | Needs good health measurement, or it flaps |
| Good-enough responses | When the deadline arrives, return what you have (results from 99% of shards) | The product must accept partial answers |
| Canary requests | In a very wide fan-out, send the request to one or two servers first, and fan out only if they survive | Adds a small delay, protects against a "query of death" that would crash every server |
Erasure-coded storage has a hedge built in: any k of n fragments rebuild the data, so a read can ask for more than k and use the first k to arrive (the erasure coding lesson measures it: a p99 of 220 ms fell to 40 ms for 17% more bytes read).
The authors report one measurement that shows how strong hedging is: reading 1,000 values spread over 100 BigTable servers, a backup request sent after a 10 ms delay cut the 99.9th percentile of the whole read from 1,800 ms to 74 ms, for 2% more requests. The simulation below reproduces the effect with a simple model: each request takes about 10 ms, and 2% of the time a slow event (a pause, a busy neighbor) adds 200 ms to that replica.
C# · Replica, Tail
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
public sealed class Replica
{
private readonly Random _random;
public Replica(int seed) { _random = new Random(seed); }
/// <summary>One request's latency: about 10 ms plus jitter, and 2% of the time a slow event adds 200 ms.</summary>
public double Latency()
{
double jitter = -2 * Math.Log(1 - _random.NextDouble());
double slow = _random.NextDouble() < 0.02 ? 200 : 0;
return 10 + jitter + slow;
}
}
public static class Tail
{
public static double Percentile(List<double> sorted, double p) =>
sorted[Math.Clamp((int)Math.Ceiling(p * sorted.Count), 1, sorted.Count) - 1];
/// <summary>Latencies (sorted) when a backup request goes out if the first has not answered within `hedgeAfterMs`.
/// The two replicas slow down independently. Also returns the share of requests that needed a backup.</summary>
public static (List<double> Sorted, double ExtraLoad) Hedged(Replica replica, int requests, double hedgeAfterMs)
{
var latencies = new List<double>();
int backups = 0;
for (int i = 0; i < requests; i++)
{
double first = replica.Latency();
if (first <= hedgeAfterMs) { latencies.Add(first); continue; }
backups++;
latencies.Add(Math.Min(first, hedgeAfterMs + replica.Latency())); // whichever answer comes first wins
}
latencies.Sort();
return (latencies, (double)backups / requests);
}
}var replica = new Replica(seed: 21);
var plain = Enumerable.Range(0, 100_000).Select(_ => replica.Latency()).OrderBy(x => x).ToList();
double hedgeAfter = Tail.Percentile(plain, 0.95); // back up only the slowest 5%: about 17 ms
var (hedged, extraLoad) = Tail.Hedged(replica, 100_000, hedgeAfter);
Debug.Assert(Tail.Percentile(plain, 0.99) > 200); // 2% of requests are slow, so the p99 is slow
Debug.Assert(Tail.Percentile(hedged, 0.99) < 40); // with a backup, p99 is close to normal (about 28 ms)
Debug.Assert(Tail.Percentile(hedged, 0.50) < Tail.Percentile(plain, 0.50) * 1.05); // the median is not hurt
Debug.Assert(extraLoad > 0.04 && extraLoad < 0.06); // and it costs about 5% more requestsHedging has sharp edges. The call must be idempotent, or hedged writes will apply twice. It only helps when the slowness is independent across replicas: if every replica shares the cause (an overloaded database, a bad deploy), hedging adds load to a system that is already hurting. So hedge with a budget, and switch it off when error rates or queue depth rise.
In an open system (see the load testing lesson), arrivals do not slow down because the server is busy. When arrivals exceed capacity, the queue grows without bound and the wait is the backlog divided by the service rate. Three effects make it worse than the arithmetic alone.
Zombie work. Once the wait exceeds the client's timeout, every request the server finishes is for a client that has already given up. The server is busy, its throughput looks normal, and its goodput is zero. First-in-first-out ordering makes this worst: it serves the oldest, most abandoned requests first.
Retry amplification. Clients that time out try again, so the offered load rises exactly when capacity is short. The effect multiplies across layers: five layers that each make three attempts can send up to 3^5 = 243 attempts to the bottom layer for one user request.
Metastable failure. A trigger (a traffic spike, a cache flush, a slow deploy) pushes the system over its limit. If a feedback loop then sustains the overload (retries, cache misses sending more load to the database, queues full of stale work), the system stays down even after the trigger is gone. It is stable in the failed state. Bronson and co-authors named this pattern in 2021, and a 2022 study of 22 incidents from 11 organizations found that it appears across the industry. Recovery means breaking the loop: shed load, stop retries, drain queues, restore caches gradually.
trigger: a traffic spike, a slow dependency, a cache flush
|
v
latency rises --> clients time out --> clients retry
^ |
| v
queues grow <-- offered load = new requests + retries
(the loop can keep itself going until something breaks it)Think in layers, from the caller to the data tier. Every defense answers one question: how do we stop the loop above?
1. Bound every queue and every concurrency. An unbounded queue turns overload into slow failure for everyone. A bounded one turns it into fast rejection for the overflow. A queue is a latency promise: 100 waiting items at 10 ms each promise a one-second wait, so size queues from the delay you can tolerate, not from the memory you have.
2. Deadlines, not just timeouts. Give every request an absolute deadline and pass the remaining time to each call it makes, so downstream work stops when the caller has stopped waiting. Drop requests whose deadline has already passed before doing any work on them. Set timeouts from the dependency's latency distribution, just above its p99.9, rather than a round number.
3. Shed load early and cheaply. Rejecting a request costs far less than serving it, but only if the check happens before parsing, authentication and database calls. Return 503 or 429 with Retry-After. Shed by priority (health checks and paid traffic last, batch and prefetch first) and by fairness (one noisy client must not use the whole budget). The rate limiter from the earlier lesson is one such mechanism, applied at a fixed rate.
4. Choose the queue discipline. FIFO is fair when the system is healthy and cruel when it is not. Two ideas from practice fix that. Controlled delay (CoDel, from network queues): if the delay of the packets leaving the queue stays above a small target (5 ms by default in Linux) for a full interval (100 ms), start dropping, so a standing queue never forms. Adaptive LIFO: serve first-in-first-out normally, but when a queue builds, serve the newest requests first, since their clients are still waiting. Facebook's engineers described using both for their request queues in "Fail at Scale".
5. Retry with discipline.
- Retry only idempotent calls, and only on errors that retrying can fix.
- Back off exponentially, with jitter, so retries from many clients do not synchronize.
- Retry in one layer, not all of them.
- Cap retries with a budget: a small fraction of recent traffic. gRPC's retry throttling is a token bucket per server: each failed call spends one token, each success returns a fraction of one (
tokenRatio), and retries stop while the bucket is at or below half full. During an outage almost nothing is retried; in normal times the retry rate can reach the token ratio. - Count hedged requests as retries.
6. Throttle on the client. The Google SRE book describes adaptive throttling: each client keeps, over the last two minutes, the number of requests it attempted and the number the backend accepted. It rejects new requests locally with probability max(0, (requests − K × accepts) / (requests + 1)), with K = 2 as the suggested starting point. If the backend accepts everything, the probability is zero. Once the backend accepts less than half, clients start dropping their own requests without sending them, which keeps the offered load near K times what the backend can actually take instead of piling on.
7. Let the limit adapt. A static pool size is a guess that is wrong on the day a dependency slows. Netflix's engineers described adaptive concurrency limits: measure latency, and let the allowed number of in-flight requests rise while latency stays near its no-load baseline and fall when it does not. The simple form is AIMD (add one, multiply by a factor below one), borrowed from TCP congestion control. This is Little's Law in a feedback loop: the right concurrency is the one that keeps queueing delay small.
8. Degrade on purpose. Serve stale cache, drop optional features (recommendations, personalization), return partial results. A degraded answer in 50 ms beats a perfect one that never arrives.
9. Stop sending traffic to what is failing. A circuit breaker opens after a run of failures, fails calls immediately, and lets a few probes through to test recovery. Pair it with bulkheads (separate pools per dependency), so one slow dependency cannot take every thread. The notification service lesson simulates a provider outage with and without a breaker.
10. Remove the restart cliff. A cold cache or a cold connection pool can recreate the overload during recovery. Coalesce duplicate requests, warm caches before taking traffic, and bring instances back gradually.
Client-side throttling in C#
C# · AdaptiveThrottle
public sealed class AdaptiveThrottle
{
private readonly double _k;
private readonly int _windowSeconds;
private readonly Queue<(double Requests, double Accepts)> _seconds = new Queue<(double, double)>();
private double _requests, _accepts;
public AdaptiveThrottle(double k, int windowSeconds) { _k = k; _windowSeconds = windowSeconds; }
/// <summary>The chance that the next request is rejected locally, without being sent.</summary>
public double RejectProbability => Math.Max(0, (_requests - _k * _accepts) / (_requests + 1));
/// <summary>Close one second. `requests` counts everything the application attempted, including requests this
/// throttle rejected itself. `accepts` counts what the backend accepted.</summary>
public void EndSecond(double requests, double accepts)
{
_seconds.Enqueue((requests, accepts));
_requests += requests;
_accepts += accepts;
if (_seconds.Count > _windowSeconds)
{
var old = _seconds.Dequeue();
_requests -= old.Requests;
_accepts -= old.Accepts;
}
}
}C# · 400 requests per second are offered, but the backend can accept only 100 per second.
// 400 requests per second are offered, but the backend can accept only 100 per second.
var throttle = new AdaptiveThrottle(k: 2, windowSeconds: 120);
double backendCapacity = 100, sentToBackend = 0;
for (int second = 0; second < 300; second++)
{
sentToBackend = 400 * (1 - throttle.RejectProbability);
throttle.EndSecond(requests: 400, accepts: Math.Min(sentToBackend, backendCapacity));
}
Debug.Assert(Math.Abs(sentToBackend - 200) < 1); // the backend is offered K x its capacity, not 400
Debug.Assert(Math.Abs(throttle.RejectProbability - 0.5) < 0.001); // half of the attempts never leave the client
backendCapacity = 1000; // the backend recovers
for (int second = 0; second < 200; second++)
{
sentToBackend = 400 * (1 - throttle.RejectProbability);
throttle.EndSecond(400, Math.Min(sentToBackend, backendCapacity));
}
Debug.Assert(throttle.RejectProbability < 0.001); // and the clients stop throttling once it accepts again
Debug.Assert(Math.Abs(Math.Max(0, (100 - 2.0 * 20) / 101.0) - 0.594) < 0.001); // 100 attempts and 20 accepted: reject about 59%A retry budget in C#
C# · RetryBudget
public sealed class RetryBudget
{
private readonly double _max, _ratio;
public RetryBudget(double maxTokens, double tokenRatio) { _max = maxTokens; _ratio = tokenRatio; Tokens = maxTokens; }
public double Tokens { get; private set; }
/// <summary>Retries are allowed only while more than half of the tokens remain.</summary>
public bool CanRetry => Tokens > _max / 2;
public void RecordFailure() => Tokens = Math.Max(0, Tokens - 1);
public void RecordSuccess() => Tokens = Math.Min(_max, Tokens + _ratio);
}C#
var budget = new RetryBudget(maxTokens: 10, tokenRatio: 0.1);
int retriesAllowed = 0;
for (int failure = 0; failure < 20; failure++)
{
budget.RecordFailure();
if (budget.CanRetry) retriesAllowed++;
}
Debug.Assert(retriesAllowed == 4); // twenty failures in a row earn only four retries
for (int success = 0; success < 40; success++) budget.RecordSuccess();
Debug.Assert(!budget.CanRetry); // forty successes are not yet enough to trust it again
for (int success = 0; success < 20; success++) budget.RecordSuccess();
Debug.Assert(budget.CanRetry); // sixty areAn adaptive concurrency limit in C#
The model server keeps its baseline latency until concurrency passes a sweet spot, then queueing makes latency grow in proportion (Little's Law again). The limiter does not know the sweet spot. It only sees latency.
C# · AimdLimit, ModelServer
public sealed class AimdLimit
{
private readonly double _tolerance, _backoff;
public AimdLimit(double initial, double tolerance, double backoff) { Limit = initial; _tolerance = tolerance; _backoff = backoff; }
/// <summary>How many requests may be in flight at once.</summary>
public double Limit { get; private set; }
public bool TryAcquire(int inFlight) => inFlight < (int)Limit;
/// <summary>Grow by one while latency is near its no-load baseline. Shrink by a factor when it is not.</summary>
public void OnSample(double latencyMs, double baselineMs)
{
if (latencyMs > _tolerance * baselineMs) Limit = Math.Max(1, Limit * _backoff);
else Limit += 1;
}
}
public sealed class ModelServer
{
private readonly double _baseMs;
private readonly int _sweetSpot;
public ModelServer(double baseMs, int sweetSpot) { _baseMs = baseMs; _sweetSpot = sweetSpot; }
public double LatencyMs(int inFlight) => _baseMs * Math.Max(1.0, (double)inFlight / _sweetSpot);
}C#
var limiter = new AimdLimit(initial: 10, tolerance: 1.2, backoff: 0.9);
var server = new ModelServer(baseMs: 20, sweetSpot: 40);
double lowest = double.MaxValue, highest = 0;
for (int step = 0; step < 300; step++)
{
limiter.OnSample(server.LatencyMs((int)limiter.Limit), baselineMs: 20);
if (step >= 100) { lowest = Math.Min(lowest, limiter.Limit); highest = Math.Max(highest, limiter.Limit); }
}
Debug.Assert(lowest > 40 && highest < 55); // it climbs from 10 and settles just above the sweet spot of 40
server = new ModelServer(baseMs: 20, sweetSpot: 20); // a dependency degrades: the server now copes with half the concurrency
lowest = double.MaxValue; highest = 0;
for (int step = 0; step < 300; step++)
{
limiter.OnSample(server.LatencyMs((int)limiter.Limit), baselineMs: 20);
if (step >= 100) { lowest = Math.Min(lowest, limiter.Limit); highest = Math.Max(highest, limiter.Limit); }
}
Debug.Assert(lowest > 18 && highest < 30); // and the limit follows it down without anyone changing a settingInterviewer follow-upL5Why do large systems care about p99.9 when the average is fine?How to answer
Because fan-out turns rare events into common ones. If a request waits for 100 backends that are each slow 1% of the time, 63% of requests include a slow call. The tail of each component becomes the typical experience of the whole. Tail control is how you keep the larger system fast.
Interviewer follow-upL6Explain hedged requests: when do they help, what do they cost and what can go wrong?How to answer
A hedge sends a backup request to another replica when the first has not answered within roughly the p95, and uses the first reply. It cuts the tail when slowness is random and independent per replica (garbage collection pauses, a busy neighbor, a bad disk), at the cost of about 5% more requests. It goes wrong if the operation is not idempotent, if the replicas share the cause of the slowness (hedging an overloaded database adds load), or if hedging is unbounded during an incident. Bound it with a budget, cancel the loser, and turn it off when errors or queue depth rise.
Interviewer follow-upL6Why is FIFO a bad queue discipline during overload?How to answer
Under overload the oldest requests have waited longest, and their clients have usually timed out already. FIFO spends capacity on exactly those requests, so the server stays busy while goodput approaches zero. Serving the newest requests first (adaptive LIFO), dropping requests whose deadline has passed, and dropping from a standing queue (controlled delay) all spend capacity on work someone still wants.
Interviewer follow-upL6A service is overloaded. What do you do in the first ten minutes?How to answer
Stop the loop before looking for the cause. Shed or disable non-critical traffic and optional features. Turn off retries and hedging upstream, or lower their budgets. Make sure queues are bounded and expired requests are dropped. Add capacity only if it can start safely (cold instances can make it worse), and bring it in gradually. Watch for a feedback loop (retries, cache misses, queue growth) that keeps the overload alive after the trigger has passed. Communicate what is degraded. Afterwards find the trigger and add the missing limit, deadline or budget.
Interviewer follow-upL7Design the retry policy for a call chain of four services.How to answer
Retry in one layer only, usually the one closest to the failing dependency or the edge that owns the user's deadline, so attempts do not multiply (three attempts at each of four layers is up to 81 attempts on the last one). Propagate an absolute deadline so no layer works past it. Retry only idempotent calls, with exponential backoff and full jitter, under a retry budget (a token bucket tied to success rate), and honor Retry-After. Return an explicit "do not retry" signal from overloaded servers, and make clients obey it. Use idempotency keys for writes that must be retried.
Interviewer follow-upL7What is a metastable failure, and how do you design against it?How to answer
A system enters a failed state that persists after the trigger (a spike, a cache flush, a deploy) is gone, because a feedback loop sustains it, such as retries, cache misses overloading the database, or queues full of stale work. Design against it by removing the amplifiers: bounded queues, expired-request dropping, retry budgets, client-side throttling, load shedding and graceful degradation. Avoid cliffs where recovery needs more capacity than normal operation does (cold caches, thundering herds on restart). Test it: run stress tests that push beyond capacity and then back down, and measure whether the system recovers on its own and how long that takes.
Interviewer follow-upL7How do you choose a timeout for a call to a dependency?How to answer
From data: look at the dependency's latency distribution and set the timeout just above a high percentile (p99.9) of healthy behavior, and always within the caller's remaining deadline. A timeout well above that wastes threads and connections on calls that will not succeed; one below it creates retries for requests that would have finished. Downstream timeouts must be shorter than upstream ones, and the total across retries must fit inside the budget. No timeout at all is a bug.
- Name the failure mode: is it the tail (variability) or overload (demand beyond capacity)?
- For the tail: reduce variability at the source, then tolerate it with hedged or tied requests, probation and partial results, with budgets.
- For overload: bound queues and concurrency, propagate deadlines, shed early by priority, and pick a queue discipline that serves the requests still wanted.
- Control the clients: backoff with jitter, retry budgets in one layer, client-side throttling and hedging with a cap.
- Make limits adaptive: latency-based concurrency limits instead of static pool sizes.
- Plan for recovery: break feedback loops, warm caches, restore gradually.
- Prove it: a stress test past capacity, a recovery test, and alerts on queue depth, rejections and goodput (page on the budget burning, as the SLO lesson explains, and keep the cause metrics for diagnosis).
The tail dominates at scale because fan-out turns rare slow calls into common ones, and the answer is to tolerate variability with redundancy (hedged and tied requests, probation, partial results), within a budget. Overload is different: queues grow, servers waste work on abandoned requests, retries multiply demand, and a metastable failure can persist after its trigger ends. The defenses are bounded queues, deadlines, early load shedding, a queue discipline that favors live requests, retry budgets, client-side throttling and adaptive concurrency limits, plus a recovery plan that breaks the feedback loop.
Try answering out loud before you reveal each answer.
QuestionA request needs answers from 100 servers in parallel, and each is slow 1% of the time. What share of requests is slow?Reveal answer
1 − 0.99^100, about 63%. The component's p99 becomes what most users see.
QuestionEach of four layers retries a failed call three times. How many attempts can reach the bottom layer for one user request, and what stops it?Reveal answer
Up to 3^4 = 81. Retry in only one layer, use a retry budget so retries are capped to a fraction of traffic, and propagate a deadline so work stops when the caller has given up.
QuestionIn the last two minutes a client attempted 100 requests and 20 were accepted. With K = 2, what share of new requests does adaptive client-side throttling reject?Reveal answer
max(0, (100 − 2 × 20) ÷ (100 + 1)) = 60 ÷ 101, about 59%. The client sheds its own requests until the backend starts accepting more.
- Jeffrey Dean and Luiz André Barroso, "The Tail at Scale", Communications of the ACM 56(2), 2013: the techniques, the fan-out argument and the BigTable hedging measurement.
- Beyer, Jones, Petoff and Murphy (eds.), Site Reliability Engineering, O'Reilly, 2016: Handling Overload (opens in a new tab) (client-side adaptive throttling) and Addressing Cascading Failures.
- Ben Maurer, "Fail at Scale", ACM Queue, 2015: controlled delay and adaptive LIFO applied to request queues.
- Kathleen Nichols and Van Jacobson, "Controlling Queue Delay", ACM Queue, 2012: CoDel.
- Bronson, Aghayev, Charapko and Zhu, "Metastable Failures in Distributed Systems", HotOS 2021; and Huang and co-authors, Metastable Failures in the Wild (opens in a new tab), OSDI 2022.
- Netflix Technology Blog, Performance Under Load (opens in a new tab) (2018), and the open-source concurrency-limits library it describes.
- Amazon Builders' Library, Timeouts, retries and backoff with jitter (opens in a new tab) and "Using load shedding to avoid overload".
- gRPC, Retries (opens in a new tab): the retry throttling token bucket.