Latency Budgets, Geography & Tail Latency (p99)
"Even rare performance hiccups affect a significant fraction of all requests in large-scale distributed systems." — Jeffrey Dean and Luiz André Barroso, The Tail at Scale, Communications of the ACM, February 2013 (key insights box)
Summary: Latency is a budget the user gives you once; distance, handshakes, queues and every hop spend it, and at scale the slowest 1% of calls (the tail) decides how fast the whole system feels. Focus: Speed of light in fibre and RTT per region, TCP/TLS handshake round trips, per-hop budgets and deadline propagation, percentiles (p50/p90/p99/p999) and why averages lie, fan-out amplification, queueing (Little's law, M/M/1, the utilisation knee), GC pauses, warm-up and cold starts, head-of-line blocking, the tail-tolerant techniques of Dean and Barroso (hedged, tied and backup requests, micro-partitions, selective replication, latency-induced probation, good-enough results, canary requests), coordinated omission, HdrHistogram, Prometheus and OpenTelemetry histograms, latency SLOs and multi-region geography (edge, anycast, read-local/write-global), with Go and Laravel code and a simulation lab. Learning goal: Given a page or an API, write its latency budget hop by hop with real numbers, say which percentile each hop must meet given its fan-out, pick the tail-tolerant technique that fits, measure it without coordinated omission, and place the pieces on the map so that physics fits inside the budget.
This chapter belongs to the Method group: it is the numeric companion of The 4-Step Approach. It owns the numbers and the design decisions. Mechanics live with the owners: the cost ladder and estimation method in Capacity Estimation; SLO, SLI and error-budget mechanics in SLAs, SLOs, SLIs & Error Budgets; deadline headers, retries and hedging between services in Service Communication and Timeouts, Retries & Jitter; the TCP and TLS wire details in TCP & UDP and TLS in Practice; HTTP/2 and HTTP/3 in HTTP Evolution; GeoDNS and anycast in IP, DNS & GeoDNS; edges and caches in CDN and Caching; overload in Load Shedding; dashboards and tracing in Observability.
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in three tables | Everything in one minute |
| Why the tail, not the mean, sets the user experience | Why it exists |
| Card 1991, Little 1961, Dean 2009, Dean and Barroso 2013, Tene, SRE book | Where it comes from |
| Budgets, speed of light, handshakes, deadlines | Budget, Propagation, Handshakes, Deadlines |
| p50, p99, p999, fan-out arithmetic | Percentiles, Fan-out |
| Queueing, Little's law, M/M/1, the knee | Queueing |
| GC pause, warm-up, cold start, jitter, head-of-line blocking | Variability, Head-of-line blocking |
| Hedged, tied and backup requests | Hedged, Tied |
| Micro-partitions, selective replication, probation | Micro-partitions, Probation |
| Good-enough results and canary requests | Good enough and canaries |
| Measuring correctly | Coordinated omission, Histograms, Latency SLOs |
| Regions, edge, anycast, read-local/write-global | Geography |
| Formulas, knobs, error messages | Mechanics |
| Code | Go, Laravel |
| Classic incidents and fixes | Solving the classic problems |
| Which technique when | Choosing |
| Monolith to multi-region | In architecture |
| Run the numbers yourself | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The physics you cannot optimise away. Distances are great-circle; real fibre paths are longer, so measured RTTs are higher (these are floors, labelled estimates unless a source is given).
| Quantity | Number | Source or method |
|---|---|---|
| Speed of light in fibre | about 200,000 km/s, so about 5 µs per km one way, 1 ms RTT per 100 km | Wikipedia, Optical fiber (secondary): "around 200,000 kilometers per second" |
| Round trip within one datacenter | 0.5 ms | Dean, "Numbers Everyone Should Know" (LADIS 2009) |
| California to the Netherlands and back | 150 ms | Dean, same slide |
| Frankfurt to Virginia (6,550 km) | fibre floor about 65 ms RTT; expect 80 to 95 ms | Estimate: 2 × 6,550 km × 5 µs |
| Frankfurt to Singapore (10,260 km) | floor about 103 ms RTT; expect 150 ms or more | Estimate |
| Sydney to New York (16,000 km) | "minimum delay of 80 milliseconds" one way | Wikipedia, Optical fiber |
| New TCP connection | 1 RTT before the first request byte | RFC 9293 three-way handshake |
| TLS 1.3 full handshake | +1 RTT ("1-RTT"); 0-RTT on resumption, replayable | RFC 8446 |
| TLS 1.2 full handshake | +2 RTT | RFC 5246, Figure 1 message flow |
Percentiles and fan-out.
| If each backend is slow with probability p | and one request waits for N of them | P(the request is slow) = 1 − (1 − p)^N |
|---|---|---|
| 1 in 100 (its p99 is slow) | N = 1 | 1% |
| 1 in 100 | N = 10 | 9.6% |
| 1 in 100 | N = 100 | 63% (Dean and Barroso) |
| 1 in 10,000 (its p99.99 is slow) | N = 2,000 | 18%, "almost one in five" (Dean and Barroso) |
| To make the request's p99 fast | with N = 100 | each backend must be fast at its p99.99 (0.99^(1/100)) |
The tail-tolerant toolkit (Dean and Barroso), in the order you usually reach for it.
| Technique | One line | Cost | Works when |
|---|---|---|---|
| Deadline per hop | Every hop gets "what is left minus a margin" | Nothing; prevents wasted work | Always |
| Hedged / backup request | Second copy after the p95 delay, take the first answer | About 5% extra load | Idempotent reads, replicas exist |
| Tied request | Enqueue on two servers; the first to start cancels the other | Under 1% extra disk in Google's test | Server-side queueing dominates |
| Micro-partitions | Many more partitions than machines, moved one at a time | Metadata, rebalancing | Load imbalance, slow machines |
| Selective replication | Extra copies of hot items | Storage | Skewed popularity |
| Latency-induced probation | Stop sending real traffic to a slow server, keep probing it | Temporary capacity loss | One machine is slow for a while |
| Good-enough result | Answer when enough leaves replied | Slightly incomplete answers | Search, ranking, optional widgets |
| Canary request | Send to one or two leaves before thousands | A little latency | Huge fan-out with risky queries |
The picture is the whole chapter in one bar: the same 50 ms of application work fits or misses a 300 ms budget depending on how many round trips happen before it, and how long each round trip is. Distance sets the RTT; architecture sets how many you pay.
Why it exists
A fast computer is not a fast system. Inside one process a function call costs nanoseconds and its time barely varies. Across a network every call pays distance (propagation delay), handshakes, queues in front of busy servers, and occasional pauses for reasons that have nothing to do with the request: a garbage collector, a log compaction, a neighbour on the same machine. Dean and Barroso list exactly these sources: shared resources, daemons, maintenance ("periodic garbage collection in garbage-collected languages"), queueing, power limits and energy management. Most calls are fast; a few are very slow. When one page needs many calls, the few become the many.
| Optimising the typical case | Engineering for the tail |
|---|---|
| Measures the mean or the median | Measures p99, p99.9 and the max, per hop and end to end |
| Assumes every call costs the same | Assumes a few calls are 100x slower and plans for it |
| Gives every hop a fixed, generous timeout | Gives every hop a share of one end-to-end budget |
| Removes slowness at the source (faster code, more hardware) | Also tolerates slowness it cannot remove (hedging, probation, partial answers) |
| Runs machines at low utilisation to stay fast | Can drive utilisation higher "without lengthening the latency tail" (Dean and Barroso) |
| Single region, single answer path | Places compute and data so that physics fits the budget |
The everyday picture used through this page: a dinner for N friends where the table is served only when the last plate is ready. Each cook is usually quick, but one in a hundred plates is forgotten for ten minutes. With one guest you rarely notice; with a hundred guests, most dinners wait for a forgotten plate. Hedging is asking a second cook to start the same dish if the first one is late; good enough is serving the table without the side salad; queueing is the kitchen at 95% capacity, where every new order waits behind the others; geography is whether the kitchen is next door or across the ocean.
Three common misunderstandings, up front
- "Our average latency is 40 ms, so we are fast." Google SRE: "If you run a web service with an average latency of 100 ms at 1,000 requests per second, 1% of requests might easily take 5 seconds." The mean hides exactly the requests users complain about.
- "p99 means only 1% of users suffer." A user session makes dozens of requests and every page fans out to many backends; the share of users who meet at least one p99 event is far above 1% (see Fan-out).
- "We will make the network faster." Bandwidth grew by orders of magnitude; round trips across a continent did not, because light in glass needs about 5 µs per km. You cannot buy a shorter ocean; you can only pay fewer round trips across it.
Where it comes from
Year Who / what What it added
1 1961 John Little (Little's law) L = λW: requests in system = arrival rate × time in system
2 1991 Card, Robertson, Mackinlay ~100 ms feels instant (cited by Dean & Barroso as ref. 3)
3 2009 Jeff Dean, LADIS keynote "Numbers Everyone Should Know": 0.5 ms DC RTT, 150 ms CA-NL-CA
4 2013 Dean & Barroso, CACM 56(2) "The Tail at Scale": fan-out math, hedged/tied requests, probation...
5 2013+ Gil Tene, "How NOT to Measure Latency" Coordinated omission; HdrHistogram; wrk2 constant-rate load
6 2016 Google SRE book "Worrying about your tail"; percentiles in SLOs
7 2018 RFC 8446 (TLS 1.3) 1-RTT full handshake, 0-RTT resumption
8 2021 RFC 9000 (QUIC) Transport + crypto handshake together; no HOL across streams
9 2020s OpenTelemetry exponential histograms, Mergeable high-resolution latency distributions as a standard
Prometheus native histogramsLittle and queueing theory. Little's law (1961) states that the long-term average number of customers in a stationary system equals the arrival rate times the time each spends inside (Wikipedia, Little's law, secondary; we did not fetch the original paper). The M/M/1 queue (Kendall notation: Poisson arrivals, exponential service, one server) gives the famous result that mean response time is 1/(μ − λ), which explodes as utilisation ρ = λ/μ approaches 1 (Wikipedia, M/M/1 queue, secondary).
Dean and Barroso. Their article starts from the user: "Systems that respond to user actions quickly (within 100ms) feel more fluid and natural to users than those that take longer", citing Card et al. 1991. It then shows that component variability is "magnified at the service level", measures a real Google service (Table 1: one random leaf finishes in 10 ms at p99; all leaves in 140 ms; 95% of leaves in 70 ms, so "waiting for the slowest 5% of the requests to complete is responsible for half of the total 99%-percentile latency"), and names the techniques this page catalogues. Their framing borrows from fault tolerance: "Just as fault-tolerant computing aims to create a reliable whole out of less-reliable parts, large online services need to create a predictably responsive whole out of less-predictable parts".
Gil Tene. His talk How NOT to Measure Latency (InfoQ) covers "proven methodologies for measuring, reporting, and investigating latencies" and the pitfalls. Two artefacts came out of it: HdrHistogram ("A High Dynamic Range (HDR) Histogram") and wrk2, whose README explains coordinated omission and its fix: wrk2 "measures response latency from the time the transmission should have occurred according to the constant throughput configured for the run."
Google SRE. The Monitoring Distributed Systems chapter has a section literally titled "Worrying About Your Tail", recommending latency histograms with roughly exponential buckets; the Service Level Objectives chapter recommends percentiles over means for latency SLIs.
The concept catalogue
Each block follows the same order: plain words, the usual wrong belief, a definition, a timeline or request flow, real scenarios, what products provide, and the fix.
Latency, response time and the budget Must-know
In plain words: latency is how long someone waits. A latency budget is the total wait the product allows (say 300 ms for a page), written down and split among everything that happens before the answer.
Common misunderstanding: "Latency is the server's processing time." The server's own work (service time) is often the smallest part; the user also pays DNS, connection setup, propagation, queueing, every downstream call and rendering. And "budget" does not mean "timeout": a timeout is one hop's limit, the budget is the end-to-end promise.
Definition: response time is what the client measures from sending to the last byte; service time is the time a server actually works on the request; queueing delay is the time waiting before work starts; propagation delay is distance divided by signal speed; transmission delay is message size divided by bandwidth (Dean's "Send 2K bytes over 1 Gbps network: 20,000 ns"). A latency budget allocates the response-time target across these components and hops, at a stated percentile.
Component (one page, p99 budget 300 ms) Allocated Comes from
1 DNS lookup (resolver nearby, cached) 10 ms resolver RTT
2 TCP + TLS 1.3 to the edge PoP 20 ms 2 x 10 ms RTT
3 Request to edge, edge -> origin (warm conn) 100 ms 10 ms + ~90 ms cross-region RTT
4 Origin: auth + routing 10 ms service time
5 Fan-out to 5 backends in parallel (p99 each) 80 ms max of five, not sum
6 Assemble + serialise 20 ms service time
7 Safety margin (GC, queueing, retries) 60 ms the tail you cannot remove
Total 300 msReal scenario: a checkout page with a 1 s budget where the payment provider promises 400 ms; a search box that must answer each keystroke in about 100 ms; a mobile API whose users are 200 ms away on cellular networks; an internal batch API where a 5 s budget is fine.
What provides it: nothing automatic. The budget is a design artefact (an ADR, a row in the SLO doc). Products enforce parts of it: gRPC deadlines, Envoy route timeouts, Go context.WithTimeout, Laravel Http::timeout(); see Deadlines.
Fix / how to use it: write the budget before the design (step 2 of The 4-Step Approach); state the percentile (a budget without a percentile means nothing); give every hop a share; keep 15 to 25% unallocated for the tail.
Propagation delay: speed of light and fibre Must-know
In plain words: a signal in optical fibre covers about 200 km per millisecond. A round trip doubles the distance. Nothing in software changes this.
Common misunderstanding: "More bandwidth reduces latency." Bandwidth (bits per second) affects transmission delay for large payloads; propagation delay depends only on distance and the medium. A 100 Gbit/s link from Frankfurt to Virginia still has a floor of about 65 ms RTT.
Definition: light in vacuum travels at 299,792 km/s; glass has a refractive index of about 1.5 ("Silica and fluoride glasses usually have refractive indices of about 1.5"), so light in fibre travels at about 200,000 km/s: 5 µs per km one way, 10 µs per km round trip. Real routes follow cables and pass routers, so measured RTT is commonly 1.3 to 2x the great-circle floor (our estimate, not a cited number).
Route (great-circle distance) Fibre floor RTT Typical measured RTT (estimate)
1 Same rack / same AZ ~0 0.1 - 0.5 ms (Dean: 0.5 ms in a DC)
2 Between AZs in one region (~50 km) 0.5 ms 1 - 2 ms
3 Frankfurt -> London (640 km) 6.4 ms 10 - 15 ms
4 Virginia -> California (3,880 km) 39 ms 60 - 75 ms
5 Frankfurt -> Virginia (6,550 km) 65 ms 80 - 95 ms
6 California -> Amsterdam (8,790 km) 88 ms ~150 ms (Dean: CA-NL-CA 150 ms)
7 Frankfurt -> Singapore (10,260 km) 103 ms 150 - 200 msReal scenario: a European user calling an API hosted only in us-east-1; a microservice in eu-west-1 that synchronously reads a database in us-east-1 on every request (90 ms added per query, multiplied by the number of queries); a "global" Redis used for sessions from three continents; a multi-region consensus write (each commit pays at least one cross-region RTT).
What provides it: physics provides the floor; products provide ways to pay it fewer times: CDNs and edge PoPs (Cloudflare, AWS CloudFront, Fastly) terminate connections near users; AWS Global Accelerator and Cloudflare announce anycast addresses so users enter the provider's backbone at the nearest PoP ("The static IP addresses are anycast from the AWS edge network"); read replicas and caches move data closer.
Fix / how to use it: count cross-region round trips per request and keep that number at zero or one on the hot path; never make a sequential loop of cross-region calls; put data where it is read (Geography).
RTT and handshake costs: TCP, TLS, QUIC Must-know
In plain words: before the first request byte, a new connection spends round trips agreeing to talk (TCP) and agreeing on keys (TLS). On a long path, those round trips are most of the page time.
Common misunderstanding: "TLS is expensive because of the crypto CPU." On modern CPUs the handshake math is cheap; the cost users feel is the extra round trip(s). A cold TLS 1.2 connection across the Atlantic costs about 3 RTTs (TCP + 2) before the request: roughly 270 ms at 90 ms RTT.
Definition: RFC 9293 synchronises sequence numbers with SYN, SYN-ACK, ACK: "The synchronization requires each side to send its own initial sequence number and to receive a confirmation of it", so data starts after one RTT. TCP Fast Open (RFC 7413) "saves up to one full round-trip time (RTT)" by carrying data in the SYN, with replay caveats. TLS 1.3 (RFC 8446) completes a full handshake in one round trip and adds "A zero round-trip time (0-RTT) mode ... saving a round trip at connection setup for some application data, at the cost of certain security properties"; 0-RTT data has "no guarantees of non-replay between connections". TLS 1.2's full handshake (RFC 5246, Figure 1) needs two round trips. QUIC (RFC 9000) runs the transport and TLS 1.3 handshakes together, so HTTP/3 needs one RTT for a new connection and supports 0-RTT. The wire details belong to TLS in Practice and TCP & UDP.
t (RTT = 90 ms) Cold HTTPS over TCP + TLS 1.3 Warm keep-alive connection
1 0 -> SYN -> GET /api (encrypted)
2 90 <- SYN-ACK; -> ACK + ClientHello <- 200 OK (done at 90 ms + server time)
3 180 <- ServerHello...Finished; -> Finished + GET
4 270 <- 200 OK (done at 270 ms + server time)
TLS 1.2 adds one more RTT (360 ms); HTTP/3 (QUIC) folds TCP+TLS into one (180 ms); 0-RTT resumption: 90 msReal scenario: a mobile app that opens a new connection per request; a PHP-FPM worker calling a partner API without connection reuse (each request is a new process-level client); a Go service with MaxIdleConnsPerHost left at its default of 2 under 100 concurrent requests (most requests open new connections); a service mesh sidecar (Envoy, Linkerd) that keeps a warm mTLS pool so the app never pays the handshake.
What provides it:
| Product | Connection reuse / handshake saving | Default to know |
|---|---|---|
Go net/http Transport | Keep-alive pool, HTTP/2 multiplexing | DefaultMaxIdleConnsPerHost = 2; TLSHandshakeTimeout: 10 * time.Second in DefaultTransport |
| Laravel HTTP client (Guzzle/cURL) | cURL reuses connections within one handle; PHP-FPM workers start fresh per process | timeout 30 s, connectTimeout 10 s |
| NGINX upstream | keepalive connections to upstreams | Off unless configured |
| Envoy / Istio | Pooled upstream connections, mTLS in the sidecar | Per-cluster pools |
| Cloudflare / CloudFront | TLS terminates at the edge; warm connections to the origin | Edge close to the user |
| HTTP/3 (QUIC) | 1-RTT setup, 0-RTT resumption | See HTTP Evolution |
Fix / how to use it: reuse connections (one shared client per process, sized pools); terminate TLS close to the user; enable TLS 1.3 everywhere; allow 0-RTT only for idempotent requests (replay); measure handshake phases with httptrace (Go).
Per-hop budgets and deadline propagation Must-know
In plain words: the edge decides once how long the user will wait; each hop gets what is left minus a margin, capped at what that dependency normally needs, and nobody starts work that cannot finish in time.
Common misunderstanding: "Each service sets its own timeout, 30 seconds to be safe." Fixed timeouts that ignore the caller waste work (the callee keeps going after the user has left) and sum to absurd worst cases: five hops of 30 s is a 150 s request nobody waits for. The mechanics (headers, gRPC grpc-timeout, retry budgets) are taught in Service Communication; this block owns the numbers.
Definition: a timeout budget is the remaining time a hop may spend. Google SRE: "a deadline is set high in the stack (e.g., in the frontend)" and the whole tree shares it. AWS: "we choose an acceptable rate of false timeouts (such as 0.1%). Then, we look at the corresponding latency percentile on the downstream service (p99.9 in this example)." The per-hop timeout is therefore min(cap from the callee's p99.9, remaining − margin), and a hop refuses the call when that number is below the callee's p50 (it cannot succeed).
Hop Receives Spends Cap (callee p99.9) Sends on
1 Edge (budget 800) 800 ms 40 ms - 800 - 40 - 10 = 750
2 API gateway 750 10 - 740 - 10 = 730
3 Orders 730 60 300 min(300, 730 - 60 - 10) = 300
4 Inventory 300 50 120 min(120, 300 - 50 - 10) = 120
5 Inventory -> DB 120 - - query cancelled at 120 ms
6 A late hop with 25 ms left and a callee p50 of 40 ms returns "budget exhausted" without callingReal scenario: a search page with a 300 ms budget calling five backends; a payment flow where the partner's contract is 2 s and the page budget 3 s; a batch job that calls the same API with a 30 s budget (budgets travel with the request because callers differ).
What provides it:
| Product | Primitive | Propagates? |
|---|---|---|
| gRPC | Deadline; grpc-timeout on the wire (relative) | Yes, when the incoming context is passed on |
| Go | context.WithTimeout, http.NewRequestWithContext | No header; this page's budget package stamps Request-Timeout-Ms |
| Laravel | Http::timeout(float), connectTimeout() | No; this page's LatencyBudget computes per-hop values |
| Envoy | Route timeout, per_try_timeout, x-envoy-expected-rq-timeout-ms | Inside the mesh |
| NGINX | proxy_connect_timeout, proxy_read_timeout (default 60s) | No |
Fix / how to use it: Go budget.ForHop plus budget.Stamp; Laravel LatencyBudget::hopTimeout() plus outgoingHeaders(); send remaining milliseconds, never an absolute timestamp (clock skew between hosts).
Percentiles: p50, p90, p99, p999 and why averages lie Must-know
In plain words: sort all response times; the p99 is the value that 99% of requests beat. p50 (the median) is the typical request, p99 and p99.9 (p999) are the bad days, the max is the worst single request.
Common misunderstanding: "The mean is a fine summary if traffic is large." Latency is skewed: it cannot go below zero, and it has a long right tail. Google SRE: "it's entirely possible for most of the requests to be fast, but for a long tail of requests to be much, much slower", and "we cannot assume that the mean and the median are the same—or even close to each other!" Footnote 23 of the monitoring chapter adds: "If 1% of your requests are 50x the average, it means that the rest of your requests are about twice as fast as the average."
Definition: Prometheus: "The φ-quantile is the observation value that ranks at number φ*N among the N observations ... The 0.5-quantile is known as the median. The 0.95-quantile is also called the 95th percentile." A percentile is always over a population and a window ("p99 over 5 minutes, measured at the load balancer"). Percentiles do not average: the p99 of two servers is not the mean of their p99s.
1,000 requests in one minute mean p50 p90 p99 p99.9 max
1 985 at 10 ms, 15 at 1,000 ms 24.9 ms 10 ms 10 ms 1,000 1,000 1,000
2 Same, but the 15 slow ones at 5,000 ms 84.9 ms 10 ms 10 ms 5,000 5,000 5,000
3 1,000 at 25 ms (no tail) 25 ms 25 ms 25 ms 25 25 25
Rows 1 and 3 have the same mean; only one of them has angry users.Real scenario: a dashboard showing a flat mean while 1.5% of checkouts time out; an SLA stated as "average under 200 ms" that the provider meets while customers churn; capacity planning from mean CPU that misses one hot core; SRE's Bigtable story, where "the mean performance was driven by a 'large' tail: the worst 5% of requests were often significantly slower than the rest".
What provides it:
| Product | How it computes percentiles | Aggregatable across instances? |
|---|---|---|
| Prometheus histogram (classic) | histogram_quantile(0.99, sum by (le) (rate(..._bucket[5m]))) | Yes, sum the buckets |
| Prometheus native histogram | histogram_quantile(0.99, sum(rate(...[5m]))) | Yes |
| Prometheus summary | Client-side quantiles | No: avg(...{quantile="0.95"}) is "statistically nonsensical" |
| OpenTelemetry exponential histogram | Buckets by scale; backend computes | Yes ("perfect subsetting") |
| HdrHistogram | getValueAtPercentile; merge by adding | Yes |
| PostgreSQL | percentile_cont, percentile_disc on raw rows | Exact, but needs raw data |
| Laravel Pulse | Aggregates avg, count, max, min, sum | No percentiles |
Fix / how to use it: record histograms, never only means; always state percentile, window and measurement point; alert on p99 (or "share of requests under X ms"), dashboard p50, p90, p99, p99.9 and max together.
Fan-out: how percentiles compose Must-know
In plain words: if a request waits for all of N backends, it is slow when any of them is slow. Rare slowness per backend becomes common slowness per request.
Common misunderstanding: "Each backend meets p99 = 10 ms, so our page meets p99 = 10 ms plus overhead." With 100 backends in parallel, 63% of pages include at least one backend's p99 event; the page's p99 is set by the backends' p99.99.
Definition: for independent backends each slow with probability p, P(request slow) = 1 − (1 − p)^N. Dean and Barroso: "If a user request must collect responses from 100 such servers in parallel, then 63% of user requests will take more than one second." Conversely, to meet an end-to-end quantile q with fan-out N, each backend must meet q^(1/N). Sequential calls add latencies; parallel calls take the max; both make the tail worse. Real backends are not fully independent (a shared switch, a shared database), which can make it better (correlated) or worse (correlated overload).
Scatter-gather (root waits for all leaves), from Dean and Barroso Table 1
1 root -> 1 random leaf finishes: p50 1 ms p95 5 ms p99 10 ms
2 root -> 95% of all leaves finish: p50 12 ms p95 32 ms p99 70 ms
3 root -> 100% of all leaves finish: p50 40 ms p95 87 ms p99 140 ms
4 the last 5% of leaves cost half of the 140 ms p99 -> techniques aimed at stragglers pay offReal scenario: a product page assembled from 30 microservices; a search over 1,000 shards; a feed that reads 200 followees' timelines; a GraphQL query whose resolvers call 40 backends (the N+1 problem in latency form); a microservice chain that is sequential by accident (await in a loop).
What provides it: the math is universal; products give you scatter-gather primitives: Go errgroup with SetLimit, Laravel Http::pool(..., concurrency: 5), Elasticsearch's shard fan-out with timeout and partial results, Cassandra's coordinator and consistency levels (wait for a quorum, not all).
Fix / how to use it: reduce N (fewer, coarser calls; caches; precomputed views); make calls parallel, not sequential; wait for fewer than all (quorums, good-enough); hedge the stragglers; and set the per-leaf target from q^(1/N), not from the page target. Go: fanout.PAtLeastOneSlow, fanout.LeafQuantileFor, fanout.Gather.
Queueing delay, utilisation, Little's law and the knee Must-know
In plain words: when work arrives faster than it can be done for a moment, requests wait in line. The busier the server, the longer the line, and the growth is not linear: going from 80% to 90% busy doubles the wait.
Common misunderstanding: "CPU at 85% is efficient; we still have 15% headroom." Latency headroom ends long before capacity does. In M/M/1, mean response time is S/(1 − ρ): 2x the service time at 50% utilisation, 5x at 80%, 10x at 90%, 20x at 95%. The p99 is about 4.6 times the mean in that model.
Definition: utilisation ρ = λ/μ (arrival rate over service rate); Wikipedia's M/M/1 article: "We write ρ = λ/μ for the utilization of the buffer and require ρ < 1 for the queue to be stable" and the "average response time or sojourn time ... can be computed using Little's law as 1/(μ − λ)". Little's law: L = λW. The knee is the region (commonly 70 to 80% for single-queue services, a rule of thumb derived from this curve, not a law) where waiting starts to dominate service time. More servers per queue (M/M/c) push the knee to the right; burstier arrivals push it left. Google SRE notes the tail effect is "exacerbated at high load by queuing effects".
M/M/1, service time S = 10 ms (from this page's tailsim, formula values)
rho queueing delay mean W p99 = ln(100) x W
1 0.50 10 ms 20 ms 92 ms
2 0.70 23 ms 33 ms 154 ms
3 0.80 40 ms 50 ms 230 ms
4 0.90 90 ms 100 ms 461 ms
5 0.95 190 ms 200 ms 921 ms
Little's law check at rho = 0.8, lambda = 80 req/s: L = 80 x 0.050 s = 4 requests in the systemReal scenario: a PHP-FPM pool of 20 workers serving 18 concurrent requests (90% busy: every burst queues at the listen socket); a PostgreSQL connection pool at 95% checkout (requests wait for a connection, not for the query); a Kafka consumer group with lag that grows only at peak; an autoscaler targeting 85% CPU that keeps p99 permanently high; Dean and Barroso's "Differentiating service classes and higher-level queuing" (keep low-level queues short so priorities work).
What provides it: load balancers that look at queue length (Envoy LEAST_REQUEST uses power of two choices: "picks the host which has the fewest active requests"), concurrency limits and load shedding (Load Shedding), Kubernetes HPA targets, connection pool sizes (Connection Pooling).
Fix / how to use it: size for latency, not for throughput: target 50 to 70% utilisation on latency-critical tiers; bound queues and reject early (a fast 503 beats a slow 200 nobody waits for); separate interactive from batch queues; use Little's law to size pools (workers ≥ λ × W with headroom).
Sources of variability: GC pauses, warm-up, cold starts, jitter Important
In plain words: the same request on the same code is sometimes slow for reasons outside the request: the runtime collects garbage, the cache is cold after a deploy, a serverless function boots, a neighbour hogs the disk, the network path varies (jitter).
Common misunderstanding: "If p99 is high, the slow requests must be doing something expensive." Often they are ordinary requests that arrived at a bad moment. Look at when slow requests happen (deploys, GC cycles, cron jobs, compactions) before looking at what they do.
Definition: a GC pause is time the runtime stops or slows application threads. The Go GC "is not fully stop-the-world and does most of its work concurrently", but the Go GC guide still lists "Brief stop-the-world pauses when the GC transitions between the mark and sweep phases", "Scheduling delays because the GC takes 25% of CPU resources when in the mark phase" and "User goroutines assisting the GC in response to a high allocation rate". Warm-up is the period after start when caches, JIT, connection pools and DNS caches are empty. A cold start (AWS Lambda): downloading code and setting up the environment "are frequently referred to as a 'cold start'", which "adds latency to your overall invocation duration"; AWS says cold starts "typically occur in under 1% of invocations" and last "from under 100 ms to over 1 second". Jitter in networking is packet delay variation; RFC 3393 warns the term "causes confusion because it is used in different ways" (the retry-backoff "jitter" in Timeouts, Retries & Jitter is a different, deliberate randomisation).
t Event on one pod Effect on requests in flight
1 00:00 Deploy: new pod starts, empty caches first 200 requests miss cache: p99 x 5
2 00:00 New pod opens DB pool lazily first requests pay TCP + TLS + auth to PostgreSQL
3 00:05 Go GC mark phase, high allocation rate goroutines assist GC: +2-5 ms on unlucky requests
4 00:30 Nightly compaction / backup on the host disk queue grows: storage p99 x 10
5 00:45 Lambda scales out: new environment one request pays the cold start (100 ms - 1 s+)Real scenario: latency spikes after every deploy (warm-up); a JVM service with periodic multi-hundred-ms pauses; an SSD garbage-collecting blocks (Dean and Barroso: it "can increase read latency by a factor of 100 with even a modest level of write activity"); CPU thermal throttling; a Laravel Octane worker that is fast but a PHP-FPM cold opcache after deploy that is not.
What provides it:
| Source | Product knob | Effect |
|---|---|---|
| Go GC | GOGC, GOMEMLIMIT (via runtime/debug) | Fewer cycles means fewer assists and pauses |
| JVM GC | G1, ZGC, Shenandoah collectors | Low-pause collectors trade throughput |
| Warm-up | Kubernetes readinessProbe, startupProbe, slow-start in Envoy and NGINX Plus | No traffic until warm, then ramp up |
| AWS Lambda cold start | Provisioned Concurrency, SnapStart | Pre-initialised environments |
| PHP | OPcache preloading, Laravel Octane (persistent workers) | No per-request bootstrap |
| Background work | Throttling, scheduling off-peak, Dean and Barroso's synchronised disruption | Fewer interfered requests |
Fix / how to use it: reduce allocation on hot paths; keep instances warm before they take traffic; schedule background work; and accept what remains with hedging and margins.
Head-of-line blocking Important
In plain words: one slow item at the front of a line holds up everything behind it, even items that would be quick.
Common misunderstanding: "HTTP/2 solved head-of-line blocking." HTTP/2 removed it at the HTTP layer (many streams on one connection) but kept it at the TCP layer: one lost packet stalls every stream until retransmission. QUIC fixes the transport part: RFC 9000, "only streams with data in that packet are blocked waiting for a retransmission to be received, while other streams can continue making progress." Application queues have their own HOL blocking no protocol can fix.
Definition: head-of-line blocking is any FIFO structure where the first item's delay is imposed on later, independent items: HTTP/1.1 pipelining, TCP byte streams, a single worker queue mixing cheap and expensive jobs, a Kafka partition where one slow message blocks the partition's consumer (Ordering & Partitioning). Dean and Barroso: "Google's Web search system uses such time-slicing to prevent a small number of very computationally expensive queries from adding substantial latency to a large number of concurrent cheaper queries."
Single FIFO worker, mixed jobs Separate queues / time-slicing
1 job A (2,000 ms report) starts queue fast: B, C, D run at once
2 job B (5 ms) waits 2,000 ms queue slow: A runs on its own worker
3 job C (5 ms) waits 2,005 ms B, C, D: 5 ms each
4 job D (5 ms) waits 2,010 ms A: 2,000 ms (as expected)Real scenario: a Laravel queue where a 10-minute export blocks password-reset emails; a gRPC channel over a lossy mobile link; a database with one long transaction holding a lock; an HTTP/1.1 client with a pool of 2 connections to a slow upstream.
What provides it: HTTP/2 and HTTP/3 (protocol level), separate queues and Horizon supervisors per queue (Laravel), priority queues in the storage layer (Dean and Barroso's shallow OS queues plus application priority queues), Kafka key design.
Fix / how to use it: split by cost class; break long work into slices; keep low-level queues shallow; use HTTP/3 where packet loss is common.
Hedged and backup requests Must-know
In plain words: if the first copy of a read is slower than usual, send the same request to another replica and use whichever answers first; cancel the other.
Common misunderstanding: "Hedging doubles the load." Sent naively, yes. Sent only after the p95 delay, only the slowest 5% get a copy: Dean and Barroso, "This approach limits the additional load to approximately 5% while substantially shortening the latency tail." Second wrong belief: "hedging is a retry." A retry follows a failure; a hedge runs beside a slow request.
Definition: "issue the same request to multiple replicas and use the results from whichever replica responds first ... a client first sends one request to the replica believed to be the most appropriate, but then falls back on sending a secondary request after some brief delay. The client cancels remaining outstanding requests once the first result is received." In a BigTable benchmark reading 1,000 keys from 100 servers, "sending a hedging request after a 10ms delay reduces the 99.9th-percentile latency for retrieving all 1,000 values from 1,800ms to 74ms while sending just 2% more requests." Finagle calls them backup requests (idempotent(maxExtraLoad = 1.percent)); gRPC calls them hedging (hedgingPolicy).
This page's tailsim (seeded): leaf = 5-15 ms, 1% of calls take 1 s; hedge every 15 ms, max 2 hedges
N leaves P(>=1 slow) p50 p99 plain p99 hedged extra calls
1 1 0.010 10 ms 14 ms 14 ms 1.0%
2 10 0.096 14 ms 1.00 s 29 ms 1.0%
3 100 0.634 1.00 s 1.00 s 35 ms 1.0%Real scenario: reading a user profile from one of three Cassandra replicas; a key-value lookup in a cache cluster; DNS resolvers (clients query several and take the first); search leaf queries; object-storage GETs from S3 or GCS for large fan-out reads.
What provides it:
| Product | Feature | Note |
|---|---|---|
| gRPC | hedgingPolicy (maxAttempts up to 5, hedgingDelay, nonFatalStatusCodes) | The gRPC guide lists Go "Not yet supported", C++ "Not yet available"; Java supports it |
| Envoy | "request hedging for retries in response to a request (per try) timeout" | hedge_policy on the route |
| Finagle (Twitter) | Backup requests via maxExtraLoad | "can be disabled by setting maxExtraLoad to 0.0" |
| Cassandra | speculative_retry table option ("rapid read protection"), e.g. 99percentile | Coordinator sends an extra read to another replica when the first is slower than that percentile |
| This page, Go | hedge.Do with a token-bucket Budget | Delay at p95, cancel losers |
Fix / how to use it: only idempotent reads (or writes with idempotency keys and server-side dedup, API Idempotency); delay at about p95 of this request class; cap total copies; cap extra load with a budget; propagate cancellation so losers stop working; tag hedges as lower priority if the server supports it.
Tied requests Important
In plain words: put the same request in two servers' queues at once, each copy knowing about the other; whichever server starts it first tells the other to drop its copy.
Common misunderstanding: "Tied requests are just hedging with zero delay." Hedging with zero delay doubles the work. Tied requests cancel the twin before execution, so the duplicate costs only a queue slot. Their target is queueing delay, the main source of variability: "once a request is actually scheduled and begins execution, the variability of its completion time goes down substantially."
Definition: "The simplest form of a tied request has the client send the request to two different servers, each tagged with the identity of the other server ('tied'). When a request begins execution, it sends a cancellation message to its counterpart." To avoid both starting when queues are empty, the client waits "two times the average network message delay (1ms or less in modern data-center networks)" before the second copy. Google's BigTable-on-distributed-file-system test (Table 2): with a concurrent terasort, p99 fell from 108 ms to 67 ms (−38%), p99.9 from 159 ms to 108 ms, with "less than 1%" extra disk utilisation.
t (ms) Client Server A queue Server B queue
1 0 send(A, tied=B) [x, y, req]
2 1 send(B, tied=A) [req]
3 1.2 B starts req -> cancel(A, req)
4 1.4 req removed before running
5 9 <- answer from B A never spent CPU on reqReal scenario: a distributed file system or object store with three replicas per chunk; a sharded search with replicated leaves; database read replicas behind an application-level router.
What provides it: rarely available off the shelf; it needs servers that accept a "tied to" tag and a cancel message. Google's cluster file system implements it (per the paper). Most teams approximate it with hedging plus fast cancellation (gRPC/HTTP context cancellation), or with "probe then send" (Dean and Barroso explain why that is weaker: load changes between probe and request, and clients herd on the same least-loaded server).
Fix / how to use it: if you own the storage servers, implement cross-server cancellation; otherwise prefer power-of-two-choices load balancing (Envoy LEAST_REQUEST) plus hedging.
Micro-partitions and selective replication Important
In plain words: cut the data into many more pieces than you have machines so you can move small pieces off a slow or overloaded machine; and give the hot pieces extra copies.
Common misunderstanding: "One shard per server is simpler and balanced." Machines are neither uniform nor constant (thermal throttling, noisy neighbours), and popularity is skewed. With one partition per machine, the only fix for a slow machine is moving all of its data.
Definition: micro-partitions: "generate many more partitions than there are machines in the service, then do dynamic assignment and load balancing of these partitions to particular machines ... With an average of, say, 20 partitions per machine, the system can shed load in roughly 5% increments and in 1/20th the time". BigTable keeps "between 20 and 1,000 tablets" per machine. Selective replication: "detect or even predict certain items that are likely to cause load imbalance and create additional replicas of these items"; Google web search makes "additional copies of popular and important documents in multiple micro-partitions".
12 machines, 240 micro-partitions (20 each); machine m7 becomes slow
1 monitor: m7 p99 = 4x cluster p99 for 2 minutes
2 balancer: move 4 of m7's 20 partitions (20% of its load) to m1, m3, m9, m11
3 m7 p99 returns to normal; recovery took seconds, not a full re-shard
4 item "world-cup-final" is 50x average reads -> 3 extra replicas of its partitionReal scenario: Kafka topics with many more partitions than brokers; Cassandra and ScyllaDB virtual nodes (vnodes) and tablets; Redis Cluster's 16,384 hash slots; DynamoDB adaptive capacity for hot partitions; Elasticsearch over-sharding with shard relocation; a CDN replicating a viral object to every PoP.
What provides it: Redis Cluster (slots), Cassandra (vnodes), CockroachDB and TiDB (ranges split and moved automatically), Elasticsearch (shards), Kafka (partitions with reassignment). Ring internals live in Consistent Hashing; system-level resharding in Sharding at System Level.
Fix / how to use it: choose a partition count 10 to 100x the machine count up front; automate moves on latency signals; replicate hot keys (or cache them at the edge) instead of re-sharding.
Latency-induced probation Good to know
In plain words: when one server is clearly slower than its peers, stop sending it real requests for a while, keep sending it test (shadow) requests, and bring it back when it recovers.
Common misunderstanding: "Removing capacity under load can only make latency worse." Dean and Barroso call the effect "somewhat peculiar, as removal of serving capacity from a live system during periods of high load actually improves latency." A slow server poisons every fan-out it takes part in.
Definition: "By observing the latency distribution of responses from the various machines in the system, intermediate servers sometimes detect situations where the system performs better by excluding a particularly slow machine, or putting it on probation ... the system continues to issue shadow requests to these excluded servers, collecting statistics on their latency so they can be reincorporated into the service when the problem abates."
t Intermediate server view Action
1 00:00 peers p99 = 12 ms; host h4 p99 = 95 ms h4 -> probation
2 00:00 real traffic to h4 = 0; shadow requests = 1/s keep measuring
3 02:00 h4 shadow p99 = 13 ms for 60 s h4 back in rotation, ramp upReal scenario: a replica on a host with a failing disk; a pod sharing a node with a CPU-heavy batch job; a database replica whose replication apply thread fell behind.
What provides it: Envoy outlier detection ejects hosts on error signals (consecutive 5xx, consecutive gateway failure, success rate, failure percentage) rather than latency, so latency-based probation is usually built at the client or balancer; Envoy LEAST_REQUEST and Finagle's latency-aware balancers (P2C with EWMA) naturally send less to slow hosts; Kubernetes readiness probes can take a pod out of Service endpoints.
Fix / how to use it: track per-host latency (an EWMA or a short-window histogram); eject hosts whose p99 exceeds k times the peer median; cap ejected hosts (Envoy's max_ejection_percent idea) so you never eject half the cluster; reintroduce gradually.
Good-enough results and canary requests Important
In plain words: in a big fan-out, answer when enough backends have replied rather than waiting for all; and before sending a risky request to thousands of servers, send it to one or two first.
Common misunderstanding: "Incomplete answers are bugs." For search, ranking and optional page parts, a slightly incomplete answer now is better than a perfect one late: "returning good results quickly is better than returning the best results slowly." And "canaries add latency so we skip them": they add one leaf's latency, which has far less variability than waiting for all leaves.
Definition: good enough: "once a sufficient fraction of all the leaf servers has responded, the user may be best served by being given slightly incomplete ('good-enough') results in exchange for better end-to-end latency"; also used "to skip nonessential subsystems ... results from ads or spelling-correction systems are easily skipped for Web searches if they do not respond in time." Canary requests: "rather than initially send a request to thousands of leaf servers, a root server sends it first to one or two leaf servers. The remaining servers are only queried if the root gets a successful response from the canary in a reasonable period of time."
Root with 1,000 leaves, budget 120 ms, minFraction 0.98
1 t=0 canary query -> leaf 17, leaf 503
2 t=9 both answer OK -> fan out to the other 998
3 t=60 985 leaves answered (98.5%)
4 t=80 budget for stragglers ends: reply with 993/1000, partial=true
5 a query that crashes the canary is never sent to the other 998 (protects the fleet)Real scenario: a product page that drops the "recommended for you" strip when it is late; an Elasticsearch search returning timed_out: true with partial hits; a feed that shows the posts it has; a dashboard tile that says "data delayed".
What provides it: Elasticsearch search with a per-shard timeout and allow_partial_search_results (default true: "If true and there are shard request timeouts or shard failures, the request returns partial results"; the response says timed_out); Go fanout.Gather (this page); Laravel Http::pool with optional entries; GraphQL partial data with errors.
Fix / how to use it: classify every dependency as required or optional; give optional ones a short leash; mark partial responses explicitly (partial: true) so caches and clients do not treat them as complete; keep good-enough rare and monitored.
Coordinated omission in load tests Must-know
In plain words: a load generator that waits for each answer before sending the next request quietly stops sending while the server is stalled, so the stall is measured once instead of as hundreds of slow requests. The tool and the server "coordinate" to omit the bad samples.
Common misunderstanding: "Our load test shows p99 = 2 ms, so production p99 will be 2 ms." If the generator is closed-loop and measures from the actual send time, a 2-second stall at 100 requests per second shows up as one slow sample instead of about 200. The p99 looks perfect; real users who kept arriving during the stall waited up to 2 s.
Definition: Tene's wrk2 README: "Rather than measure response latency from the time that the actual transmission of a request occurred, wrk2 measures response latency from the time the transmission should have occurred according to the constant throughput configured for the run." HdrHistogram offers after-the-fact correction: recordValueWithExpectedInterval() is "useful in [common latency measurement] scenarios where response times may exceed the expected interval between issuing requests, leading to 'dropped' response time measurements that would typically correlate with 'bad' results."
tailsim: 100 req/s for 100 s, the server stalls 2 s at t = 50 s
Measurement n p50 p99 p99.9 max
1 from actual send (wrk, ab) 10,000 1 ms 1 ms 1 ms 2.00 s
2 from intended send (wrk2) 10,000 1 ms 1.10 s 1.92 s 2.00 s
3 RecordCorrected (HdrHist) 10,199 1 ms 991 ms 1.90 s 2.00 sReal scenario: JMeter or ab tests that "prove" an SLO; a synthetic monitor that sends one request per minute and waits; a client library that measures only successful calls; an APM agent sampling only completed requests.
What provides it: wrk2 (-R constant rate), k6 with arrival-rate executors (constant-arrival-rate), Gatling open-model injection, Vegeta (constant rate); HdrHistogram's corrected recording; this page's hist.RecordCorrected.
Fix / how to use it: use open-model, constant-rate load generators; measure from the intended start time; record every request including errors and timeouts (a timeout is a latency of at least the timeout); report the full percentile spectrum and the max.
Histograms: HdrHistogram, Prometheus buckets, OpenTelemetry exponential Must-know
In plain words: instead of storing every latency or a single average, count requests per latency range (bucket). Counts can be added across servers and minutes, and any percentile can be read off later.
Common misunderstanding: "Prometheus summaries are more accurate, so use them." Summary quantiles are accurate per instance but cannot be combined: Prometheus says averaging them "yields statistically nonsensical values" (avg(http_request_duration_seconds{quantile="0.95"}) // BAD!). Histograms are slightly less precise per bucket but aggregate correctly.
Definition: a histogram has buckets with counts plus a total count and sum. Three families:
| Family | Bucket layout | Precision | Aggregation |
|---|---|---|---|
| HdrHistogram | Log-linear; fixed significant digits ("3 significant digits ... no larger than 1/1,000th (or 0.1%) of any value") | Configurable, 1 to 5 digits | Exact merge by adding counts |
| Prometheus classic histogram | Explicit cumulative le buckets, one series per bucket (_bucket, _sum, _count) | "limited by the width of the bucket the quantile is located in" | Sum by le, if bucket boundaries match |
| Prometheus native histogram | Exponential schema, sparse buckets, one series | "Limited by the configured resolution" | Any; layouts reconciled automatically |
| OpenTelemetry exponential histogram | base = 2**(2**(-scale)), "2**scale buckets between successive powers of 2" | Scale up to 20; default MaxSize 160 buckets | "perfect subsetting": downscale without error |
| OpenTelemetry explicit histogram | Default boundaries [0, 5, 10, 25, 50, 75, 100, 250, 500, 750, 1000, 2500, 5000, 7500, 10000] | Coarse | Like classic |
Choosing classic Prometheus buckets for a 300 ms SLO (seconds, base units)
1 le="0.025" "0.05" "0.1" "0.2" "0.3" "0.45" "0.75" "1" "2.5" "+Inf"
2 put a boundary exactly at the SLO threshold (0.3): the "share under 300 ms" is then exact
3 histogram_quantile(0.99, sum by (le) (rate(http_request_duration_seconds_bucket[5m])))
4 native or OTel exponential histograms: no boundaries to choose; interpolation near 0.3 is still closeReal scenario: a fleet of 200 pods each exporting a histogram, summed into one p99; changing an SLO from 300 ms to 250 ms (exponential histograms answer it immediately, classic ones need a new boundary and a redeploy); an HdrHistogram in a load tester; a Redis-backed histogram in Laravel (this page).
What provides it: Prometheus client libraries (Go prometheus.NewHistogram with Buckets or NativeHistogramBucketFactor, e.g. 1.1 as the Prometheus docs suggest), OpenTelemetry SDKs (Base2 Exponential Bucket Histogram aggregation), HdrHistogram ports (Java, C, Go hdrhistogram-go, Rust, Python...), Google SRE's advice: buckets "approximately exponentially (in this case by factors of roughly 3)".
Fix / how to use it: prefer native/exponential histograms; with classic histograms put boundaries at your SLO thresholds; use base units (seconds); never average quantiles; record timeouts as values at the timeout.
Latency SLOs Must-know
In plain words: a latency SLO is a promise like "99% of checkout requests finish within 300 ms over 28 days", measured at a named point. The error budget is the 1% that may be slower.
Common misunderstanding: "SLO: average latency under 100 ms." The SRE book uses an average example to introduce SLOs, then recommends percentiles: "Using percentiles for indicators allows you to consider the shape of the distribution". A second wrong belief: "p99 under 300 ms, computed per minute and averaged over the month." Averaging per-minute p99s is not the monthly p99; count good requests instead.
Definition: a request-based latency SLI is good requests / valid requests where good means duration ≤ threshold. SRE's example: "99% (averaged over 1 minute) of Get RPC calls will complete in less than 100 ms (measured across all the backend servers)." Multiple thresholds are common: 90% under 100 ms and 99% under 400 ms. The mechanics of error budgets, burn rates and alerting belong to SLAs, SLOs, SLIs & Error Budgets.
28-day window, 120 M checkout requests, SLO: 99% <= 300 ms
1 good = 118.9 M (<= 300 ms), bad = 1.1 M -> 99.08%: SLO met
2 error budget = 1% x 120 M = 1.2 M slow requests -> 0.1 M left
3 a deploy adds 40 ms to p99 for 2 days -> burns 0.3 M -> budget overspent: freeze
4 PromQL (classic): sum(rate(..._bucket{le="0.3"}[5m])) / sum(rate(..._count[5m]))Real scenario: an API contract with a partner ("p99 under 500 ms, measured at our load balancer"); an internal platform SLO for a database proxy; a mobile team measuring at the client (real user monitoring) while the backend measures at the server.
What provides it: Prometheus recording rules, Google Cloud Monitoring and Datadog SLO objects, Grafana SLO, OpenSLO specifications; measurement points: client (RUM), edge (Cloudflare, CloudFront logs), load balancer (AWS ALB TargetResponseTime), server middleware.
Fix / how to use it: state threshold, percentile, window and measurement point; use "fraction under threshold" (exact with a bucket at the threshold); derive per-hop budgets from the SLO and the fan-out (Deadlines).
Geography: multi-region, edge, read-local/write-global, DNS and anycast Must-know
In plain words: put the first hop (the edge) near the user, put data near where it is read, and let only the operations that must be globally consistent cross an ocean.
Common misunderstanding: "Multi-region makes everything faster." It makes reads faster if data is replicated locally; it makes consistent writes slower if every write needs a quorum across regions (one or more cross-region RTTs per commit). Multi-region is a latency trade, not a free upgrade.
Definition: edge: a point of presence (PoP) close to users that terminates TCP and TLS and serves cached content (CDN). Anycast: "Anycast is the name given to the practice of making a Service Address available to a routing system at Anycast Nodes in two or more discrete locations" (RFC 4786), so BGP routes each user to a nearby node. GeoDNS: the authoritative DNS answers with a region based on the resolver's location (IP, DNS & GeoDNS). Read-local, write-global: every region holds replicas for reads; each record has a home region (or a global consensus group) for writes. Multi-region active-active: each region serves its users' writes for the data it owns.
EU user, data homed in eu-central-1, app in both regions
1 DNS / anycast -> Frankfurt PoP (10 ms RTT); TLS ends at the PoP
2 PoP -> eu-central-1 app over warm connection (~5 ms)
3 read profile from local replica (1 ms) -> page in ~40 ms
4 same user travels to New York: anycast -> Virginia PoP -> us-east-1 app
5 reads: local replica of EU data (stale by replication lag, ~100s of ms)
6 write: forwarded to eu-central-1 primary (~85 ms RTT) -> write in ~110 ms
7 read-your-writes: route this user's reads to the home region for a few seconds after a writeReal scenario: a SaaS with EU data-residency rules (home region by tenant); a global game leaderboard (write-global with a consensus store, reads cached at the edge); a social feed (fan-out written in each region, eventual consistency); Spanner or CockroachDB multi-region tables (REGIONAL BY ROW, global tables with stale reads) where commits pay cross-region quorums.
What provides it:
| Need | Products |
|---|---|
| Edge termination and caching | Cloudflare, AWS CloudFront, Fastly, Akamai |
| Anycast entry into a backbone | Cloudflare, AWS Global Accelerator ("two static IPv4 addresses ... anycast from the AWS edge network"), Google Cloud global load balancer |
| GeoDNS / latency routing | AWS Route 53 latency-based and geolocation routing, NS1, Cloudflare load balancing |
| Read-local replicas | PostgreSQL read replicas, Aurora Global Database, DynamoDB global tables, Redis replicas |
| Write-global consistency | Spanner, CockroachDB, YugabyteDB, etcd/Consul (small data), single home-region primaries |
Fix / how to use it: decide the home of each data type (user, tenant, global); keep the synchronous path in one region; move cross-region work to async replication; pin users to their home region for writes; measure RTT from real users (RUM), not from your office.
Mechanics
Physics and budget arithmetic
| Quantity | Formula | Example |
|---|---|---|
| Propagation delay (one way) | distance × 5 µs/km in fibre | 6,550 km → 33 ms |
| RTT floor | 2 × distance × 5 µs/km | Frankfurt–Virginia 65 ms |
| Transmission delay | size / bandwidth | 1 MB at 100 Mbit/s → 80 ms |
| Cold HTTPS request (TCP + TLS 1.3) | 3 RTT + server time | 3 × 90 + 50 = 320 ms |
| Warm keep-alive request | 1 RTT + server time | 90 + 50 = 140 ms |
| Sequential chain | sum of hop latencies | 4 × 50 = 200 ms |
| Parallel fan-out | max of leaf latencies | dominated by the slowest leaf |
| Per-hop timeout | min(callee p99.9, remaining − margin) | min(120, 300 − 60) = 120 ms |
Fan-out and percentile arithmetic
| Question | Formula | Example |
|---|---|---|
| P(request slow), N independent leaves | 1 − (1 − p)^N | p = 0.01, N = 100 → 0.634 |
| Leaf quantile needed for end-to-end q | q^(1/N) | q = 0.99, N = 100 → 0.9999 |
| Users who see at least one slow page per session of k pages | 1 − (1 − p_page)^k | p_page = 0.01, k = 20 → 18% |
| Extra load of hedging at delay d | P(latency > d) per hedge level | hedge at p95 → about 5% |
| Benefit of one hedge | P(both slow) ≈ p² if independent | 0.01 → 0.0001 |
Queueing formulas (M/M/1 intuition)
| Quantity | Formula | Note |
|---|---|---|
| Utilisation | ρ = λ/μ | Must be under 1 for stability |
| Little's law | L = λW | Any stable system, any distribution |
| Mean response time | W = 1/(μ − λ) = S/(1 − ρ) | S = 1/μ service time |
| Mean queueing delay | ρ/(μ − λ) = W − S | Waiting before service |
| p99 response time | ln(100) × W ≈ 4.6 W | M/M/1 response time is exponential |
| Pool size from Little | workers ≥ λ × W | 200 req/s × 0.05 s = 10 busy workers, size for 15 to 20 |
Handshake costs
| Setup | RTTs before the first request byte arrives | Source |
|---|---|---|
| TCP + TLS 1.2 (full) | 3 | RFC 9293 + RFC 5246 Figure 1 |
| TCP + TLS 1.3 (full) | 2 | RFC 8446 |
| TCP + TLS 1.3 with 0-RTT early data | 1 (data rides with ClientHello) | RFC 8446; replayable |
| TCP Fast Open + TLS 1.3 0-RTT | 0 extra for data in SYN (rare in practice) | RFC 7413 |
| QUIC / HTTP/3 (new) | 1 | RFC 9000 |
| QUIC 0-RTT (resumed) | 0 | RFC 9000; replayable |
| Reused keep-alive / HTTP/2 connection | 0 | Connection pooling |
Histogram precision
| Histogram | Setting | Worst-case relative error |
|---|---|---|
| HdrHistogram | 3 significant digits | 0.1% |
| HdrHistogram | 2 significant digits | 1% |
| OTel exponential | scale 3 (base 1.0905) | about 9% bucket width |
| OTel exponential | scale 8 (base 1.0027) | about 0.27% |
| Prometheus native | NativeHistogramBucketFactor 1.1 | about 10% bucket width |
| Prometheus classic | buckets 0.2, 0.3, 0.45 s | up to the bucket width (150 ms around 0.3 s) |
This page's Go hist | 3 digits, 1 µs to 1 h | 0.1%, fixed memory |
This page's Laravel LatencyHistogram | 8 buckets per power of 2 | under 9.1% |
Knobs that shape latency
| Product | Knob | Default | Latency meaning |
|---|---|---|---|
Go http.Client | Timeout | 0 (no timeout) | "includes connection time, any redirects, and reading the response body" |
Go http.Transport | ResponseHeaderTimeout | 0 | Server think time limit |
Go http.Transport | TLSHandshakeTimeout | 10 s in DefaultTransport | Cap the handshake RTTs |
Go http.Transport | MaxIdleConnsPerHost | 2 | Too low forces new handshakes |
| Go runtime | GOGC, GOMEMLIMIT | 100, no limit | GC frequency: fewer cycles, fewer assists |
| Laravel HTTP client | timeout() / connectTimeout() | 30 s / 10 s | Per-hop limits; float seconds allowed |
| Laravel HTTP client | retry(times, sleep, when, throw) | none | Retry only while the budget allows |
| Laravel HTTP client | Http::pool(..., concurrency: n) | unbounded | Parallel fan-out |
| Laravel Pulse | SlowRequests / SlowOutgoingRequests threshold | 1,000 ms | Align with the SLO threshold |
| gRPC | hedgingPolicy.hedgingDelay, maxAttempts (max 5) | off | Hedging (not in grpc-go) |
| Envoy | route timeout, per_try_timeout, hedge_policy | 15 s route timeout | Deadline and hedging in the mesh |
| Envoy | LEAST_REQUEST choice_count | 2 | Power of two choices |
| Finagle | idempotent(maxExtraLoad) | 0 = off | Backup requests |
| AWS Lambda | Provisioned Concurrency | 0 | Removes cold starts for that capacity |
| Prometheus | NativeHistogramBucketFactor | off (classic) | Exponential buckets |
| OpenTelemetry SDK | MaxSize, MaxScale | 160, 20 | Exponential histogram resolution |
Error messages you will actually see
| Where | Message | Meaning |
|---|---|---|
| Go | context deadline exceeded | The hop's budget ran out |
Go net/http | net/http: TLS handshake timeout | TLSHandshakeTimeout fired |
Go net/http | net/http: timeout awaiting response headers | ResponseHeaderTimeout fired |
| Go (this page) | budget: exhausted before the call started | The call was refused because it could not finish |
| Laravel | Illuminate\Http\Client\ConnectionException (cURL error 28) | timeout() or connectTimeout() exceeded |
| gRPC | DEADLINE_EXCEEDED | Deadline passed |
| Envoy | upstream request timeout (504) | Route timeout |
| Elasticsearch | "timed_out": true in a search response | Partial (good-enough) results |
| Prometheus | info annotation on reconciled NHCB layouts | Bucket layouts differed when aggregating |
Go
The module academy/latency-budget-tail-latency uses only the standard library plus golang.org/x/sync/errgroup. Every package has tests; cmd/tailsim prints the numbers used on this page.
Before
Sequential calls through http.DefaultClient (no timeout), no budget, and a mean as the only metric. The fifth page load has one slow backend; the mean hides it.
// Command before shows the latency design most first versions have:
// sequential calls, the default client with no timeout, no budget, and an
// average as the only latency number. It works on a quiet laptop and hides
// every tail problem the page describes.
package main
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"time"
)
// fetchAll calls every backend one after the other. Total latency is the SUM
// of the calls, and one slow backend delays the whole page.
func fetchAll(urls []string) ([]string, time.Duration, error) {
start := time.Now()
out := make([]string, 0, len(urls))
for _, u := range urls {
resp, err := http.Get(u) // http.DefaultClient: Timeout is zero, so it can wait forever
if err != nil {
return nil, 0, err
}
body, err := io.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
return nil, 0, err
}
out = append(out, string(body))
}
return out, time.Since(start), nil
}
// meanLatency is the only metric the first version exports. One request in a
// hundred can take a second and the mean barely moves.
func meanLatency(samples []time.Duration) time.Duration {
if len(samples) == 0 {
return 0
}
var sum time.Duration
for _, s := range samples {
sum += s
}
return sum / time.Duration(len(samples))
}
func main() {
fast := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(10 * time.Millisecond)
fmt.Fprint(w, "ok")
}))
defer fast.Close()
slow := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(300 * time.Millisecond) // a GC pause or a cold cache on one replica
fmt.Fprint(w, "ok")
}))
defer slow.Close()
var samples []time.Duration
for i := 0; i < 5; i++ {
urls := []string{fast.URL, fast.URL, fast.URL}
if i == 4 {
urls[1] = slow.URL
}
_, took, err := fetchAll(urls)
if err != nil {
fmt.Println("error:", err)
return
}
samples = append(samples, took)
}
fmt.Println("mean page latency:", meanLatency(samples).Round(time.Millisecond))
}After
Per-hop budgets. ForHop turns the request's deadline into a per-call timeout (min(cap, remaining − margin)), refuses doomed calls, and Stamp/FromRequest carry the remaining milliseconds across services.
// Package budget turns one end-to-end latency budget into per-hop timeouts.
//
// The edge decides how long the user will wait. Every hop gets "what is left,
// minus a safety margin, capped at what this dependency normally needs", and
// refuses to start work that cannot finish in time. The remaining time travels
// as a relative number of milliseconds (not a wall-clock timestamp, which
// would be wrong by the clock skew between hosts), as gRPC does with
// grpc-timeout.
package budget
import (
"context"
"errors"
"net/http"
"strconv"
"time"
)
// Header carries the remaining budget between services (a convention shared
// with /architecture/service-communication; gRPC uses grpc-timeout).
const Header = "Request-Timeout-Ms"
// ErrExhausted means the remaining budget cannot cover even the floor this
// hop needs, so the call is not worth starting.
var ErrExhausted = errors.New("budget: exhausted before the call started")
// Hop describes one downstream dependency.
type Hop struct {
Cap time.Duration // never wait longer than this (from the callee's p99.9)
Margin time.Duration // leave this much for the caller's own work and transit
Floor time.Duration // below this the call cannot succeed (callee's p50)
}
// ForHop derives the context for one outgoing call.
func ForHop(ctx context.Context, h Hop) (context.Context, context.CancelFunc, error) {
timeout := h.Cap
if dl, ok := ctx.Deadline(); ok {
left := time.Until(dl) - h.Margin
if left < timeout {
timeout = left
}
}
if timeout <= 0 || timeout < h.Floor {
return ctx, func() {}, ErrExhausted
}
c, cancel := context.WithTimeout(ctx, timeout)
return c, cancel, nil
}
// FromRequest applies an incoming budget header to the request context.
// Missing or malformed headers fall back to def.
func FromRequest(r *http.Request, def time.Duration) (context.Context, context.CancelFunc) {
d := def
if v := r.Header.Get(Header); v != "" {
if ms, err := strconv.ParseInt(v, 10, 64); err == nil && ms > 0 {
d = min(time.Duration(ms)*time.Millisecond, def)
}
}
return context.WithTimeout(r.Context(), d)
}
// Stamp writes the remaining budget of ctx on an outgoing request.
func Stamp(ctx context.Context, req *http.Request) {
if dl, ok := ctx.Deadline(); ok {
ms := time.Until(dl).Milliseconds()
if ms < 1 {
ms = 1
}
req.Header.Set(Header, strconv.FormatInt(ms, 10))
}
}package budget
import (
"context"
"errors"
"net/http/httptest"
"testing"
"time"
)
func TestHopGetsRemainingMinusMargin(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond)
defer cancel()
c, done, err := ForHop(ctx, Hop{Cap: time.Second, Margin: 20 * time.Millisecond, Floor: 5 * time.Millisecond})
defer done()
if err != nil {
t.Fatal(err)
}
dl, _ := c.Deadline()
left := time.Until(dl)
if left > 281*time.Millisecond || left < 250*time.Millisecond {
t.Fatalf("hop timeout %v, want about 280 ms", left)
}
}
func TestCapAppliesWhenBudgetIsLarge(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
c, done, _ := ForHop(ctx, Hop{Cap: 80 * time.Millisecond, Margin: 10 * time.Millisecond})
defer done()
dl, _ := c.Deadline()
if time.Until(dl) > 81*time.Millisecond {
t.Fatal("cap not applied")
}
}
func TestRefusesDoomedCall(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond)
defer cancel()
_, done, err := ForHop(ctx, Hop{Cap: time.Second, Margin: 10 * time.Millisecond, Floor: 40 * time.Millisecond})
defer done()
if !errors.Is(err, ErrExhausted) {
t.Fatalf("want ErrExhausted, got %v", err)
}
}
func TestHeaderRoundTrip(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
defer cancel()
out := httptest.NewRequest("GET", "http://svc.internal/x", nil)
Stamp(ctx, out)
if out.Header.Get(Header) == "" {
t.Fatal("header not stamped")
}
in := httptest.NewRequest("GET", "http://svc.internal/x", nil)
in.Header.Set(Header, "120")
c, done := FromRequest(in, time.Second)
defer done()
dl, _ := c.Deadline()
if time.Until(dl) > 121*time.Millisecond {
t.Fatal("incoming budget not applied")
}
}Hedged requests with a load budget. Do sends the primary, hedges after Delay (about p95), retries immediately on a fast failure, cancels the losers, and stops hedging when the token bucket (5% of primaries) is empty.
// Package hedge implements hedged (backup) requests as described by Dean and
// Barroso in "The Tail at Scale": send the request to one replica, and if it
// has not answered after a delay (typically the p95 latency of this request
// class), send a copy to another replica, use whichever answers first and
// cancel the rest.
//
// Use it only for idempotent reads. A Budget caps the extra load, the way
// Finagle's maxExtraLoad or gRPC's retry throttling do.
package hedge
import (
"context"
"errors"
"sync"
"time"
)
// Func performs one attempt. attempt is 0 for the primary, 1.. for hedges;
// use it to pick a different replica. It must return promptly when ctx is
// cancelled, otherwise cancelled losers keep consuming server capacity.
type Func[T any] func(ctx context.Context, attempt int) (T, error)
// Policy configures hedging for one request class.
type Policy struct {
Delay time.Duration // wait this long before each hedge (about p95)
MaxAttempts int // primary + hedges; gRPC caps hedging at 5
Budget *Budget // nil means unlimited (not recommended)
}
// Result reports what happened.
type Result struct {
Attempts int // attempts started
Winner int // attempt index that answered first, -1 on failure
}
// ErrAllFailed wraps the last error when every attempt failed.
var ErrAllFailed = errors.New("hedge: all attempts failed")
type outcome[T any] struct {
v T
err error
attempt int
}
// Do runs fn with hedging and returns the first successful answer.
func Do[T any](ctx context.Context, p Policy, fn Func[T]) (T, Result, error) {
var zero T
if p.MaxAttempts < 1 {
p.MaxAttempts = 1
}
ctx, cancel := context.WithCancel(ctx)
defer cancel() // cancels every loser once we return
results := make(chan outcome[T], p.MaxAttempts)
started, pending := 0, 0
launch := func() {
attempt := started
started++
pending++
go func() {
v, err := fn(ctx, attempt)
results <- outcome[T]{v: v, err: err, attempt: attempt}
}()
}
p.Budget.primary()
launch()
timer := time.NewTimer(p.Delay)
defer timer.Stop()
var lastErr error
for {
select {
case <-ctx.Done():
return zero, Result{Attempts: started, Winner: -1}, ctx.Err()
case <-timer.C:
// The current attempts are slower than Delay: hedge if allowed.
if started < p.MaxAttempts && p.Budget.allowHedge() {
launch()
timer.Reset(p.Delay)
}
case o := <-results:
pending--
if o.err == nil {
return o.v, Result{Attempts: started, Winner: o.attempt}, nil
}
lastErr = o.err
// A fast failure is not slowness: try the next replica now.
if started < p.MaxAttempts && p.Budget.allowHedge() {
launch()
if !timer.Stop() {
select {
case <-timer.C:
default:
}
}
timer.Reset(p.Delay)
continue
}
if pending == 0 {
return zero, Result{Attempts: started, Winner: -1}, errors.Join(ErrAllFailed, lastErr)
}
}
}
}
// Budget limits hedges to a fraction of primary requests with a token
// bucket: every primary adds Ratio tokens (up to Max), every hedge costs one.
// Ratio 0.05 keeps extra load near 5%, the figure Dean and Barroso give for
// hedging at the p95 delay.
type Budget struct {
mu sync.Mutex
Ratio float64
Max float64
tokens float64
}
// NewBudget returns a budget that starts full.
func NewBudget(ratio, maxTokens float64) *Budget {
return &Budget{Ratio: ratio, Max: maxTokens, tokens: maxTokens}
}
func (b *Budget) primary() {
if b == nil {
return
}
b.mu.Lock()
b.tokens = min(b.Max, b.tokens+b.Ratio)
b.mu.Unlock()
}
func (b *Budget) allowHedge() bool {
if b == nil {
return true
}
b.mu.Lock()
defer b.mu.Unlock()
if b.tokens < 1 {
return false
}
b.tokens--
return true
}package hedge
import (
"context"
"errors"
"sync/atomic"
"testing"
"time"
)
// replica returns a Func whose attempt i sleeps delays[i] (honouring ctx).
func replica(delays []time.Duration, cancelled *atomic.Int32) Func[string] {
return func(ctx context.Context, attempt int) (string, error) {
select {
case <-time.After(delays[attempt]):
return []string{"a", "b", "c"}[attempt], nil
case <-ctx.Done():
cancelled.Add(1)
return "", ctx.Err()
}
}
}
func TestFastPrimaryNeverHedges(t *testing.T) {
var c atomic.Int32
v, r, err := Do(context.Background(), Policy{Delay: 50 * time.Millisecond, MaxAttempts: 2},
replica([]time.Duration{time.Millisecond, time.Millisecond}, &c))
if err != nil || v != "a" || r.Attempts != 1 || r.Winner != 0 {
t.Fatalf("got %q %+v %v, want primary only", v, r, err)
}
}
func TestSlowPrimaryIsHedgedAndCancelled(t *testing.T) {
var c atomic.Int32
start := time.Now()
v, r, err := Do(context.Background(), Policy{Delay: 20 * time.Millisecond, MaxAttempts: 2},
replica([]time.Duration{2 * time.Second, 5 * time.Millisecond}, &c))
took := time.Since(start)
if err != nil || v != "b" || r.Winner != 1 || r.Attempts != 2 {
t.Fatalf("got %q %+v %v, want hedge to win", v, r, err)
}
if took > 500*time.Millisecond {
t.Fatalf("took %v: hedge should cut the 2 s tail to about 25 ms", took)
}
deadline := time.Now().Add(time.Second)
for c.Load() == 0 && time.Now().Before(deadline) {
time.Sleep(time.Millisecond)
}
if c.Load() != 1 {
t.Fatal("the losing primary was not cancelled")
}
}
func TestEmptyBudgetDisablesHedging(t *testing.T) {
var c atomic.Int32
b := NewBudget(0.05, 1)
b.tokens = 0 // spent by earlier requests
_, r, err := Do(context.Background(), Policy{Delay: 5 * time.Millisecond, MaxAttempts: 2, Budget: b},
replica([]time.Duration{40 * time.Millisecond, time.Millisecond}, &c))
if err != nil || r.Attempts != 1 || r.Winner != 0 {
t.Fatalf("got %+v %v, want no hedge when the budget is empty", r, err)
}
}
func TestBudgetRefillsAtRatio(t *testing.T) {
b := NewBudget(0.05, 2)
b.tokens = 0
for i := 0; i < 20; i++ {
b.primary()
}
if !b.allowHedge() || b.allowHedge() {
t.Fatal("20 primaries at ratio 0.05 should earn exactly one hedge")
}
}
func TestAllFail(t *testing.T) {
boom := errors.New("boom")
_, r, err := Do(context.Background(), Policy{Delay: time.Second, MaxAttempts: 3},
func(ctx context.Context, attempt int) (int, error) { return 0, boom })
if !errors.Is(err, ErrAllFailed) || !errors.Is(err, boom) || r.Attempts != 3 {
t.Fatalf("got %+v %v", r, err)
}
}
func TestDeadlineWins(t *testing.T) {
var c atomic.Int32
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond)
defer cancel()
_, _, err := Do(ctx, Policy{Delay: 10 * time.Millisecond, MaxAttempts: 2},
replica([]time.Duration{time.Second, time.Second}, &c))
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("want DeadlineExceeded, got %v", err)
}
}A runnable example against two httptest replicas (replica A is in a pause; the hedge to B wins and A's handler sees its context cancelled):
package hedge_test
import (
"context"
"fmt"
"io"
"net/http"
"net/http/httptest"
"time"
"academy/latency-budget-tail-latency/hedge"
)
// Two replicas of the same read-only endpoint; replica A is in a long pause.
func Example() {
slowA := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
select {
case <-time.After(2 * time.Second):
case <-r.Context().Done(): // the hedge won; stop working
return
}
fmt.Fprint(w, "replica-a")
}))
defer slowA.Close()
fastB := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "replica-b")
}))
defer fastB.Close()
replicas := []string{slowA.URL, fastB.URL}
client := &http.Client{Timeout: time.Second}
get := func(ctx context.Context, attempt int) (string, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, replicas[attempt]+"/profile/42", nil)
if err != nil {
return "", err
}
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
b, err := io.ReadAll(resp.Body)
return string(b), err
}
ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond)
defer cancel()
body, res, err := hedge.Do(ctx, hedge.Policy{Delay: 20 * time.Millisecond, MaxAttempts: 2, Budget: hedge.NewBudget(0.05, 10)}, get)
fmt.Println(body, res.Winner, res.Attempts, err)
// Output: replica-b 1 2 <nil>
}HdrHistogram-style percentiles. Log-linear buckets with 3 significant digits, fixed memory, exact merge, and RecordCorrected for coordinated omission.
// Package hist is a small HdrHistogram-style log-linear histogram for
// latency values (any integer unit; this page records microseconds).
//
// Like HdrHistogram it keeps a fixed number of significant decimal digits
// across the whole range: values below the sub-bucket count are stored
// exactly, larger values share a bucket only with neighbours that differ in
// digits beyond the configured precision. Recording is O(1) with no
// allocation, and two histograms with the same configuration merge exactly,
// which is what makes percentiles aggregatable across hosts.
package hist
import (
"errors"
"math"
"math/bits"
)
// ErrOutOfRange is returned when a value is negative or above the maximum
// trackable value chosen at construction time.
var ErrOutOfRange = errors.New("hist: value out of range")
// ErrIncompatible is returned by Merge when configurations differ.
var ErrIncompatible = errors.New("hist: incompatible histograms")
// Histogram counts values in log-linear buckets.
type Histogram struct {
maxValue int64
sigDigits int
subBits uint // log2(subBucketCount)
subCount int64
subHalf int64
counts []int64
total int64
min, max, sum int64
}
// New creates a histogram that tracks values in [0, maxValue] with
// sigDigits significant decimal digits (1 to 5).
func New(maxValue int64, sigDigits int) (*Histogram, error) {
if sigDigits < 1 || sigDigits > 5 || maxValue < 1 {
return nil, errors.New("hist: sigDigits must be 1..5 and maxValue >= 1")
}
// Enough linear sub-buckets to separate 2 * 10^d values exactly.
largest := 2 * int64(math.Pow10(sigDigits))
subBits := uint(bits.Len64(uint64(largest - 1)))
h := &Histogram{
maxValue: maxValue,
sigDigits: sigDigits,
subBits: subBits,
subCount: 1 << subBits,
subHalf: 1 << (subBits - 1),
min: math.MaxInt64,
}
h.counts = make([]int64, h.index(maxValue)+1)
return h, nil
}
// index maps a value to its bucket.
func (h *Histogram) index(v int64) int {
if v < h.subCount {
return int(v)
}
shift := uint(bits.Len64(uint64(v))) - h.subBits
sub := v >> shift // in [subHalf, subCount)
return int(h.subCount + int64(shift-1)*h.subHalf + (sub - h.subHalf))
}
// highest returns the largest value that maps to bucket i (what HdrHistogram
// calls the highest equivalent value).
func (h *Histogram) highest(i int) int64 {
if int64(i) < h.subCount {
return int64(i)
}
rel := int64(i) - h.subCount
shift := uint(rel/h.subHalf) + 1
sub := h.subHalf + rel%h.subHalf
return ((sub + 1) << shift) - 1
}
// Record counts one value.
func (h *Histogram) Record(v int64) error {
return h.RecordN(v, 1)
}
// RecordN counts the same value n times.
func (h *Histogram) RecordN(v, n int64) error {
if v < 0 || v > h.maxValue {
return ErrOutOfRange
}
h.counts[h.index(v)] += n
h.total += n
h.sum += v * n
if v < h.min {
h.min = v
}
if v > h.max {
h.max = v
}
return nil
}
// RecordCorrected records v and, when v is larger than the expected interval
// between requests, also records the samples a stalled load generator never
// sent: v-interval, v-2*interval, ... down to interval. It mirrors
// HdrHistogram's recordValueWithExpectedInterval and corrects coordinated
// omission after the fact. Prefer measuring from the intended start time
// (as wrk2 does); use this when you cannot.
func (h *Histogram) RecordCorrected(v, expectedInterval int64) error {
if err := h.Record(v); err != nil {
return err
}
if expectedInterval <= 0 {
return nil
}
for missing := v - expectedInterval; missing >= expectedInterval; missing -= expectedInterval {
if err := h.Record(missing); err != nil {
return err
}
}
return nil
}
// ValueAtPercentile returns the value at percentile p (0..100), reported as
// the highest value equivalent to the bucket that holds it.
func (h *Histogram) ValueAtPercentile(p float64) int64 {
if h.total == 0 {
return 0
}
if p > 100 {
p = 100
}
target := int64(math.Ceil(p / 100 * float64(h.total)))
if target < 1 {
target = 1
}
var seen int64
for i, c := range h.counts {
seen += c
if seen >= target {
v := h.highest(i)
if v > h.max {
v = h.max
}
return v
}
}
return h.max
}
// Merge adds every count of o into h. Both must share maxValue and digits.
func (h *Histogram) Merge(o *Histogram) error {
if o.maxValue != h.maxValue || o.sigDigits != h.sigDigits {
return ErrIncompatible
}
for i, c := range o.counts {
h.counts[i] += c
}
h.total += o.total
h.sum += o.sum
if o.total > 0 {
h.min = min(h.min, o.min)
h.max = max(h.max, o.max)
}
return nil
}
// TotalCount returns the number of recorded values.
func (h *Histogram) TotalCount() int64 { return h.total }
// Mean returns the arithmetic mean (exact, from the running sum).
func (h *Histogram) Mean() float64 {
if h.total == 0 {
return 0
}
return float64(h.sum) / float64(h.total)
}
// Max returns the largest recorded value.
func (h *Histogram) Max() int64 { return h.max }
// Buckets returns the number of buckets allocated; memory is fixed by range
// and precision, not by the number of samples.
func (h *Histogram) Buckets() int { return len(h.counts) }package hist
import (
"math"
"testing"
)
func TestPercentilesWithinPrecision(t *testing.T) {
h, err := New(3_600_000_000, 3) // 1 us .. 1 h in microseconds, 3 digits
if err != nil {
t.Fatal(err)
}
for v := int64(1); v <= 1_000_000; v++ {
if err := h.Record(v); err != nil {
t.Fatal(err)
}
}
for _, tc := range []struct {
p float64
want int64
}{{50, 500_000}, {90, 900_000}, {99, 990_000}, {99.9, 999_000}, {100, 1_000_000}} {
got := h.ValueAtPercentile(tc.p)
relErr := math.Abs(float64(got-tc.want)) / float64(tc.want)
if relErr > 0.001 {
t.Errorf("p%v = %d, want %d within 0.1%% (error %.5f)", tc.p, got, tc.want, relErr)
}
}
if h.Buckets() > 40_000 {
t.Errorf("bucket count %d: memory should depend on range and digits only", h.Buckets())
}
}
func TestMeanHidesTail(t *testing.T) {
h, _ := New(10_000_000, 3)
for i := 0; i < 990; i++ {
_ = h.Record(10_000) // 10 ms
}
for i := 0; i < 10; i++ {
_ = h.Record(1_000_000) // 1 s
}
if m := h.Mean(); m > 20_000 {
t.Fatalf("mean %.0f us: expected about 19.9 ms", m)
}
if p := h.ValueAtPercentile(99.5); p < 990_000 {
t.Fatalf("p99.5 = %d, the 1 s tail must show", p)
}
}
func TestMergeEqualsCombinedRecording(t *testing.T) {
a, _ := New(1_000_000, 2)
b, _ := New(1_000_000, 2)
all, _ := New(1_000_000, 2)
for v := int64(1); v < 5000; v++ {
_ = a.Record(v)
_ = all.Record(v)
_ = b.Record(v * 100)
_ = all.Record(v * 100)
}
if err := a.Merge(b); err != nil {
t.Fatal(err)
}
for _, p := range []float64{50, 90, 99, 99.9} {
if a.ValueAtPercentile(p) != all.ValueAtPercentile(p) {
t.Fatalf("p%v differs after merge", p)
}
}
c, _ := New(1_000_000, 3)
if err := a.Merge(c); err != ErrIncompatible {
t.Fatalf("want ErrIncompatible, got %v", err)
}
}
func TestRecordCorrectedAddsMissingSamples(t *testing.T) {
h, _ := New(10_000_000, 3)
// One 1 s stall while the generator meant to send every 10 ms.
if err := h.RecordCorrected(1_000_000, 10_000); err != nil {
t.Fatal(err)
}
if got := h.TotalCount(); got != 100 {
t.Fatalf("count = %d, want 100 (1 measured + 99 that were never sent)", got)
}
}
func TestOutOfRange(t *testing.T) {
h, _ := New(1000, 2)
if err := h.Record(1001); err != ErrOutOfRange {
t.Fatalf("want ErrOutOfRange, got %v", err)
}
if err := h.Record(-1); err != ErrOutOfRange {
t.Fatalf("want ErrOutOfRange, got %v", err)
}
}Fan-out arithmetic and a good-enough gather. The tests assert the paper's 63% and 18%.
// Package fanout holds the arithmetic and a scatter-gather helper for
// requests that wait on many backends.
package fanout
import (
"context"
"errors"
"math"
"sync"
"time"
"golang.org/x/sync/errgroup"
)
// PAtLeastOneSlow is the probability that a request fanning out to n
// independent backends sees at least one slow answer, when each backend is
// slow with probability p: 1 - (1-p)^n. With p = 0.01 and n = 100 it is 0.634,
// the 63% in "The Tail at Scale".
func PAtLeastOneSlow(p float64, n int) float64 {
return 1 - math.Pow(1-p, float64(n))
}
// LeafQuantileFor returns the per-backend quantile you need so that a
// fan-out of n meets an end-to-end quantile q: q^(1/n). For q = 0.99 and
// n = 100, every leaf must meet its p99.99.
func LeafQuantileFor(q float64, n int) float64 {
return math.Pow(q, 1/float64(n))
}
// Leaf queries one backend. It must honour ctx.
type Leaf[T any] func(ctx context.Context) (T, error)
// Result of a gather.
type Result[T any] struct {
Values []T // answers in leaf order; missing ones are the zero value
Answered []bool
Count int // number of leaves that answered in time
Partial bool // true when some leaves were dropped (good-enough result)
}
// ErrNotEnough means fewer than the required fraction answered in time.
var ErrNotEnough = errors.New("fanout: not enough leaves answered within the budget")
// Gather calls every leaf with at most limit in flight, waits at most budget,
// and returns what arrived if at least minFraction of the leaves answered.
// Leaf errors are counted as missing answers, not as a reason to cancel the
// others: a good-enough answer beats a perfect one that arrives late.
func Gather[T any](ctx context.Context, leaves []Leaf[T], limit int, budget time.Duration, minFraction float64) (Result[T], error) {
ctx, cancel := context.WithTimeout(ctx, budget)
defer cancel()
res := Result[T]{Values: make([]T, len(leaves)), Answered: make([]bool, len(leaves))}
var mu sync.Mutex
var g errgroup.Group
if limit > 0 {
g.SetLimit(limit)
}
for i, leaf := range leaves {
g.Go(func() error {
v, err := leaf(ctx)
if err != nil || ctx.Err() != nil {
return nil // dropped leaf; never cancel siblings
}
mu.Lock()
res.Values[i], res.Answered[i] = v, true
res.Count++
mu.Unlock()
return nil
})
}
_ = g.Wait()
res.Partial = res.Count < len(leaves)
if float64(res.Count) < minFraction*float64(len(leaves)) {
return res, ErrNotEnough
}
return res, nil
}package fanout
import (
"context"
"errors"
"math"
"testing"
"time"
)
func TestPaperNumbers(t *testing.T) {
// "63% of user requests will take more than one second"
if got := PAtLeastOneSlow(0.01, 100); math.Abs(got-0.634) > 0.001 {
t.Fatalf("1 in 100, 100 servers: %.3f", got)
}
// "almost one in five user requests" with 1 in 10,000 and 2,000 servers
if got := PAtLeastOneSlow(0.0001, 2000); math.Abs(got-0.181) > 0.001 {
t.Fatalf("1 in 10,000, 2,000 servers: %.3f", got)
}
if got := LeafQuantileFor(0.99, 100); math.Abs(got-0.9999) > 0.00001 {
t.Fatalf("leaf quantile for p99 over 100 leaves: %.6f", got)
}
}
func sleepy(d time.Duration, v int) Leaf[int] {
return func(ctx context.Context) (int, error) {
select {
case <-time.After(d):
return v, nil
case <-ctx.Done():
return 0, ctx.Err()
}
}
}
func TestGoodEnoughResult(t *testing.T) {
leaves := make([]Leaf[int], 10)
for i := range leaves {
leaves[i] = sleepy(2*time.Millisecond, i)
}
leaves[7] = sleepy(5*time.Second, 7) // one leaf in a GC pause
start := time.Now()
res, err := Gather(context.Background(), leaves, 4, 100*time.Millisecond, 0.9)
if err != nil {
t.Fatal(err)
}
if !res.Partial || res.Count != 9 || res.Answered[7] {
t.Fatalf("got %+v, want 9 of 10 and a partial flag", res)
}
if time.Since(start) > time.Second {
t.Fatal("gather did not respect its budget")
}
}
func TestNotEnough(t *testing.T) {
leaves := []Leaf[int]{sleepy(time.Millisecond, 1), sleepy(time.Second, 2)}
_, err := Gather(context.Background(), leaves, 0, 30*time.Millisecond, 1.0)
if !errors.Is(err, ErrNotEnough) {
t.Fatalf("want ErrNotEnough, got %v", err)
}
}Where the time of one request goes. A tuned Transport and an httptrace recorder; the test shows a cold TLS connection paying connect + handshake and the next request reusing it for free.
// Package client builds an HTTP client whose every waiting phase has a
// limit, and measures where the time of one request goes (DNS, TCP connect,
// TLS handshake, time to first byte) with net/http/httptrace.
package client
import (
"context"
"crypto/tls"
"net"
"net/http"
"net/http/httptrace"
"sync"
"time"
)
// New returns a client for service-to-service calls. The whole-request limit
// comes from the caller's context (see package budget); the transport limits
// each phase and keeps connections warm so most calls skip the handshakes.
func New() *http.Client {
t := &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 500 * time.Millisecond, // TCP connect: about 1 RTT; in-region far below this
KeepAlive: 30 * time.Second,
}).DialContext,
TLSHandshakeTimeout: 500 * time.Millisecond, // TLS 1.3 full handshake is 1 RTT
ResponseHeaderTimeout: 2 * time.Second, // server think time
IdleConnTimeout: 90 * time.Second, // keep warm connections
MaxIdleConns: 200,
MaxIdleConnsPerHost: 50, // the default of 2 forces new handshakes under concurrency
ForceAttemptHTTP2: true,
TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS12},
}
// No client-wide Timeout: per-call deadlines come from the context so
// that one budget governs the whole chain.
return &http.Client{Transport: t}
}
// Timing is where the time of one request went.
type Timing struct {
DNS, Connect, TLS, TTFB time.Duration
Reused bool // a warm keep-alive connection was used
}
// Phases records Timing while the request runs (hooks may run concurrently).
type Phases struct {
mu sync.Mutex
t Timing
dns0, conn0, tls0, w time.Time
}
// Snapshot returns the timing; call it after the response body is read.
func (p *Phases) Snapshot() Timing {
p.mu.Lock()
defer p.mu.Unlock()
return p.t
}
// Trace attaches an httptrace.ClientTrace to ctx and returns the recorder.
func Trace(ctx context.Context) (context.Context, *Phases) {
p := &Phases{}
lock := func(f func()) { p.mu.Lock(); f(); p.mu.Unlock() }
tr := &httptrace.ClientTrace{
DNSStart: func(httptrace.DNSStartInfo) { lock(func() { p.dns0 = time.Now() }) },
DNSDone: func(httptrace.DNSDoneInfo) { lock(func() { p.t.DNS = time.Since(p.dns0) }) },
ConnectStart: func(string, string) { lock(func() { p.conn0 = time.Now() }) },
ConnectDone: func(string, string, error) { lock(func() { p.t.Connect = time.Since(p.conn0) }) },
TLSHandshakeStart: func() { lock(func() { p.tls0 = time.Now() }) },
TLSHandshakeDone: func(tls.ConnectionState, error) {
lock(func() { p.t.TLS = time.Since(p.tls0) })
},
GotConn: func(i httptrace.GotConnInfo) { lock(func() { p.t.Reused = i.Reused }) },
WroteRequest: func(httptrace.WroteRequestInfo) { lock(func() { p.w = time.Now() }) },
GotFirstResponseByte: func() { lock(func() { p.t.TTFB = time.Since(p.w) }) },
}
return httptrace.WithClientTrace(ctx, tr), p
}package client
import (
"context"
"io"
"net/http"
"net/http/httptest"
"testing"
"time"
)
// The first HTTPS request pays TCP + TLS; the second reuses the connection
// and pays neither. That is why connection reuse is a latency feature.
func TestReuseSkipsHandshakes(t *testing.T) {
srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = io.WriteString(w, "ok")
}))
defer srv.Close()
c := New()
tr := c.Transport.(*http.Transport)
tr.TLSClientConfig = srv.Client().Transport.(*http.Transport).TLSClientConfig // trust the test CA
get := func() Timing {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
ctx, ph := Trace(ctx)
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL, nil)
resp, err := c.Do(req)
if err != nil {
t.Fatal(err)
}
_, _ = io.Copy(io.Discard, resp.Body)
resp.Body.Close()
return ph.Snapshot()
}
first := get()
if first.Reused || first.TLS == 0 || first.Connect == 0 {
t.Fatalf("first request should open a new TLS connection: %+v", first)
}
second := get()
if !second.Reused || second.TLS != 0 || second.Connect != 0 {
t.Fatalf("second request should reuse the warm connection: %+v", second)
}
t.Logf("cold: connect=%v tls=%v ttfb=%v | warm: reused=%v ttfb=%v",
first.Connect, first.TLS, first.TTFB, second.Reused, second.TTFB)
}The simulation behind the page's tables (seeded; identical output on every run):
// Command tailsim reproduces the page's three numeric claims with a seeded,
// single-process simulation (no network, deterministic output):
//
// 1. fan-out amplifies a 1% leaf tail, and hedging at p95 cuts it;
// 2. queueing delay explodes past the utilisation knee (M/M/1 formulas);
// 3. a closed-loop load generator hides a stall (coordinated omission).
package main
import (
"fmt"
"math"
"math/rand/v2"
"academy/latency-budget-tail-latency/fanout"
"academy/latency-budget-tail-latency/hist"
)
const us = 1 // values are microseconds
const ms = 1000 * us // one millisecond
const maxV = 60 * 1e6 // track up to 60 s
func mustHist() *hist.Histogram {
h, err := hist.New(maxV, 3)
if err != nil {
panic(err)
}
return h
}
// leaf: 99% of calls take 5-15 ms, 1% take 1 s (a GC pause, a busy disk).
func leaf(r *rand.Rand) int64 {
if r.Float64() < 0.01 {
return 1000 * ms
}
return int64(5*ms + r.IntN(10*ms))
}
// hedged leaf: every `delay` without an answer sends one more copy to
// another replica (at most two hedges); the call ends when any copy answers.
func hedgedLeaf(r *rand.Rand, delay int64, hedges *int) int64 {
best := leaf(r)
for k := int64(1); k <= 2 && best > k*delay; k++ {
*hedges++
best = min(best, k*delay+leaf(r))
}
return best
}
func fanOutTable(r *rand.Rand) {
fmt.Println("1) Fan-out: leaf p99 = 1 s for 1% of calls; request waits for ALL leaves")
fmt.Println(" N P(>=1 slow) p50 p99 p99 hedged@15ms extra calls")
const requests = 20000
for _, n := range []int{1, 10, 100} {
plain, hedged := mustHist(), mustHist()
hedges := 0
for i := 0; i < requests; i++ {
var worst, worstH int64
for j := 0; j < n; j++ {
worst = max(worst, leaf(r))
worstH = max(worstH, hedgedLeaf(r, 15*ms, &hedges))
}
_ = plain.Record(worst)
_ = hedged.Record(worstH)
}
fmt.Printf(" %-4d %-12.3f %-8s %-8s %-16s %.1f%%\n", n, fanout.PAtLeastOneSlow(0.01, n),
fmtD(plain.ValueAtPercentile(50)), fmtD(plain.ValueAtPercentile(99)),
fmtD(hedged.ValueAtPercentile(99)), 100*float64(hedges)/float64(requests*n))
}
}
func queueingTable() {
fmt.Println("2) M/M/1 with service time S = 10 ms: W = S/(1-rho), p99 = ln(100)*W")
fmt.Println(" rho queueing delay mean W p99")
const s = 10.0
for _, rho := range []float64{0.5, 0.7, 0.8, 0.9, 0.95, 0.99} {
w := s / (1 - rho)
fmt.Printf(" %-5.2f %-15s %-9s %s\n", rho, fmt.Sprintf("%.0f ms", w-s),
fmt.Sprintf("%.0f ms", w), fmt.Sprintf("%.0f ms", math.Log(100)*w))
}
}
func coordinatedOmission() {
fmt.Println("3) Coordinated omission: 100 req/s for 100 s, server stalls 2 s at t=50 s")
const interval = 10 * ms // intended: one request every 10 ms
const service = 1 * ms
const stallAt, stallFor = 50_000 * ms, 2_000 * ms
naive, fromIntended, corrected := mustHist(), mustHist(), mustHist()
// Closed-loop generator: sends the next request only after the previous
// answer, and measures from the moment it actually sent it.
var now int64
for intended := int64(0); intended < 100_000*ms; intended += interval {
sent := max(now, intended)
done := sent + service
if sent >= stallAt && sent < stallAt+stallFor {
done = stallAt + stallFor + service // the stall holds this request
}
now = done
_ = naive.Record(done - sent)
_ = fromIntended.Record(done - intended) // what wrk2 does
_ = corrected.RecordCorrected(done-sent, interval)
}
row := func(name string, h *hist.Histogram) {
fmt.Printf(" %-26s n=%-6d p50=%-8s p99=%-8s p99.9=%-8s max=%s\n", name, h.TotalCount(),
fmtD(h.ValueAtPercentile(50)), fmtD(h.ValueAtPercentile(99)),
fmtD(h.ValueAtPercentile(99.9)), fmtD(h.Max()))
}
row("measured from send", naive)
row("measured from intended", fromIntended)
row("RecordCorrected (HdrHist)", corrected)
}
func fmtD(v int64) string {
switch {
case v >= 1000*ms:
return fmt.Sprintf("%.2fs", float64(v)/float64(1000*ms))
case v >= ms:
return fmt.Sprintf("%dms", v/ms)
default:
return fmt.Sprintf("%dus", v)
}
}
func main() {
r := rand.New(rand.NewPCG(2013, 2)) // seeded: identical output on every run
fanOutTable(r)
fmt.Println()
queueingTable()
fmt.Println()
coordinatedOmission()
}The Go angle
| Go feature | Use for latency | Note |
|---|---|---|
context.WithTimeout, ctx.Deadline() | Budgets and propagation | Pass ctx first; every blocking call should take it |
http.NewRequestWithContext | Cancel an in-flight call when the budget ends or a hedge wins | Without it, losers keep running |
http.Transport pool fields | Avoid handshakes (MaxIdleConnsPerHost, IdleConnTimeout) | DefaultMaxIdleConnsPerHost = 2 |
net/http/httptrace.ClientTrace | DNS, connect, TLS, first byte timings | "hooks to run at various stages of an outgoing HTTP request" |
golang.org/x/sync/errgroup | Bounded fan-out (SetLimit); WithContext cancels on first error | Use plain Group when one failure must not cancel the rest |
time.Timer, select | Hedge delays, per-leaf deadlines | Stop/drain timers before Reset |
runtime/debug.SetGCPercent, SetMemoryLimit | GC frequency | GC guide: "reducing GC frequency may also lead to latency improvements" |
runtime/trace, go tool trace | See GC assists, scheduler delay | GC guide: latency sources "are visible in execution traces" |
github.com/HdrHistogram/hdrhistogram-go | Production HdrHistogram | The hist package here is a teaching version |
github.com/prometheus/client_golang | Histogram with Buckets or NativeHistogramBucketFactor | Export, do not compute percentiles in-process |
Laravel
Before
Three sequential Http::get calls with the 30 s default timeout and a running mean stored in the cache.
<?php
namespace App\Http\Controllers\Before;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
/**
* The first version: three sequential calls with the default 30 s timeout,
* no budget, and an average as the only latency number.
*/
class DashboardControllerBefore
{
public function __invoke(): JsonResponse
{
$start = microtime(true);
// Sequential: page latency = sum of the three calls.
$profile = Http::get('http://profile.internal/users/42')->json();
$orders = Http::get('http://orders.internal/users/42/orders')->json();
$recs = Http::get('http://recs.internal/users/42')->json(); // optional, but it can stall the page
$ms = (microtime(true) - $start) * 1000;
// A running mean: one 5 s request in a hundred barely moves it.
$n = Cache::increment('dashboard:latency:n');
$mean = Cache::get('dashboard:latency:mean', 0.0);
Cache::forever('dashboard:latency:mean', $mean + ($ms - $mean) / $n);
return response()->json(compact('profile', 'orders', 'recs'));
}
}After
One budget per request, created by the middleware and shared by every client. hopTimeout() returns float seconds (Laravel's timeout() accepts them) or null when the call cannot finish.
<?php
namespace App\Support;
use Illuminate\Http\Request;
/**
* One end-to-end budget per incoming request, shared by every outgoing call.
* The RecordRequestLatency middleware binds a fresh instance per request
* (also under Octane, where the application object is reused).
*/
class LatencyBudget
{
public const HEADER = 'Request-Timeout-Ms';
private float $deadline;
public function __construct(float $budgetMs)
{
$this->deadline = hrtime(true) / 1e6 + $budgetMs;
}
/** Use the caller's remaining budget when it is smaller than ours. */
public static function fromRequest(Request $request, float $defaultMs): self
{
$incoming = (float) $request->header(self::HEADER, '0');
return new self($incoming > 0 ? min($incoming, $defaultMs) : $defaultMs);
}
public function remainingMs(): float
{
return max(0.0, $this->deadline - hrtime(true) / 1e6);
}
/**
* Timeout for one hop in seconds (Laravel's timeout() accepts a float):
* what is left minus a margin, capped at what this dependency needs.
* Returns null when the call cannot finish in time and should be skipped.
*/
public function hopTimeout(float $capMs, float $marginMs = 20, float $floorMs = 5): ?float
{
$ms = min($capMs, $this->remainingMs() - $marginMs);
return $ms >= $floorMs ? $ms / 1000 : null;
}
/** Header for the next hop: the remaining time, never a wall-clock time. */
public function outgoingHeaders(): array
{
return [self::HEADER => (string) max(1, (int) $this->remainingMs())];
}
}A per-hop client: connectTimeout(0.1), a timeout from the budget, and a retry() whose when callback retries only transient errors and only while the budget can pay for another attempt, updating the timeout and header before each retry.
<?php
namespace App\Clients;
use App\Support\LatencyBudget;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Http;
use Throwable;
/**
* A per-hop client: connect timeout about one in-region RTT plus slack,
* response timeout from the shared budget, and a retry only while the
* budget can still pay for another attempt.
*/
class ProfileClient
{
public function __construct(private LatencyBudget $budget)
{
}
public function find(int $userId): ?array
{
// Cap from the callee's p99.9 (AWS: pick the percentile that matches an
// acceptable false-timeout rate), not a round 30 s default.
$timeout = $this->budget->hopTimeout(capMs: 150);
if ($timeout === null) {
return null; // not worth starting; the caller degrades
}
$response = Http::baseUrl('http://profile.internal')
->connectTimeout(0.1)
->timeout($timeout)
->withHeaders($this->budget->outgoingHeaders())
->retry(
2,
fn (int $attempt) => random_int(0, 20 * $attempt), // small full-jitter pause
function (Throwable $e, PendingRequest $request): bool {
$transient = $e instanceof ConnectionException
|| ($e instanceof RequestException && $e->response->serverError());
$next = $this->budget->hopTimeout(capMs: 150);
if (! $transient || $next === null) {
return false; // out of budget: a retry would only add latency
}
$request->timeout($next)->withHeaders($this->budget->outgoingHeaders());
return true;
},
throw: false,
)
->get("/users/{$userId}");
return $response->successful() ? $response->json() : null;
}
}Parallel fan-out with a good-enough result. Http::pool(..., concurrency: 4); in a pool a timeout arrives as a ConnectionException instance, so optional parts are dropped instead of failing the page.
<?php
namespace App\Http\Controllers;
use App\Clients\ProfileClient;
use App\Support\LatencyBudget;
use Illuminate\Http\Client\Pool;
use Illuminate\Http\Client\Response;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Http;
/**
* Parallel fan-out under one budget. Required parts fail the page; optional
* parts are dropped when late (a good-enough result, as in "The Tail at Scale").
*/
class DashboardController
{
public function __invoke(LatencyBudget $budget, ProfileClient $profiles): JsonResponse
{
$profile = $profiles->find(42);
if ($profile === null) {
return response()->json(['error' => 'profile unavailable'], 503);
}
$ordersTimeout = $budget->hopTimeout(capMs: 120) ?? 0.005;
$recsTimeout = $budget->hopTimeout(capMs: 60) ?? 0.005; // optional: short leash
// Parallel: page latency = max of the calls, not the sum.
$responses = Http::pool(fn (Pool $pool) => [
$pool->as('orders')->connectTimeout(0.1)->timeout($ordersTimeout)
->withHeaders($budget->outgoingHeaders())
->get('http://orders.internal/users/42/orders'),
$pool->as('recs')->connectTimeout(0.1)->timeout($recsTimeout)
->withHeaders($budget->outgoingHeaders())
->get('http://recs.internal/users/42'),
], concurrency: 4);
// In a pool a timeout is a ConnectionException instance, not a throw.
$ok = fn (string $k) => $responses[$k] instanceof Response && $responses[$k]->successful();
if (! $ok('orders')) {
return response()->json(['error' => 'orders unavailable'], 503);
}
return response()->json([
'profile' => $profile,
'orders' => $responses['orders']->json(),
'recs' => $ok('recs') ? $responses['recs']->json() : [], // good enough without it
'partial' => ! $ok('recs'),
]);
}
}Percentiles in Redis. A log-linear histogram (8 buckets per power of two, like an OpenTelemetry exponential histogram at scale 3), one hash per route per minute, merged for any window.
<?php
namespace App\Support;
use Illuminate\Support\Facades\Redis;
/**
* Log-linear latency histogram stored in Redis: one hash per route per
* minute, field = bucket index, value = count. Buckets grow by about 2^(1/8)
* (9% wide, like an OpenTelemetry exponential histogram at scale 3), so
* merging minutes or servers is exact and percentiles can be computed for
* any window later. Averages of per-server percentiles are never needed.
*/
class LatencyHistogram
{
public const SCALE = 3; // 2^3 = 8 buckets per power of two
public const TTL_SECONDS = 86400; // keep one day of minutes
/** Bucket index for a latency in microseconds (index i covers (base^(i-1), base^i]). */
public static function bucketFor(float $micros): int
{
if ($micros <= 1) {
return 0;
}
return (int) ceil(log($micros, 2) * (1 << self::SCALE));
}
/** Upper bound of a bucket in microseconds. */
public static function upperBound(int $bucket): float
{
return 2 ** ($bucket / (1 << self::SCALE));
}
public static function key(string $route, int $minute): string
{
return "latency:{$route}:{$minute}";
}
public function record(string $route, float $micros, ?int $now = null): void
{
$key = self::key($route, intdiv($now ?? time(), 60));
$bucket = self::bucketFor($micros);
// The Redis facade passes unknown methods straight to Redis (HINCRBY, EXPIRE).
Redis::pipeline(function ($pipe) use ($key, $bucket) {
$pipe->hincrby($key, (string) $bucket, 1);
$pipe->expire($key, self::TTL_SECONDS);
});
}
/** Merge the last $minutes minutes of a route into one bucket => count map. */
public function window(string $route, int $minutes, ?int $now = null): array
{
$end = intdiv($now ?? time(), 60);
$merged = [];
for ($m = $end - $minutes + 1; $m <= $end; $m++) {
foreach (Redis::hgetall(self::key($route, $m)) ?: [] as $bucket => $count) {
$merged[(int) $bucket] = ($merged[(int) $bucket] ?? 0) + (int) $count;
}
}
ksort($merged);
return $merged;
}
/**
* Percentile from merged buckets, reported as the bucket's upper bound,
* so the error is at most one bucket width (about 9%).
*
* @param array<int,int> $buckets
*/
public static function percentile(array $buckets, float $p): ?float
{
$total = array_sum($buckets);
if ($total === 0) {
return null;
}
$target = max(1, (int) ceil($p / 100 * $total));
$seen = 0;
foreach ($buckets as $bucket => $count) {
$seen += $count;
if ($seen >= $target) {
return self::upperBound($bucket);
}
}
return self::upperBound(array_key_last($buckets));
}
}Terminable middleware records after the response is sent, into the histogram and into Pulse (Pulse::record(...)->max()->avg()->count()):
<?php
namespace App\Http\Middleware;
use App\Support\LatencyBudget;
use App\Support\LatencyHistogram;
use Closure;
use Illuminate\Http\Request;
use Laravel\Pulse\Facades\Pulse;
use Symfony\Component\HttpFoundation\Response;
/**
* Starts the request's latency budget and records the server-side latency
* of every request into a Redis histogram and a Pulse aggregate. Recording
* happens in terminate(), after the response was sent (under FastCGI), so it
* adds nothing to the latency it measures.
*
* Laravel resolves a fresh middleware instance for terminate(), so the start
* time travels on the request, not on $this.
*/
class RecordRequestLatency
{
public function __construct(private LatencyHistogram $histogram)
{
}
public function handle(Request $request, Closure $next, string $budgetMs = '800'): Response
{
$request->attributes->set('latency.start', hrtime(true));
// Bound per request (also correct under Octane, which reuses the app).
app()->instance(LatencyBudget::class, LatencyBudget::fromRequest($request, (float) $budgetMs));
return $next($request);
}
public function terminate(Request $request, Response $response): void
{
$start = $request->attributes->get('latency.start');
if ($start === null) {
return;
}
$micros = (hrtime(true) - $start) / 1000;
$route = $request->route()?->getName() ?? 'unnamed';
$this->histogram->record($route, $micros);
// Pulse aggregates are avg/count/max/min/sum: good for a dashboard
// card, but not percentiles. The histogram above is the SLO source.
Pulse::record('route_latency', $route, (int) ($micros / 1000))->max()->avg()->count();
}
}<?php
use App\Http\Middleware\RecordRequestLatency;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware): void {
// Routes pass their end-to-end budget in milliseconds:
// Route::get('/dashboard', DashboardController::class)->middleware('latency:800');
$middleware->alias(['latency' => RecordRequestLatency::class]);
})
->withExceptions(function (Exceptions $exceptions): void {
//
})->create();A report command that prints p50/p90/p99/p99.9 and the share of requests within the SLO:
<?php
namespace App\Console\Commands;
use App\Support\LatencyHistogram;
use Illuminate\Console\Command;
class LatencyReport extends Command
{
protected $signature = 'latency:report {route} {--minutes=5} {--slo-ms=300}';
protected $description = 'Print p50/p90/p99/p99.9 and the share of requests within the latency SLO';
public function handle(LatencyHistogram $histogram): int
{
$buckets = $histogram->window($this->argument('route'), (int) $this->option('minutes'));
$total = array_sum($buckets);
if ($total === 0) {
$this->warn('no samples');
return self::SUCCESS;
}
$sloMicros = (float) $this->option('slo-ms') * 1000;
$good = 0;
foreach ($buckets as $bucket => $count) {
if (LatencyHistogram::upperBound($bucket) <= $sloMicros) {
$good += $count; // conservative: a bucket counts only if fully inside
}
}
$row = fn (float $p) => [
"p{$p}",
number_format(LatencyHistogram::percentile($buckets, $p) / 1000, 1).' ms',
];
$this->table(['percentile', 'latency'], [$row(50), $row(90), $row(99), $row(99.9)]);
$this->info(sprintf('%d requests, %.3f%% within %s ms', $total, 100 * $good / $total, $this->option('slo-ms')));
return self::SUCCESS;
}
}Pulse thresholds aligned with the SLO (the default is 1,000 ms):
<?php
// Excerpt of config/pulse.php after `php artisan vendor:publish --tag=pulse-config`.
// Thresholds are in milliseconds; patterns are matched against the URL.
use Laravel\Pulse\Recorders;
return [
'recorders' => [
Recorders\SlowRequests::class => [
'enabled' => env('PULSE_SLOW_REQUESTS_ENABLED', true),
'threshold' => [
'#^/admin/#' => 5000,
'default' => env('PULSE_SLOW_REQUESTS_THRESHOLD', 300), // align with the latency SLO, not 1 s
],
],
Recorders\SlowOutgoingRequests::class => [
'enabled' => env('PULSE_SLOW_OUTGOING_REQUESTS_ENABLED', true),
'threshold' => [
'default' => env('PULSE_SLOW_OUTGOING_REQUESTS_THRESHOLD', 150), // one hop's cap
],
],
],
];Tests and the storage schema for the SQL lab:
<?php
namespace Tests\Unit;
use App\Support\LatencyHistogram;
use PHPUnit\Framework\TestCase;
class LatencyHistogramTest extends TestCase
{
public function test_bucket_error_is_below_one_bucket_width(): void
{
foreach ([150.0, 9_999.0, 250_000.0, 1_000_000.0] as $micros) {
$upper = LatencyHistogram::upperBound(LatencyHistogram::bucketFor($micros));
$this->assertGreaterThanOrEqual($micros, $upper);
$this->assertLessThan($micros * 1.0906, $upper); // 2^(1/8)
}
}
public function test_p99_sees_the_tail_the_mean_hides(): void
{
$buckets = [];
foreach (array_merge(array_fill(0, 985, 10_000.0), array_fill(0, 15, 1_000_000.0)) as $v) {
$b = LatencyHistogram::bucketFor($v);
$buckets[$b] = ($buckets[$b] ?? 0) + 1;
}
ksort($buckets);
$this->assertLessThan(11_000, LatencyHistogram::percentile($buckets, 50));
$this->assertGreaterThan(990_000, LatencyHistogram::percentile($buckets, 99));
}
}<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
// Raw request log (exact percentiles for a lab or a small app) and the
// pre-aggregated histogram table that scales (one row per route, minute, bucket).
return new class extends Migration
{
public function up(): void
{
Schema::create('request_log', function (Blueprint $table) {
$table->id();
$table->string('route', 120);
$table->unsignedInteger('duration_us');
$table->timestampTz('started_at')->index();
});
Schema::create('latency_buckets', function (Blueprint $table) {
$table->string('route', 120);
$table->timestampTz('minute');
$table->smallInteger('bucket');
$table->unsignedBigInteger('count');
$table->primary(['route', 'minute', 'bucket']);
});
}
public function down(): void
{
Schema::dropIfExists('latency_buckets');
Schema::dropIfExists('request_log');
}
};The Laravel angle
| Laravel feature | Use for latency | Note (Laravel 13 docs) |
|---|---|---|
Http::timeout() / connectTimeout() | Per-hop limits | "By default, the HTTP client will timeout after 30 seconds"; connect default 10 s |
Http::retry($times, $sleep, $when, throw: false) | Budget-aware retries | The when callable may modify $request before the next attempt |
Http::pool(fn (Pool $pool) => [...], concurrency: 5) | Parallel fan-out | Connection-level failures come back as ConnectionException instances |
Http::batch(...)->concurrency(5)->send() | Fan-out with callbacks | Progress and completion hooks |
Http::globalOptions([...]) | Default limits for every request | Set in AppServiceProvider::boot |
Terminable middleware (terminate()) | Record metrics after the response | A fresh middleware instance is resolved for terminate |
Redis::pipeline(), dynamic commands | Cheap histogram updates | "you may call any Redis command on the facade" |
| Laravel Pulse | Slow requests, slow outgoing requests, slow queries, slow jobs; Pulse::record with avg, count, max, min, sum | Thresholds default to 1,000 ms; no percentiles |
| Pulse Redis ingest | PULSE_INGEST_DRIVER=redis + php artisan pulse:work | Moves recording off the request path |
| Laravel Octane | Persistent workers | Removes per-request bootstrap (a warm-up cost) |
| Laravel Horizon | Separate supervisors per queue | Avoids head-of-line blocking between job classes |
Solving the classic problems
"The average is fine but users complain"
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Histograms everywhere | Prometheus/OTel histograms at the edge and per hop | Real p99, aggregatable | Cardinality per label |
| SLO on "fraction under threshold" | Bucket boundary at the SLO | Exact, alertable | Needs a decided threshold |
| Look at the max and p99.9 | Dashboards with full spectrum | Shows pauses and stalls | Noisy at low traffic |
When the raw log exists (lab scale or a small app), PostgreSQL computes exact percentiles; at scale query the pre-aggregated bucket table instead:
-- Exact percentiles from the raw request log (fine up to a few million rows)
SELECT route,
count(*) AS n,
round(avg(duration_us) / 1000.0, 1) AS mean_ms,
percentile_cont(0.50) WITHIN GROUP (ORDER BY duration_us) / 1000 AS p50_ms,
percentile_cont(0.99) WITHIN GROUP (ORDER BY duration_us) / 1000 AS p99_ms,
percentile_cont(0.999) WITHIN GROUP (ORDER BY duration_us) / 1000 AS p999_ms,
max(duration_us) / 1000.0 AS max_ms,
avg((duration_us <= 300000)::int) AS share_within_slo
FROM request_log
WHERE started_at > now() - interval '5 minutes'
GROUP BY route
ORDER BY p99_ms DESC;
-- Same question from the mergeable histogram table (bucket upper bound = 2^(bucket/8) us)
WITH w AS (
SELECT bucket, sum(count) AS c
FROM latency_buckets
WHERE route = 'dashboard' AND minute > now() - interval '1 hour'
GROUP BY bucket
), cum AS (
SELECT bucket, c, sum(c) OVER (ORDER BY bucket) AS running, sum(c) OVER () AS total FROM w
)
SELECT min(power(2, bucket / 8.0)) FILTER (WHERE running >= 0.99 * total) / 1000 AS p99_ms_upper_bound
FROM cum;A page that fans out is slow
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Parallelise | errgroup / Http::pool | Latency = max, not sum | Concurrency limits needed |
| Reduce N | Batch endpoints, precomputed views, caches | Fewer tail draws | Staleness, more code |
| Good-enough | Optional parts with short leashes | Bounded latency | Partial pages |
| Hedge stragglers | hedge.Do at p95 | p99 near p95 | 2 to 5% extra load |
| Leaf targets from q^(1/N) | Per-leaf SLO at p99.9 or p99.99 | Honest budgets | Harder leaf SLOs |
A cross-region call blows the budget
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Edge termination | Cloudflare/CloudFront/Global Accelerator near users | Handshakes cost 10 ms RTTs | Another layer to run |
| Data locality | Read replicas in each region | Reads in 1 ms | Replication lag |
| Home region | Pin writes to the data's home | One cross-region RTT, only for writes | Routing logic |
| Async instead of sync | Replicate events, not calls | No RTT on the hot path | Eventual consistency |
Load test said p99 = 2 ms, production says 800 ms
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Constant-rate generator | wrk2 -R, k6 constant-arrival-rate | No coordinated omission | Must pick a realistic rate |
| Measure from intended time | Schedule-based start times | True latency during stalls | Needs a model of arrivals |
| Corrected recording | HdrHistogram recordValueWithExpectedInterval | Fixes old data | Approximation |
| Test at production utilisation | Run near the planned peak | Shows the knee | Cost of the test environment |
Per-instance p99s averaged on a dashboard
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Histograms, then quantile | histogram_quantile(0.99, sum by (le) (rate(...))) | Correct fleet p99 | Bucket precision |
| Native/exponential histograms | Prometheus native, OTel exponential | Mergeable at high resolution | Newer tooling |
Never avg(quantile) | Code review rule | Avoids nonsense numbers | - |
Latency spikes at every deploy
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Readiness after warm-up | startupProbe, warm caches and pools before ready | No cold traffic | Slower rollout |
| Slow start | Envoy/NGINX Plus slow-start ramp | Gradual load | Config |
| Persistent workers | Laravel Octane, Go long-lived processes | No per-request bootstrap | Memory leaks matter |
| Pre-provision serverless | AWS Lambda Provisioned Concurrency, SnapStart | No cold starts | Paid idle capacity |
p99 explodes above 80% CPU
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Scale on latency or concurrency | HPA on in-flight requests, not 85% CPU | Stays left of the knee | More instances |
| Bounded queues + shedding | Reject early with 503 + Retry-After | Protects p99 for admitted requests | Some requests fail fast |
| Separate interactive and batch | Different pools/queues | No HOL blocking | Capacity split |
One slow replica drags every fan-out
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Latency-induced probation | Eject on per-host p99, shadow-probe, reintroduce | Removes the straggler | Temporarily less capacity |
| P2C balancing | Envoy LEAST_REQUEST | Slow hosts get less load naturally | Needs request counts |
| Micro-partitions | Move 5% slices off the host | Fast rebalancing | Partition metadata |
| Hedging | Second copy to another replica | Masks it immediately | Extra load |
Choosing
Which tail technique
| Situation | Recommended | Extra technique | Reason |
|---|---|---|---|
| Single call, idempotent read, replicas exist | Hedge at p95 with a 5% budget | Cancel losers | Cheapest big p99 win |
| Writes / non-idempotent calls | No hedging; deadlines + idempotency keys | Retry within budget only | Duplicates have side effects |
| Server-side queueing dominates, you own the servers | Tied requests | Shallow OS queues + priority | Duplicates cost only a queue slot |
| Large fan-out search / ranking | Good-enough + canary requests | Selective replication of top docs | Waiting for all is unbounded |
| Optional widgets (ads, recs, spell check) | Short leash, drop when late | Cache last good value | User does not miss them |
| One host intermittently slow | Probation / P2C balancing | Micro-partitions | Remove the straggler |
| Hot keys | Selective replication or edge cache | Request coalescing | Skew is the cause |
| High utilisation tier | Capacity to 50-70% + load shedding | Separate batch traffic | Queueing is the cause |
| Users far away | Edge PoP + anycast + regional replicas | Home region for writes | Physics is the cause |
| GC-heavy service | Reduce allocation, tune GOGC/GOMEMLIMIT | Hedging masks the rest | Variability is the cause |
Which histogram
| Situation | Recommended | Why |
|---|---|---|
| New Prometheus instrumentation | Native histogram | High resolution, mergeable, no boundaries |
| Existing dashboards on classic histograms | Keep, add a boundary at each SLO threshold | Exact SLO fractions |
| OpenTelemetry pipeline | Base-2 exponential histogram aggregation | Perfect subsetting, default 160 buckets |
| Load tester or benchmark | HdrHistogram with 3 digits | Full spectrum, coordinated-omission correction |
| Per-instance precise quantile, never aggregated | Summary | Only then |
| Laravel app without Prometheus | Redis log-linear histogram (this page) | Mergeable minutes, cheap writes |
Which geography
| Situation | Recommended | Latency effect |
|---|---|---|
| Users on one continent | One region, multi-AZ, CDN for static | Simple; edge saves handshakes |
| Global users, read-heavy | Edge + regional read replicas, one write region | Fast reads, writes pay one RTT |
| Global users, writes by user/tenant | Home-region partitioning (read-local/write-local, write-global for shared data) | Most writes local |
| Global strongly consistent data | Spanner/CockroachDB with regional placement | Commits pay cross-region quorums |
| Real-time multiplayer / chat | Anycast edge + regional servers + async fan-out | Low RTT to the nearest server |
In architecture: from a single process to a distributed system
The same promise, "the dashboard answers within 300 ms for 99% of requests", is spent differently as the system grows. What stays the same: a budget, a percentile, a measurement point and a histogram.
Monolith: one process, one database
How it shows up: latency is service time plus database queries plus queueing in the web server. The budget is mostly about queries (Query Planning) and pool sizes.
Simplest correct usage: a request histogram at the middleware; a slow-query log; PHP-FPM or Go server concurrency sized with Little's law; external calls with explicit timeouts.
Example (simple): one Laravel app on PHP-FPM with 20 workers, peak 150 req/s at 60 ms mean: L = 150 × 0.06 = 9 busy workers, so 45% utilisation; p99 stays near 3x the mean. Pulse thresholds at 300 ms.
Example (production-shaped): the same app behind Cloudflare: TLS ends at the edge, static assets cached, RecordRequestLatency writes histograms to Redis, latency:report dashboard runs in CI after a load test with k6 constant-arrival-rate.
Modular monolith: boundaries without the network
How it shows up: module calls are in-process, so the budget does not change, but this is where to write per-module latency targets that will become per-hop budgets later.
| Concern | In-process now | When extracted |
|---|---|---|
| Cost of a call | Nanoseconds to microseconds | 0.5 to 2 ms in-region RTT plus serialisation |
| Timeout | None needed | Per-hop timeout from the budget |
| Tail | GC and DB only | Plus network, queueing, the callee's GC |
| Fan-out | Loop over modules is cheap | Loop becomes N tail draws: batch it |
Example: orders calls pricing 30 times per page in a loop (30 µs total). Extracting pricing without a batch endpoint turns that into 30 sequential RTTs (30 to 60 ms) plus 30 tail draws; design pricing.quoteMany() before the split.
Microservices: every hop spends the budget
How it shows up: the budget is split per hop and propagated; fan-out multiplies tail risk; hedging and good-enough are per-call decisions.
Client -> Edge (budget 300 ms, p99) -> BFF -> {profile, orders, recs} in parallel
1 Edge: TLS at PoP; forwards Request-Timeout-Ms: 280 over a warm connection
2 BFF: budget.ForHop(profile, cap 150) -> hedge.Do(delay = p95 15 ms, 5% budget)
3 BFF: Gather(orders required, recs optional, budget 120 ms, minFraction for recs 0)
4 orders: ForHop(DB, cap 80) -> pgx query with ctx; refuses if under 10 ms left
5 recs late at 60 ms -> dropped, response partial=true; histogram per hop, trace per request
6 SLO: share of edge requests <= 300 ms; per-hop SLOs from q^(1/N) for the fan-outWhat survives across the boundary: the remaining budget (as milliseconds), the trace context, the idempotency key. What does not: a caller's timeout setting (each hop computes its own from the budget), and percentiles (they do not add or average; histograms do).
Distributed data: replicas, caches, regions
How it shows up: where data lives decides how many cross-region RTTs a request pays. Replicas give read-local latency at the price of staleness; consensus gives correctness at the price of quorum RTTs.
| Effect | Where it hurts | Mitigation |
|---|---|---|
| Cross-region synchronous read | Every request pays 80 to 150 ms | Regional replica or cache |
| Consensus write across regions | Each commit waits for a remote quorum | Home-region data; regional tables |
| Replica lag | Read-your-writes after a write | Pin reads to the home region briefly |
| Cache miss storm after deploy | p99 jumps to the database's | Warm-up, request coalescing (Caching) |
| Hot partition | One shard's p99 dominates | Selective replication, micro-partitions |
| Clock skew | Absolute deadlines wrong across hosts | Send remaining time, not timestamps |
Scaling path: 1x, 10x, 100x
| Load | What changes | Example |
|---|---|---|
| 1x | Histograms, explicit timeouts, one region, CDN for static | One Laravel app or one Go service, Pulse thresholds at the SLO |
| 10x | Budgets propagated, fan-out parallel and bounded, hedging on hot reads, capacity at 50-70% utilisation, constant-rate load tests | 5 to 20 services, Prometheus native histograms, k6 or wrk2 in CI |
| 100x | Multi-region with edge and anycast, home-region data, micro-partitions, probation, good-enough results, canary requests for fan-out | Hundreds of services, tied requests in owned storage, per-hop SLOs from q^(1/N) |
Lab: tail latency, queueing and coordinated omission with real numbers
Steps 1 to 3 are single-process Go programs and were run on the author's laptop; the outputs below are copied from those runs. Steps 4 to 7 need a running stack and are expected, not run.
- Run the tests (all packages, including the TLS reuse test):
cd docs/snippets/system-design/latency-budget-tail-latency/go
go test ./...
# ok academy/latency-budget-tail-latency/budget
# ok academy/latency-budget-tail-latency/client
# ok academy/latency-budget-tail-latency/fanout
# ok academy/latency-budget-tail-latency/hedge
# ok academy/latency-budget-tail-latency/hist
go test -v -run TestReuseSkipsHandshakes ./client/
# client_test.go: cold: connect=166.542µs tls=1.82525ms ttfb=72.833µs | warm: reused=true ttfb=98.916µs- Run the simulation and compare its three tables with the concept blocks:
go run ./cmd/tailsim
# 1) Fan-out: leaf p99 = 1 s for 1% of calls; request waits for ALL leaves
# N P(>=1 slow) p50 p99 p99 hedged@15ms extra calls
# 1 0.010 10ms 14ms 14ms 1.0%
# 10 0.096 14ms 1.00s 29ms 1.0%
# 100 0.634 1.00s 1.00s 35ms 1.0%
# 2) M/M/1 with service time S = 10 ms: W = S/(1-rho), p99 = ln(100)*W
# 0.80 40 ms 50 ms 230 ms ... 0.95 190 ms 200 ms 921 ms
# 3) Coordinated omission: 100 req/s for 100 s, server stalls 2 s at t=50 s
# measured from send n=10000 p50=1ms p99=1ms p99.9=1ms max=2.00s
# measured from intended n=10000 p50=1ms p99=1.10s p99.9=1.92s max=2.00s
# RecordCorrected (HdrHist) n=10199 p50=1ms p99=991ms p99.9=1.90s max=2.00sChange one parameter at a time in
tailsimand predict before running (predictions, not recorded output): leaf slow probability 0.001 (P(≥1 slow) for N = 100 is 1 − 0.999^100 ≈ 9.5%, still above 1%, so the plain p99 stays at 1 s); hedge delay 30 ms (hedged p99 rises by roughly the extra delay); one hedge instead of two (N = 100 hedged p99 climbs back toward 1 s, because P(both copies slow) × 100 ≈ 1%).Measure handshake phases with curl (expected, not run; numbers depend on your RTT):
curl -so /dev/null -w 'dns=%{time_namelookup} connect=%{time_connect} tls=%{time_appconnect} ttfb=%{time_starttransfer} total=%{time_total}\n' https://example.com/
# expected shape: dns=0.012 connect=0.095 tls=0.190 ttfb=0.285 total=0.286 (RTT ~90 ms: connect ~1 RTT, tls ~1 more)- Coordinated omission with wrk vs wrk2 against a test server that pauses (expected, not run):
wrk -t2 -c50 -d60s --latency http://127.0.0.1:8080/ # closed loop: p99 looks tiny
wrk2 -t2 -c50 -d60s -R2000 --latency http://127.0.0.1:8080/ # constant 2000 req/s, measured from intended time
# expected: during a 1 s pause wrk reports p99 in single-digit ms; wrk2 reports p99 near hundreds of ms- Prometheus queries (expected, not run):
# fleet p99, classic histogram
histogram_quantile(0.99, sum by (le) (rate(http_request_duration_seconds_bucket{job="api"}[5m])))
# share of requests within the 300 ms SLO (needs a bucket at 0.3)
sum(rate(http_request_duration_seconds_bucket{job="api",le="0.3"}[5m])) / sum(rate(http_request_duration_seconds_count{job="api"}[5m]))
# the WRONG way (never do this)
avg(http_request_duration_seconds{quantile="0.99"})- Laravel histogram report after some traffic (expected, not run):
php artisan latency:report dashboard --minutes=15 --slo-ms=300
# +------------+----------+
# | percentile | latency |
# | p50 | 42.0 ms |
# | p90 | 88.0 ms |
# | p99 | 262.1 ms |
# | p99.9 | 741.5 ms |
# +------------+----------+
# 18234 requests, 99.120% within 300 msCommon misconceptions
| Belief | Reality |
|---|---|
| The average describes the user experience | Latency is skewed; the mean hides the tail users remember (SRE: 1% at 5 s with a 100 ms mean) |
| p99 means 1% of users are affected | Sessions and fan-out make far more users meet a p99 event |
| p99s can be averaged across servers | Quantiles do not aggregate; merge histograms, then compute |
| More bandwidth means lower latency | Propagation depends on distance; bandwidth only cuts transmission time |
| TLS is slow because of CPU | The cost is round trips; TLS 1.3 and connection reuse remove most of it |
| Hedging doubles load | Hedging after p95 costs about 5% (2% in Google's BigTable test) |
| Hedging is safe for any request | Only for idempotent reads or keyed writes with dedup |
| 85% CPU is efficient | Past the knee queueing dominates: 5x service time at 80%, 10x at 90% in M/M/1 |
| Load tests show production latency | Closed-loop generators suffer coordinated omission |
| Removing a server under load hurts latency | Putting a slow server on probation improves it |
| Multi-region makes everything faster | Reads yes; consistent writes pay cross-region quorums |
| Caching fixes tail latency | Dean and Barroso: caches "do not directly address tail latency" unless the whole working set fits |
| Each service can pick its own timeout | Timeouts must come from one end-to-end budget |
Cheat sheet
| Topic | Remember |
|---|---|
| Fibre | 5 µs/km one way; 1 ms RTT per 100 km; real paths 1.3-2x longer |
| Dean's numbers | DC RTT 0.5 ms; CA-NL-CA 150 ms |
| Handshakes | TCP 1 RTT; TLS 1.3 +1; TLS 1.2 +2; QUIC 1 total; reuse = 0 |
| Budget | End-to-end, with a percentile and a measurement point; 15-25% margin |
| Per-hop timeout | min(callee p99.9, remaining − margin); refuse below callee p50 |
| Propagation | Send remaining ms, not timestamps |
| Fan-out | P(slow) = 1 − (1 − p)^N; leaf target q^(1/N) |
| Queueing | W = S/(1 − ρ); stay at 50-70% on latency-critical tiers |
| Little's law | L = λW; size pools with it |
| Hedging | Delay ≈ p95, cap copies, 5% budget, cancel losers, reads only |
| Tied | Enqueue twice, cancel on start, second copy after ~2x network delay |
| Partitions | 10-100x more partitions than machines; replicate hot ones |
| Good enough | Required vs optional dependencies; mark partial responses |
| Measuring | Constant-rate load, intended start time, record timeouts |
| Histograms | Native/exponential; bucket at SLO threshold; never avg quantiles |
| Geography | Edge near users, data near reads, writes to the home region |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — A service has a mean latency of 30 ms and you are told 1% of requests take 2 s. Roughly what are the other 99% doing, and why does the mean mislead? Must-know
Answer
Answer: The 1% contribute 0.01 × 2,000 = 20 ms to the mean, so the other 99% average about 10 ms. The mean (30 ms) describes almost no real request: most are 3x faster and some are 66x slower. SRE's footnote makes the same point with 50x.
2 — A page waits for 50 backends in parallel, each slow 1% of the time. What fraction of pages are slow, and what leaf percentile must be fast for the page p99 to be fast? Must-know
Answer
Answer: 1 − 0.99^50 ≈ 39.5% of pages are slow. For the page p99, each leaf needs 0.99^(1/50) ≈ 0.9998, its p99.98.
3 — What is the RTT floor between Frankfurt and Virginia, and why do measured RTTs exceed it? Good to know
Answer
Answer: About 6,550 km great-circle × 2 × 5 µs/km ≈ 65 ms. Real cables do not follow great circles and routers add delay, so 80 to 95 ms is typical (estimate).
4 — A new HTTPS connection over TCP and TLS 1.3 to a server 90 ms away: how long until the response, if the server takes 50 ms? And with a reused connection? Important
Answer
Answer: TCP 1 RTT + TLS 1 RTT + request 1 RTT + 50 ms = 320 ms. Reused: 90 + 50 = 140 ms. Connection reuse saves more than most code optimisation.
5 — Why does hedging at the p95 delay add only about 5% load, and why must it be restricted to idempotent requests? Important
Answer
Answer: Only requests still outstanding after the p95 latency (about 5%) get a second copy. Both copies may execute, so a non-idempotent request (a payment) could run twice; hedging is for reads or keyed writes with server-side dedup.
6 — How do tied requests differ from hedging with zero delay? Good to know
Answer
Answer: Tied copies are enqueued on two servers tagged with each other; the first to start executing cancels its twin before it runs, so the duplicate costs only a queue slot. Zero-delay hedging executes both. The client waits about 2x the network delay before the second copy so both do not start on empty queues.
7 — A tier runs at 90% utilisation with a 10 ms service time. Estimate mean and p99 response time with M/M/1, and the effect of dropping to 70%. Important
Answer
Answer: At 90%: W = 10/(1 − 0.9) = 100 ms, p99 ≈ 4.6 × 100 = 461 ms. At 70%: W = 33 ms, p99 ≈ 154 ms. Adding 30% more capacity cut p99 by 3x.
8 — Your load test at 100 req/s shows p99 = 1 ms, but the server had a 2 s stall. Why, and how do you measure correctly? Must-know
Answer
Answer: Coordinated omission: the closed-loop generator stopped sending during the stall and measured from the actual send time, so the stall became one sample. Use a constant-rate generator (wrk2, k6 arrival-rate) that measures from the intended start time, or correct with HdrHistogram's recordValueWithExpectedInterval; then p99 is about 1.1 s.
9 — Why is avg(http_request_duration_seconds{quantile="0.99"}) wrong, and what is right? Must-know
Answer
Answer: Quantiles cannot be averaged; the result is "statistically nonsensical". Export histograms and compute histogram_quantile(0.99, sum by (le) (rate(..._bucket[5m]))), or use native/exponential histograms.
10 — An EU user travels to the US. With read-local/write-global and an EU home region, what are the latencies for reads and writes, and what consistency issue appears? Important
Answer
Answer: Reads come from the US replica of EU data in about 1 ms plus edge time; writes are forwarded to the EU primary and pay about 85 ms RTT. Reads right after a write may be stale by the replication lag, so route that user's reads to the home region briefly (read-your-writes).
11 — Why can putting a slow server on probation improve latency during high load? Good to know
Answer
Answer: In fan-out every request that touches the slow server waits for it. Removing it lets the others answer quickly; shadow requests keep measuring it so it returns when healthy. Dean and Barroso call this "somewhat peculiar" but effective.
12 — Which Laravel Pulse feature would you use for percentiles, and what does Pulse provide instead? Good to know
Answer
Answer: None: Pulse aggregates avg, count, max, min and sum, and its slow-request cards use a threshold (default 1,000 ms). Use a histogram (Prometheus, OpenTelemetry or the Redis histogram on this page) for percentiles, and set Pulse thresholds to the SLO threshold.
Glossary
| Term | Meaning |
|---|---|
| Latency | Time someone waits for a result; usually response time at a named point |
| Response time | Time from sending a request to receiving the last byte, as measured by the client |
| Service time | Time a server actually spends working on the request |
| Queueing delay | Time spent waiting before service starts |
| Propagation delay | Distance divided by signal speed (about 5 µs/km in fibre) |
| Transmission delay | Message size divided by bandwidth |
| Speed of light in fibre | About 200,000 km/s, two thirds of the vacuum speed |
| RTT | Round-trip time: there and back; the unit of handshake cost |
| Latency budget | The end-to-end response-time target, split across components and hops |
| Timeout budget | The remaining time a hop may spend, derived from the end-to-end budget |
| Deadline propagation | Passing the remaining budget to every downstream call |
| Percentile (p50, p90, p99, p999) | The value below which that share of requests falls; p999 is p99.9 |
| Tail latency | The slow end of the distribution (p99 and above) |
| The Tail at Scale | Dean and Barroso's 2013 CACM article on tail-tolerant techniques |
| Tail-tolerant | Designed to stay responsive despite slow components |
| Fan-out | One request calling many backends in parallel (scatter-gather) |
| Hedged request | A second copy sent after a delay; the first answer wins, others are cancelled |
| Backup request | Finagle's name for a hedged request |
| Tied request | Copies enqueued on two servers that cancel each other when one starts |
| Micro-partition | One of many small partitions per machine, moved for load balancing |
| Selective replication | Extra replicas only for hot items |
| Latency-induced probation | Temporarily excluding a slow server while shadow-probing it |
| Good-enough result | A slightly incomplete answer returned to meet the latency target |
| Canary request | A request sent to one or two leaves before the full fan-out |
| Utilisation | ρ = arrival rate / service rate; share of time a server is busy |
| Little's law | L = λW: items in system = arrival rate × time in system |
| M/M/1 | Queue with Poisson arrivals, exponential service, one server |
| Knee | The utilisation range where queueing delay starts to dominate |
| Head-of-line blocking | A slow first item delaying independent items behind it |
| GC pause | Time the garbage collector stops or slows application work |
| Warm-up | The period after start when caches and pools are cold |
| Cold start | Serverless environment setup before the first invocation runs |
| Jitter | Variation in delay (network), or deliberate randomisation (retry backoff) |
| Coordinated omission | A measurement bug where the load generator stops sending during stalls |
| HdrHistogram | Gil Tene's high dynamic range histogram with fixed significant digits |
| Histogram buckets | Value ranges with counts; Prometheus classic buckets use le |
| Exponential histogram | Buckets growing by base 2^(2^-scale) (OpenTelemetry; Prometheus native) |
| Native histogram | Prometheus histogram type with dynamic exponential buckets in one series |
| Summary | Prometheus metric with client-side quantiles; not aggregatable |
| Latency SLO | Target share of requests faster than a threshold over a window |
| Error budget | The allowed share of requests that miss the SLO |
| Multi-region | Running the service in more than one geographic region |
| Read-local | Serving reads from replicas in the user's region |
| Write-global | Sending writes to a record's home region or a global consensus group |
| Edge / PoP | A point of presence near users that terminates connections and caches |
| Anycast | One address announced from many locations; routing picks a near one |
| GeoDNS | DNS answers chosen by the resolver's location |
| Power of two choices (P2C) | Pick two random backends, send to the less loaded |
| 0-RTT | Sending application data in the first flight on resumption (TLS 1.3, QUIC); replayable |
References
- Jeffrey Dean, Luiz André Barroso — The Tail at Scale, CACM 56(2), 2013: https://research.google/pubs/the-tail-at-scale/ (full text read from https://www.barroso.org/publications/TheTailAtScale.pdf)
- Jeffrey Dean — Designs, Lessons and Advice from Building Large Distributed Systems (LADIS 2009 keynote, "Numbers Everyone Should Know"): https://www.cs.cornell.edu/projects/ladis2009/talks/dean-keynote-ladis2009.pdf
- Gil Tene — How NOT to Measure Latency (InfoQ): https://www.infoq.com/presentations/latency-response-time/
- Gil Tene — wrk2 README (coordinated omission): https://github.com/giltene/wrk2
- HdrHistogram: https://hdrhistogram.github.io/HdrHistogram/ and https://github.com/HdrHistogram/HdrHistogram
- Google SRE Book — Monitoring Distributed Systems: https://sre.google/sre-book/monitoring-distributed-systems/
- Google SRE Book — Service Level Objectives: https://sre.google/sre-book/service-level-objectives/
- Prometheus — Histograms and summaries: https://prometheus.io/docs/practices/histograms/
- Prometheus — Native histograms specification: https://prometheus.io/docs/specs/native_histograms/
- OpenTelemetry — Metrics data model (ExponentialHistogram): https://opentelemetry.io/docs/specs/otel/metrics/data-model/
- OpenTelemetry — Metrics SDK (aggregation defaults): https://opentelemetry.io/docs/specs/otel/metrics/sdk/
- RFC 9293 — Transmission Control Protocol: https://www.rfc-editor.org/rfc/rfc9293.html
- RFC 7413 — TCP Fast Open: https://www.rfc-editor.org/rfc/rfc7413.html
- RFC 8446 — TLS 1.3: https://www.rfc-editor.org/rfc/rfc8446.html
- RFC 5246 — TLS 1.2: https://www.rfc-editor.org/rfc/rfc5246.txt
- RFC 9000 — QUIC: https://www.rfc-editor.org/rfc/rfc9000.html
- RFC 3393 — IP Packet Delay Variation: https://www.rfc-editor.org/rfc/rfc3393.html
- RFC 4786 — Operation of Anycast Services: https://www.rfc-editor.org/rfc/rfc4786.html
- AWS Builders' Library — Timeouts, retries, and backoff with jitter: https://aws.amazon.com/builders-library/timeouts-retries-and-backoff-with-jitter/
- AWS Global Accelerator — How it works: https://docs.aws.amazon.com/global-accelerator/latest/dg/introduction-how-it-works.html
- AWS Lambda — Execution environment lifecycle (cold starts): https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtime-environment.html
- gRPC — Deadlines: https://grpc.io/docs/guides/deadlines/
- gRPC — Request hedging: https://grpc.io/docs/guides/request-hedging/
- Envoy — HTTP routing (timeouts, retries, hedging): https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/http/http_routing
- Envoy — Outlier detection: https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/upstream/outlier
- Envoy — Load balancers (least request, P2C): https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/upstream/load_balancing/load_balancers
- Finagle — MethodBuilder (backup requests): https://twitter.github.io/finagle/guide/MethodBuilder.html
- Go —
net/http: https://pkg.go.dev/net/http - Go —
net/http/httptrace: https://pkg.go.dev/net/http/httptrace - Go —
golang.org/x/sync/errgroup: https://pkg.go.dev/golang.org/x/sync/errgroup - Go — A Guide to the Go Garbage Collector: https://go.dev/doc/gc-guide
- Laravel 13 — HTTP Client: https://laravel.com/docs/13.x/http-client
- Laravel 13 — Pulse: https://laravel.com/docs/13.x/pulse
- Laravel 13 — Middleware: https://laravel.com/docs/13.x/middleware
- Laravel 13 — Redis: https://laravel.com/docs/13.x/redis
- Wikipedia (secondary) — Optical fiber: https://en.wikipedia.org/wiki/Optical_fiber
- Wikipedia (secondary) — Little's law: https://en.wikipedia.org/wiki/Little's_law
- Wikipedia (secondary) — M/M/1 queue: https://en.wikipedia.org/wiki/M/M/1_queue