Latency, throughput and queues
The vocabulary and the math behind every performance conversation: percentiles, Little's Law, why latency climbs steeply near saturation, why scaling stops being linear, and how to find the resource that caps throughput.
ConceptCore28 min readUpdated
- 1 architecture diagram
- 1 sequence flow
- 10 code samples
- 6 interviewer follow-ups
- 3 self-checks
On this page13 sectionsHLDLLDSenior depth
Read first: Load balancing, Queues and asynchronous work
- Use latency, service time, wait time, throughput, utilization and saturation precisely.
- Report percentiles from merged histograms, and explain why percentiles cannot be averaged or added.
- Apply Little's Law to size pools, check a benchmark and see how a slow dependency becomes an outage.
- Predict how latency grows with utilization, and set headroom for peaks and for failures.
- Use Amdahl's Law and the Universal Scalability Law to explain why scaling flattens, and find the resource that caps throughput.
6 code samples (168 lines), collapsed so the explanation stays in focus.
Performance engineering is making a system meet a speed and capacity target, proving it with measurements, and keeping it there while the code and the traffic change. The craft is rarely clever optimization. It is knowing which number to look at, what it should be, and which resource is the reason it is not.
This lesson is the foundation for the rest of the performance section: the vocabulary used precisely, and the handful of laws that predict how queues, servers and scaling behave. Senior performance questions lean on them because they let you predict a result before you measure it, and a prediction that fails is where the interesting finding is.
Most performance arguments are two people using the same word for different things. Fix the vocabulary first.
| Term | Meaning | Common mistake |
|---|---|---|
| Service time | Time a resource spends working on one request, without waiting | Reading it off a busy system, where the number already includes waiting |
| Wait time | Time a request spends queued for a resource | Never measuring it |
| Latency (response time) | Wait plus service time, summed over every hop, as the caller sees it | Quoting an average |
| Throughput | Completed work per second: requests, bytes, transactions | Counting arrivals instead of completions |
| Goodput | Throughput of useful work: successful, and inside the deadline | Celebrating throughput that is mostly retries and errors |
| Utilization | The fraction of time, or of capacity, a resource is busy | Looking at one resource over one long window |
| Saturation | Work waiting because the resource is full: queue length | Treating "100% busy" and "saturated" as the same thing |
| Concurrency | Requests inside the system at once | Forgetting it equals rate times latency (see Little's Law below) |
The gap between latency and service time is queueing, and queueing is where almost every performance problem lives. A resource can be fast per request and still produce terrible latency because requests are waiting for it.
Measure latency where the caller stands. A server-side timer starts after the request has already waited in the network, the load balancer and the kernel's accept queue, so it is always the optimistic view. The SLO belongs to the caller's clock (the observability lesson covers where to measure, and the SLO lesson turns the measurement into an objective and an alert).
An average hides the experience of the users you most need to protect. If 99 requests take 10 ms and one takes 1,010 ms, the mean is 20 ms and nobody saw 20 ms. Latency distributions are skewed with long right tails, so report percentiles: p50 (the median, the typical request), p95 and p99 (the slow end most users meet sooner or later), p99.9 and the maximum for the extremes. The p99 is the value that 99% of requests did not exceed.
Sample size matters. A p99 computed from 200 requests rests on the two slowest ones. To see even ten samples beyond the p99.9 you need ten thousand requests. Report the count next to the percentile.
Three mistakes look harmless and are not:
- Averaging percentiles across hosts or minutes. Ten hosts take equal traffic. Nine answer in 10 ms and one answers in 500 ms. The average of the ten p99 values is 59 ms, which looks fine. The fleet's real p99 is 500 ms, because one request in ten went to the sick host. (Mergeable quantile sketches fix this for a metrics system; see probabilistic data structures.)
- Adding percentiles along a call chain. Two hops with a p99 of 46 ms each do not give a chain p99 of 92 ms. For independent hops the chain's p99 is lower (about 66 ms in the example below), and for correlated hops, such as two services slowed by the same noisy neighbor, it can be higher. You cannot get a chain percentile from the hop percentiles. You can only get it from the samples.
- Quoting a percentile without the load. A p99 of 80 ms at 100 requests per second and at 5,000 requests per second are different facts.
Fan-out makes the tail the norm. If a user request waits for n parallel calls and each is slow 1% of the time, the chance that at least one is slow is 1 - 0.99^n: 9.6% for 10 calls and 63% for 100. At that scale a component's p99 is what most users experience.
C# · Stats, Rng
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
public static class Stats
{
/// <summary>Nearest-rank percentile of a sorted list: p = 0.99 is the value 99% of the samples do not exceed.</summary>
public static double Percentile(IReadOnlyList<double> sorted, double p)
{
int rank = (int)Math.Ceiling(p * sorted.Count);
return sorted[Math.Clamp(rank, 1, sorted.Count) - 1];
}
/// <summary>The chance that at least one of n independent calls lands in the slow fraction p.</summary>
public static double AnySlow(double p, int n) => 1 - Math.Pow(1 - p, n);
}
/// <summary>A seeded random source (xorshift64*), so every run sees the same traffic and the tests are repeatable.</summary>
public sealed class Rng
{
private ulong _s;
public Rng(ulong seed) { _s = seed == 0 ? 0x9E3779B97F4A7C15UL : seed; }
public double NextDouble()
{
_s ^= _s >> 12; _s ^= _s << 25; _s ^= _s >> 27;
ulong x = _s * 2685821657736338717UL;
return (x >> 11) * (1.0 / 9007199254740992.0); // 53 random bits, in [0, 1)
}
/// <summary>An exponential sample with the given mean: the gaps between random arrivals, or a service time.</summary>
public double Exponential(double mean) => -mean * Math.Log(1.0 - NextDouble());
}Now use them. The first check is the sick host; the second is the two-hop chain:
C# · Ten hosts, equal traffic. Nine answer in 10 ms, one in 500 ms.
// Ten hosts, equal traffic. Nine answer in 10 ms, one in 500 ms.
var perHost = new List<double>();
var fleet = new List<double>();
for (int host = 0; host < 10; host++)
{
double latency = host == 9 ? 500 : 10;
var samples = Enumerable.Repeat(latency, 1000).ToList(); // every value is equal, so already sorted
perHost.Add(Stats.Percentile(samples, 0.99));
fleet.AddRange(samples);
}
fleet.Sort();
Debug.Assert(Math.Abs(perHost.Average() - 59) < 1e-9); // the average of the ten p99s looks healthy
Debug.Assert(Stats.Percentile(fleet, 0.99) == 500); // the fleet's p99 is the sick host
// Two independent hops, 10 ms on average each.
var traffic = new Rng(11);
var oneHop = new List<double>();
var twoHops = new List<double>();
for (int i = 0; i < 200_000; i++)
{
double first = traffic.Exponential(10), second = traffic.Exponential(10);
oneHop.Add(first);
twoHops.Add(first + second);
}
oneHop.Sort();
twoHops.Sort();
double p99Hop = Stats.Percentile(oneHop, 0.99); // about 46 ms
double p99Chain = Stats.Percentile(twoHops, 0.99); // about 66 ms, not 92
Debug.Assert(p99Chain < 0.8 * (2 * p99Hop)); // adding the p99s overstates the chain by more than a quarter
Debug.Assert(Math.Abs(Stats.AnySlow(0.01, 100) - 0.634) < 0.001);The practical consequence is about what you store. Keep histograms (counts per latency bucket), not percentiles. Histograms from many hosts and minutes merge by adding their counts, and you read any percentile off the merged result. Percentiles cannot be merged at all. The observability lesson shows what histograms cost in series, and how to place their buckets.
In a stable system, the average number of requests inside equals their arrival rate times the average time each spends inside.
L = λ × W
L: average number in the system
λ: arrival rate (the throughput, when the system is stable)
W: average time in the systemIt holds for any arrival pattern, any service-time distribution and any queue discipline, and for any boundary you draw: the whole service, only the queue, or only the database call. It is a statement about long-run averages of a system that is not growing without bound, so it uses means, not percentiles.
| You know | You get | Example |
|---|---|---|
| Throughput and latency | Requests in flight | 2,000 requests/s × 0.05 s = 100 in flight |
| In flight and latency | The throughput that setup can sustain | 200 connections, each query 0.5 s: at most 400 queries/s |
| In flight and throughput | The latency the system must have | 64 workers finishing 800 jobs/s: 80 ms each |
It earns its keep in three places.
Sizing pools and limits. A service doing 2,000 requests/s with 50 ms mean latency has 100 requests in flight. A pool smaller than that queues requests even though the machine is idle. A pool much larger is just a bigger place for work to wait. For CPU-bound work, Little's Law tells you the concurrency that exists, not the concurrency you should allow: threads beyond the core count add context switching, not speed.
Seeing how a slow dependency becomes an outage. The same service calls a database for 20 ms per request, so 2,000 × 0.02 = 40 queries are in flight, and a pool of 100 connections is 40% used. The database slows to 200 ms. Now 400 queries are in flight, the pool caps at 100, and throughput is limited to 100 ÷ 0.2 = 500 requests/s. The other 1,500 per second queue, threads block on the pool, latency becomes a timeout, clients retry, and the queue grows. Nothing "crashed". The arithmetic ran out.
Checking a benchmark. If a load generator reports 64 connections, 20,000 requests/s and a 1 ms mean, the numbers cannot all be true: 20,000 × 0.001 = 20 requests in flight, not 64. Either the generator sat idle part of the time, or it is not counting the time requests spent waiting to be sent, a distortion called coordinated omission that hides the tail. Applying L = λW to someone else's results is one of the quickest ways to find out whether to trust them.
Little's Law in C#
The law is exact for long runs, so a simulation can check it. This one models a single first-in-first-out server with random arrivals. It computes each request's time in the system, then counts how many requests are inside by looking at the system at regular instants, which is a separate measurement from the arithmetic.
C# · QueueRun, Sim
public sealed record QueueRun(double[] Arrival, double[] Sojourn, double[] Wait);
public static class Sim
{
/// <summary>One FIFO server. Arrivals are random at `arrivalRate` per time unit; `service` draws each job's service time.</summary>
public static QueueRun SingleServer(int n, double arrivalRate, Func<Rng, double> service, ulong seed)
{
var g = new Rng(seed);
var arrival = new double[n];
var sojourn = new double[n]; // time in the system: wait plus service
var wait = new double[n];
double clock = 0, serverFreeAt = 0;
for (int i = 0; i < n; i++)
{
clock += g.Exponential(1 / arrivalRate);
double start = Math.Max(clock, serverFreeAt); // wait if the server is busy
serverFreeAt = start + service(g);
arrival[i] = clock;
wait[i] = start - clock;
sojourn[i] = serverFreeAt - clock;
}
return new QueueRun(arrival, sojourn, wait);
}
/// <summary>Average number of requests in the system, counted by looking every `step` time units.</summary>
public static double AverageInSystem(QueueRun r, double from, double to, double step)
{
int n = r.Arrival.Length, arrived = 0, left = 0, looks = 0;
double total = 0;
for (double t = from; t < to; t += step)
{
while (arrived < n && r.Arrival[arrived] <= t) arrived++;
while (left < n && r.Arrival[left] + r.Sojourn[left] <= t) left++;
total += arrived - left;
looks++;
}
return total / looks;
}
}var littleRun = Sim.SingleServer(200_000, 0.8, g => g.Exponential(1.0), seed: 42);
double span = littleRun.Arrival[^1];
double lambda = littleRun.Arrival.Length / span; // arrivals per time unit
double meanTime = littleRun.Sojourn.Average(); // W: mean time in the system
double counted = Sim.AverageInSystem(littleRun, 0, span, 0.5); // L: counted by looking, not by arithmetic
Debug.Assert(Math.Abs(counted - lambda * meanTime) / counted < 0.02);Take the simplest realistic model: one server, requests arriving at random, service times exponential with mean S. This is the M/M/1 queue. At utilization ρ (the arrival rate times S), the mean response time is S ÷ (1 − ρ). The response time is itself exponentially distributed, so the p99 is about 4.6 times the mean.
| Utilization | Mean response, in service times | p99, in service times |
|---|---|---|
| 50% | 2.0 | 9.2 |
| 70% | 3.3 | 15.4 |
| 80% | 5.0 | 23.0 |
| 90% | 10 | 46 |
| 95% | 20 | 92 |
| 99% | 100 | 461 |
utilization mean response
10% ## 1.1
50% #### 2
70% ####### 3.3
80% ########## 5
90% #################### 10
95% ######################################## 20The curve is flat, then bends, then goes vertical. That shape explains several things that surprise people:
- A small increase in load can double latency. From 90% to 95% utilization the load rises by 5.6% and the mean response time doubles. This is why a system that was fine at 3:00 pm falls over at 3:05.
- "CPU at 70%" is already uncomfortable for a latency-sensitive service: the average request waits more than twice its service time, and the tail is several times that.
- Averages over long windows hide the problem. A one-minute CPU average of 60% can contain seconds at 100%, and those seconds are where the queue builds.
- Autoscaling must react before the bend. A scaler that acts at 90% utilization is acting inside the vertical part of the curve, plus the minutes it takes new capacity to start.
Variability is the other half
Utilization is not the only input. Kingman's approximation for the mean wait in a queue is:
wait ≈ ρ ÷ (1 − ρ) × (ca² + cs²) ÷ 2 × S
ca: variability of the gaps between arrivals
cs: variability of service times
(0 = constant, 1 = exponential)With random arrivals and exponential service both variabilities are 1 and the factor disappears, which is the M/M/1 case. Make service times constant and the factor halves, so the same load waits half as long. Make traffic bursty or service times heavy-tailed (a few huge requests, a garbage collection pause, a cache miss storm) and the factor grows. Two services at the same utilization and the same average service time can have very different latencies.
This is why reducing variance is as valuable as reducing the mean: cap request sizes, put slow request classes in their own pool, avoid stop-the-world pauses, smooth bursts with a queue or a rate limit, and make retries wait with jitter. It is also why the utilization you can run at depends on the shape of your traffic, not just its volume.
public static class Queueing
{
/// <summary>Mean time in an M/M/1 system (waiting plus service) at utilization rho.</summary>
public static double MeanResponse(double rho, double service) => service / (1 - rho);
/// <summary>The p-quantile of M/M/1 response time, which is exponential with mean service / (1 - rho).</summary>
public static double ResponsePercentile(double rho, double service, double p) => -Math.Log(1 - p) * service / (1 - rho);
/// <summary>The highest utilization at which the mean response stays within `slowdown` service times.</summary>
public static double MaxUtilization(double slowdown) => 1 - 1 / slowdown;
}C#
foreach (double rho in new[] { 0.5, 0.8 })
{
var run = Sim.SingleServer(400_000, rho, g => g.Exponential(1.0), seed: 42);
double mean = run.Sojourn.Average();
Debug.Assert(Math.Abs(mean - Queueing.MeanResponse(rho, 1.0)) / mean < 0.05);
var times = run.Sojourn.OrderBy(t => t).ToList();
double p99 = Stats.Percentile(times, 0.99);
Debug.Assert(Math.Abs(p99 - Queueing.ResponsePercentile(rho, 1.0, 0.99)) / p99 < 0.05);
}
// The same load with constant service times waits half as long: variability costs latency.
double randomWait = Sim.SingleServer(400_000, 0.8, g => g.Exponential(1.0), seed: 7).Wait.Average();
double constantWait = Sim.SingleServer(400_000, 0.8, g => 1.0, seed: 7).Wait.Average();
Debug.Assert(Math.Abs(constantWait / randomWait - 0.5) < 0.03);
Debug.Assert(Math.Abs(Queueing.MaxUtilization(3) - 2.0 / 3) < 1e-9); // at most 3 service times on average: run at 67% or lessHeadroom is not waste
Pick utilization by working backwards from the latency you can afford. If the mean may be at most 3 service times, MaxUtilization(3) says 67%. For a p99 target of k service times in this model, utilization must stay below 1 - 4.6 / k.
Headroom also has to cover failure. With N equal nodes (or zones), losing one raises the load on each survivor by N / (N - 1). If survivors may run at 75% after a failure, the normal peak must stay at or below 75% × (N − 1) ÷ N: 50% with three zones, 56% with four, 62% with six. The same reasoning covers a deployment that takes a node out of rotation. A service that runs at 85% "to save money" has no capacity to survive the day anything goes wrong.
A request crosses several hops, and each owes a share of the end-to-end target. Sequential hops add up. Parallel hops cost as much as the slowest one, so fan-out turns the tail of each branch into the typical case (see the fan-out numbers above). Retries add the timeout that preceded them. And every hop adds queueing on top of its service time.
Allocate the budget top-down from the user-facing target, then verify it bottom-up by measuring each hop's actual percentile at realistic load. Spend attention where the critical path is longest: by Amdahl's reasoning, making a hop that is 5% of the path twice as fast buys 2.5%, while the hop that is 50% of the path is worth twenty times that effort. Write budgets as percentiles at a stated load, and make timeouts shorter than the budget they protect.
It also pays to know the orders of magnitude, so a design fails on arithmetic before it fails in a test. These are rules of thumb that vary by hardware, not specifications:
| Operation | Roughly |
|---|---|
| Read from CPU cache | 1 to 10 ns |
| Read from main memory | 100 ns |
| Random read from a fast SSD | 50 to 100 µs |
| Round trip inside one datacenter | 0.5 ms |
| Spinning-disk seek | 5 to 10 ms |
| Round trip between continents | 100 to 150 ms |
A design that needs fifty sequential cross-region calls cannot meet a 100 ms target, whatever the code looks like. That is arithmetic, not tuning.
Amdahl's Law says that if a fraction s of the work is serial, the speedup on N workers is at most 1 / (s + (1 - s) / N), and never more than 1 / s. With 5% serial work the ceiling is 20×, however many cores you add.
Real systems do worse than Amdahl predicts, because workers also pay to coordinate. Neil Gunther's Universal Scalability Law adds a second term:
C(N) = N ÷ (1 + α(N − 1) + βN(N − 1))
α: contention, the serial share (a lock, a single-threaded component)
β: coherency, the cost of keeping copies agreeing (cache lines,
shared counters, all-to-all coordination)With β = 0 this is Amdahl. With β > 0 throughput peaks at N* = √((1 − α) ÷ β) and then falls: past the peak, more workers make the system slower. That is retrograde scaling, and it is real: a shared counter updated by every core, a lock everyone queues on, and a consensus group that grows all behave like this.
With α = 0.05 and β = 0.001, the speedup over one worker is:
| Workers | 1 | 2 | 4 | 8 | 16 | 32 | 64 |
|---|---|---|---|---|---|---|---|
| Speedup | 1.00 | 1.90 | 3.44 | 5.69 | 8.04 | 9.03 | 7.82 |
Eight workers buy 5.7× (71% efficiency). Thirty-two buy 9× (28%). Sixty-four are slower than thirty-two. The curve peaks near 31.
How to use it: measure throughput at 1, 2, 4, 8, 16 workers (cores, threads or nodes), fit α and β by regression, and read the result. A large α says to shrink or shard the serial section. A large β says to stop sharing writes: partition the data, batch updates, use per-core counters. The model does not prove a cause; it tells you which kind of cause to hunt with a profiler. Do not extrapolate far beyond the measured range, and keep the load generator out of the picture, because a saturated generator produces a perfect-looking flat line.
The fit is a straight line in disguise. Rearranging gives (N / C − 1) / (N − 1) = α + βN, so a least-squares line through those points has intercept α and slope β.
C# · Usl
public sealed class Usl
{
public double Alpha { get; } // contention
public double Beta { get; } // coherency
public Usl(double alpha, double beta) { Alpha = alpha; Beta = beta; }
/// <summary>Throughput at n workers relative to one worker.</summary>
public double Speedup(double n) => n / (1 + Alpha * (n - 1) + Beta * n * (n - 1));
/// <summary>The worker count where throughput peaks (infinite when there is no coherency cost).</summary>
public double PeakAt() => Beta > 0 ? Math.Sqrt((1 - Alpha) / Beta) : double.PositiveInfinity;
/// <summary>Fit alpha and beta from measured (workers, speedup) points by least squares on the straight-line form.</summary>
public static Usl Fit(IReadOnlyList<(double Workers, double Speedup)> points)
{
var x = new List<double>();
var y = new List<double>();
foreach (var (n, c) in points)
{
if (n <= 1) continue; // N = 1 carries no information: the ratio is 0 / 0
x.Add(n);
y.Add((n / c - 1) / (n - 1));
}
double mx = x.Average(), my = y.Average(), sxy = 0, sxx = 0;
for (int i = 0; i < x.Count; i++)
{
sxy += (x[i] - mx) * (y[i] - my);
sxx += (x[i] - mx) * (x[i] - mx);
}
double beta = sxy / sxx;
return new Usl(my - beta * mx, beta);
}
}var model = new Usl(alpha: 0.05, beta: 0.001);
Debug.Assert(Math.Abs(model.Speedup(1) - 1) < 1e-12);
Debug.Assert(model.Speedup(8) > 5.6 && model.Speedup(8) < 5.8); // eight workers buy 5.7x, not 8x
Debug.Assert(model.Speedup(64) < model.Speedup(32)); // past the peak, more workers are slower
Debug.Assert(Math.Abs(model.PeakAt() - 30.8) < 0.1);
Debug.Assert(new Usl(0.05, 0).Speedup(1e9) > 19.99); // with no coherency cost, Amdahl's ceiling is 1 / 0.05
// Pretend these were measured at 1, 2, 4 ... 64 workers: the fit recovers both coefficients.
var measured = new[] { 1, 2, 4, 8, 16, 32, 64 }.Select(n => ((double)n, model.Speedup(n))).ToList();
var fitted = Usl.Fit(measured);
Debug.Assert(Math.Abs(fitted.Alpha - 0.05) < 1e-9 && Math.Abs(fitted.Beta - 0.001) < 1e-9);Every resource has a utilization law: U = X × D ÷ m, where X is the system's throughput, D the time one request demands from that resource, and m how many units of it work in parallel (cores, connections, disks). A resource is full at X = m ÷ D. The system can never exceed the lowest of those ceilings, and the resource with the lowest ceiling is the bottleneck.
The useful consequence is that the bottleneck is not always the resource you were watching. Take a request that needs 2 ms of CPU on an 8-core machine, holds a database connection for 5 ms from a pool of 20, and passes through a 0.45 ms section guarded by one global lock:
| Resource | Demand per request | Parallel units | Ceiling |
|---|---|---|---|
| CPU | 2 ms | 8 | 4,000 requests/s |
| Database connections | 5 ms | 20 | 4,000 requests/s |
| Global lock | 0.45 ms | 1 | 2,222 requests/s |
The lock caps the system at 2,222 requests/s. At that rate the CPU is only 56% busy and the pool 56% used, so a dashboard that shows CPU and nothing else says "plenty of headroom" while the lock's queue grows and latency follows the hockey stick. Fix the lock (shrink the critical section, shard it) and the ceiling moves to 4,000, where two resources are tied and the next fix has to address both. That sequence is predictable, which is the point: you can say before the change what it buys and where the next wall is.
C# · Resource, Capacity
public sealed record Resource(string Name, double DemandMs, int Units);
public static class Capacity
{
/// <summary>Requests per second at which this resource is 100% busy.</summary>
public static double Ceiling(Resource r) => r.Units * 1000.0 / r.DemandMs;
/// <summary>The resource that fills first as load rises.</summary>
public static Resource Bottleneck(IEnumerable<Resource> resources) => resources.OrderBy(Ceiling).First();
public static double Utilization(Resource r, double perSecond) => perSecond / Ceiling(r);
/// <summary>The normal-day peak utilization that leaves survivors at `targetAfterFailure` when one of `zones` is lost.</summary>
public static double NormalCeiling(double targetAfterFailure, int zones) => targetAfterFailure * (zones - 1) / zones;
}var request = new[]
{
new Resource("CPU (8 cores)", DemandMs: 2.0, Units: 8),
new Resource("Database connections", DemandMs: 5.0, Units: 20),
new Resource("Global lock", DemandMs: 0.45, Units: 1),
};
var limit = Capacity.Bottleneck(request);
double ceiling = Capacity.Ceiling(limit);
Debug.Assert(limit.Name == "Global lock" && Math.Abs(ceiling - 2222.2) < 0.1);
Debug.Assert(Math.Abs(Capacity.Utilization(request[0], ceiling) - 0.5556) < 0.001); // the CPU is barely past half
Debug.Assert(Math.Abs(Capacity.NormalCeiling(0.75, 3) - 0.5) < 1e-9); // three zones: run at 50% on a normal dayThe same loop applies to a latency complaint, a capacity plan and a regression:
- Write the goal as a testable statement. A percentile, a threshold, a load and a window: "p99 under 300 ms at 2,000 requests/s, measured at the client".
- Measure a baseline under a realistic workload, and record the conditions so you can reproduce them.
- Find the limiting resource. Check utilization, saturation and errors for every resource (CPU, memory, disk, network, locks, pools), then use a profiler to see where the time goes inside it.
- Predict before you change. Write down what the fix should buy: "the lock ceiling moves from 2,200 to 4,000 requests/s". If the measurement disagrees by more than a modest margin, your model is wrong, which is the most useful thing you could learn.
- Change one thing.
- Re-measure with the same method, and compare runs with proper statistics instead of a glance.
- Lock it in with a regression test, an alert or a budget, so the gain survives the next quarter.
- Stop when the goal is met. Work past the target is a cost.
The rest of this section turns each step into practice: how to build a load test that does not lie, how to find the bottleneck with a profiler, and how systems behave when demand exceeds capacity.
Interviewer follow-upL5Can you improve latency and throughput together, or do you always trade one for the other?How to answer
Sometimes you trade, sometimes you do not. Batching and pipelining raise throughput by amortizing fixed costs but add the time a request waits for its batch, so they trade latency for throughput. Removing work (a cache hit, a cheaper serialization, a removed round trip) improves both, and adding capacity improves both until a shared bottleneck appears. Say which one the SLO protects first: an interactive API protects tail latency, a batch pipeline protects throughput per dollar.
Interviewer follow-upL6A service handles 5,000 requests/s at 80 ms mean latency. How many requests are in flight, and what happens to its 100-connection database pool if each request makes one 20 ms query and the database becomes four times slower?How to answer
The service has 5,000 × 0.08 = 400 requests in flight. The pool carries 5,000 × 0.02 = 100 queries in flight, so it is already 100% used: no headroom at all. At 80 ms per query it would need 400 connections, but it has 100, so it can finish only 100 ÷ 0.08 = 1,250 requests/s. The remaining 3,750 per second queue, threads block on the pool, latency turns into timeouts and retries amplify the load. The fix is structural: a pool sized with headroom from Little's Law, timeouts shorter than the caller's budget, load shedding at the front, a circuit breaker on the dependency and bulkheads so one slow dependency cannot take every thread.
Interviewer follow-upL6CPU is at 55% but p99 keeps climbing as load grows. Where do you look?How to answer
At every other resource, because a different one is saturated. Candidates are a lock or a single-threaded component (one core pinned while the average looks low), a connection or thread pool at its limit, disk or network queues, a downstream dependency, garbage collection pauses, and in containers CPU throttling by a quota. Use the USE method for each resource (utilization, saturation, errors), look at per-core and per-thread numbers rather than the machine average, and look at short windows, since a one-minute average hides one-second bursts. Then compute each resource's ceiling from its demand per request: the lowest one is the bottleneck.
Interviewer follow-upL7Throughput stops scaling at 8 cores. How do you diagnose it?How to answer
First rule out the test: a saturated load generator, a client-side limit or a shared dependency produces the same flat line. Then measure throughput at 1, 2, 4, 8 and 16 workers and fit the Universal Scalability Law. A large contention term α points to a serial section: find it with off-CPU profiling and lock-contention counters, then shrink it, shard it or take it off the hot path. A large coherency term β, or throughput that falls after the peak, points to shared writes: false sharing and cache line bouncing, a shared counter, an all-to-all protocol. Confirm with hardware counters and a cache-contention profile, then partition the data or keep per-core state and merge it later. Also check memory bandwidth and NUMA placement, since remote memory access scales badly.
Interviewer follow-upL7How much headroom does a service need if it runs in three zones and must survive losing one?How to answer
Losing one of three zones raises the load on each survivor by 3/2. If survivors must stay at or below about 75% to keep latency acceptable, the normal-day peak must be at most 75% × 2/3 = 50%. With six zones the same rule gives 62%. Add the effect of deploys (a node out of rotation), the growth between capacity reviews, and the time autoscaling takes to react. A cheaper alternative to idle capacity is graceful degradation: shed low-priority work first so the survivors serve what matters.
Interviewer follow-upL7How do you compute a fleet-wide p99 cheaply, and what goes wrong with the obvious approaches?How to answer
Do not average per-host percentiles and do not sample a few hosts. Have every host record a histogram, with buckets sized for a bounded relative error, or a mergeable sketch such as HdrHistogram or DDSketch. Ship the bucket counts. Merging is addition, so any window, host group or service rolls up exactly, and you read the percentile from the merged histogram. The error is bounded by the bucket width, which you chose up front. Raw samples are accurate but too costly at scale, and a mean of percentiles is simply wrong.
When a prompt mentions speed, scale or "it is slow", walk through these in order:
- Pin down the goal. Which operation, which percentile, what load, measured where, for whom.
- Model before you measure. State the arrival rate, the service time, the concurrency from Little's Law, the likely bottleneck and its ceiling.
- Name the resources and say what you would watch for each: utilization, saturation, errors.
- Say how you would find the time: a profile, a trace, a breakdown of the critical path.
- Propose changes with predicted effects, and the trade-off each one costs.
- Cover overload and failure: what happens at 2× load and when a dependency slows down.
- Say how you would prove it and keep it: a load test, a baseline, a regression check, an alert.
Latency is service time plus waiting, and waiting grows without bound as utilization approaches 100%. Report percentiles from merged histograms, never averages of percentiles. Little's Law ties concurrency, throughput and latency together and checks other people's numbers. Headroom is sized from the latency you can afford and the failures you must survive. Scaling flattens because of contention and coherency, and the resource with the lowest ceiling is the bottleneck, which is often not the one on the dashboard.
Try answering out loud before you reveal each answer.
QuestionA service completes 400 requests per second and each takes 250 ms on average. How many requests are inside it at any moment?Reveal answer
100, from L = λ × W = 400 × 0.25. If a pool or thread limit is below that, requests queue.
QuestionA queue runs at 90% utilization with a 10 ms mean response (the M/M/1 model). What is the service time, and what happens to latency at 95%?Reveal answer
Mean response is S ÷ (1 − ρ), so S = 10 ms × 0.1 = 1 ms. At 95% it is 1 ÷ 0.05 = 20 ms. A 5.6% rise in load doubled the latency.
QuestionTen hosts report their own p99. Why can you not average them to get the fleet's p99?Reveal answer
Percentiles do not combine. If nine hosts have a p99 of 10 ms and one has 500 ms, the average is 59 ms, but a tenth of all requests hit the slow host, so the fleet's p99 is 500 ms. Keep histograms, add their bucket counts, and read the percentile from the merged result.
- J. D. C. Little, "A Proof for the Queuing Formula: L = λW", Operations Research 9(3), 1961.
- Neil J. Gunther, Guerrilla Capacity Planning, Springer, 2007: the Universal Scalability Law.
- Lazowska, Zahorjan, Graham and Sevcik, Quantitative System Performance, Prentice-Hall, 1984: the operational laws behind the bottleneck calculation.
- Brendan Gregg, The USE Method (opens in a new tab), and Systems Performance, 2nd edition, Addison-Wesley, 2020.
- Beyer, Jones, Petoff and Murphy (eds.), Site Reliability Engineering, O'Reilly, 2016, chapter Monitoring Distributed Systems (opens in a new tab): the four golden signals.