"Is it fast?" is not a measurable question. Performance is described by latency (how long one request takes), throughput (how many requests complete per second) and the distribution of latency, summarized by percentiles like p50 and p99. This lesson shows why averages lie, why the slowest 1% dominates large systems, how Little's Law links concurrency to throughput, why latency explodes as utilization approaches 100%, and which techniques actually make systems faster.
Think of it like
A highway
Bandwidth is how many lanes the highway has. Throughput is how many cars actually pass a point per hour. Latency is how long one car takes to get from A to B. Adding lanes does not make an empty road faster, and as traffic approaches the road's capacity, small disturbances cause jams: travel times explode long before the road is "100% full". The percentiles are the difference between the typical commute and the day you sat in a jam for two hours.
Latency, throughput and bandwidth
- Latency
- Time from sending a request to receiving the response, as seen by the caller. Includes network time, queueing and processing. Sometimes split into service time (actually working) and wait time (queued).
- Throughput
- Completed operations per unit of time: requests per second (RPS/QPS), messages per second, MB/s.
- Bandwidth
- The maximum data rate a link or device can carry, such as 10 Gbps. Throughput is what you achieve; bandwidth is the ceiling.
- Utilization
- The fraction of time a resource is busy. The key variable connecting throughput to latency.
Optimizing latency
- Do less work per request; avoid waiting
- Cache, precompute, move data closer (CDN, regions)
- Parallelize independent calls
- Keep utilization moderate so queues stay short
Optimizing throughput
- Do more work per unit of overhead
- Batch writes, pipeline requests, compress
- Add workers and partitions
- Run resources hotter, accepting longer queues
Percentiles, and why averages lie
Latency is a distribution, usually with a long right tail: most requests are fast, a few are very slow (garbage-collection pauses, cache misses, retries, a slow disk). The p99 is the value that 99% of requests are faster than. The median (p50) describes the typical experience; p99 and p99.9 describe the worst experiences that still happen thousands of times a day.
| Requests (out of 1,000) | Latency |
|---|---|
| 900 | 20 ms |
| 90 | 100 ms |
| 9 | 500 ms |
| 1 | 3,000 ms |
Mean
34.5 ms
Matches no actual request
p50
20 ms
Typical experience
p99
100 ms
1 in 100 is slower
p99.9
500 ms
1 in 1,000 is slower
- The mean hides the tail: 34.5 ms looks healthy, yet 10 requests per thousand take 500 ms or more.
- The mean is pulled by outliers: one 30-second timeout can double the average of an otherwise fast service.
- The tail is not rare at scale: at 10,000 requests per second, p99.9 is ten users per second.
- Slow requests often belong to your best users: the customers with the most data, the biggest carts, the most followers.
- One page is many requests: a page that makes 30 backend calls exposes most users to the p99 of at least one of them.
Tail latency amplification under fan-out
Large services answer one user request by fanning out to many backends in parallel: a search query hits hundreds of index shards, a feed request gathers posts from dozens of services. The user waits for the slowest one. If each backend is slow with probability p, the chance that at least one of N is slow grows fast.
| Fan-out N | P(request hits at least one backend p99) |
|---|---|
| 1 | 1% |
| 10 | 9.6% |
| 50 | 39.5% |
| 100 | 63.4% |
| 1,000 | 99.996% |
Little's Law
- 1
Size a pool
A service handles 2,000 req/s with 50 ms average latency: L = 2,000 × 0.05 = 100 requests in flight. A thread or connection pool smaller than 100 becomes the bottleneck.
- 2
Predict throughput
A database allows 50 connections and each query holds one for 5 ms: maximum λ = L ÷ W = 50 ÷ 0.005 = 10,000 queries/s. Slow queries cut this directly.
- 3
Estimate queue wait
A queue holds 30,000 messages and consumers drain 500/s: W = L ÷ λ = 60 s for a new message to get through.
Utilization vs queueing delay
Requests do not arrive evenly; they bunch up randomly. When a server is busy, newcomers wait in a queue. Queueing theory's simplest model (M/M/1: random arrivals, random service times, one server) gives a startling result: waiting time grows with 1 ÷ (1 − utilization).
| Utilization ρ | Average latency (multiples of service time) | With S = 10 ms |
|---|---|---|
| 50% | 2× | 20 ms |
| 75% | 4× | 40 ms |
| 90% | 10× | 100 ms |
| 95% | 20× | 200 ms |
| 99% | 100× | 1,000 ms |
Measuring latency correctly
- Record histograms, not averages. Store counts in latency buckets; compute percentiles at query time. Tools: HdrHistogram, Prometheus histograms, OpenTelemetry. See Observability.
- Never average percentiles. The mean of ten servers' p99s is not the fleet's p99. Histograms can be merged (add the bucket counts) and then queried.
- Choose bucket boundaries around your SLO (for example 50, 100, 200, 300, 500 ms) so the important percentiles are precise.
- Measure where the user is. Server-side timing misses network, queueing in load balancers and client rendering. Combine server metrics with client-side real-user monitoring.
- Beware coordinated omission. A load tester that waits for each response before sending the next silently stops sending during a stall, hiding exactly the slow periods you care about. Use open-loop load generators with a fixed arrival rate.
- Separate success from errors. Fast failures can make latency look great while users see errors.
histogram_quantile(
0.99,
sum by (le) (rate(http_request_duration_seconds_bucket{service="search"}[5m]))
)Techniques that make systems faster
| Technique | Improves | How | Watch out for |
|---|---|---|---|
| Caching | Latency and throughput | Serve repeated reads from memory or the edge (Caching, Content Delivery Networks) | Staleness, invalidation, cold starts |
| Batching | Throughput | Amortize per-request overhead: bulk inserts, grouped disk flushes, pipelined commands | Adds wait time to individual items |
| Parallelism | Latency | Issue independent calls concurrently instead of sequentially | Fan-out amplifies tail latency |
| Hedged requests | Tail latency | After a delay near the p95, send a duplicate to another replica; take the first answer | Extra load; only for idempotent reads |
| Connection reuse | Latency | Keep-alive and pools skip TCP/TLS handshakes (HTTP, HTTPS & TLS) | Pool sizing (use Little's Law) |
| Async processing | User-facing latency | Respond now, do slow work on a queue (Message Queues & Pub/Sub) | Eventual consistency, failure handling |
| Precomputation | Read latency | Materialize views, timelines, aggregates ahead of time | Write amplification, freshness |
| Timeouts and budgets | Tail latency, stability | Bound every call; pass a deadline down the chain | Too tight causes needless failures |
| Load shedding | Latency under overload | Reject excess early (429/503) to keep accepted requests fast | Must prioritize important traffic |
Implementation
Exact nearest-rank percentiles need every sample; fixed-bucket histograms use constant memory and can be merged across servers, at the cost of bucket-width precision.
import math
import random
from bisect import bisect_left
def percentile(samples: list[float], p: float) -> float:
"""Nearest-rank: the smallest value with at least p% of samples at or below it."""
ordered = sorted(samples)
rank = max(1, math.ceil(p / 100 * len(ordered) - 1e-9)) # epsilon guards float error
return ordered[rank - 1]
class LatencyHistogram:
def __init__(self, bounds_ms: list[float]) -> None:
self.bounds = bounds_ms # ascending upper bounds
self.counts = [0] * (len(bounds_ms) + 1) # final bucket = overflow
def record(self, ms: float) -> None:
self.counts[bisect_left(self.bounds, ms)] += 1
def merge(self, other: "LatencyHistogram") -> None:
# Merging histograms is exact; averaging per-server percentiles is not.
self.counts = [a + b for a, b in zip(self.counts, other.counts)]
def quantile(self, p: float) -> float:
"""Upper bound of the bucket holding the p-th percentile (a conservative estimate)."""
target = max(1, math.ceil(p / 100 * sum(self.counts) - 1e-9))
seen = 0
for i, count in enumerate(self.counts):
seen += count
if seen >= target:
return self.bounds[i] if i < len(self.bounds) else math.inf
return math.inf
random.seed(7)
# Mostly fast requests plus a small population of slow ones: a long tail
samples = [random.lognormvariate(3, 0.4) for _ in range(9_900)]
samples += [random.uniform(300, 2_000) for _ in range(100)]
hist = LatencyHistogram([10, 20, 30, 50, 100, 200, 300, 500, 1_000, 2_000])
for s in samples:
hist.record(s)
print(f"mean {sum(samples) / len(samples):7.1f} ms")
for p in (50, 95, 99, 99.9):
print(f"p{p:<5} exact {percentile(samples, p):7.1f} ms histogram <= {hist.quantile(p):g} ms")Key takeaways
- Latency is time per request, throughput is requests per second, bandwidth is the ceiling; optimizing one often costs the other.
- Describe latency with percentiles (p50, p99, p99.9) over a stated window; the mean hides the tail.
- Fan-out amplifies tails: 1 − (1 − p)^N means 100 backends with 1% slowness make 63% of requests slow.
- Little's Law (L = λ × W) sizes pools and shows that slower dependencies directly cut throughput.
- Queueing delay grows like 1 ÷ (1 − utilization): keep latency-sensitive resources well below 100% busy.
- Measure with mergeable histograms and open-loop load tests; improve with caching, batching, parallelism, hedging and load shedding.
Common pitfalls
- Reporting average latency, or averaging per-server percentiles into a fleet number.
- Load testing with closed-loop clients (coordinated omission), which hides stalls.
- Sizing for 90%+ utilization and being surprised when latency multiplies under modest bursts.
- Fanning out to many backends without timeouts, partial results or hedging.
- Hedging or retrying non-idempotent requests, or hedging immediately and doubling load.
Interview tips
- State latency requirements as percentiles with numbers ("p99 under 200 ms for the feed").
- Use Little's Law to justify pool sizes or the number of workers a queue needs.
- When your design fans out, bring up tail amplification and its mitigations before the interviewer does.
Real-world applications
- Defining SLOs and dashboards for production services.
- Capacity planning: how many servers keep p99 within target at peak.
- Search, feed and recommendation backends that scatter-gather across shards.
- Load testing and performance regression detection in CI.
Test yourself
A request fans out to 100 backends in parallel; each exceeds its p99 latency 1% of the time, independently. Roughly what fraction of requests are slowed by at least one backend?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.