Skip to content

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 forGo to
The whole page in three tablesEverything in one minute
Why the tail, not the mean, sets the user experienceWhy it exists
Card 1991, Little 1961, Dean 2009, Dean and Barroso 2013, Tene, SRE bookWhere it comes from
Budgets, speed of light, handshakes, deadlinesBudget, Propagation, Handshakes, Deadlines
p50, p99, p999, fan-out arithmeticPercentiles, Fan-out
Queueing, Little's law, M/M/1, the kneeQueueing
GC pause, warm-up, cold start, jitter, head-of-line blockingVariability, Head-of-line blocking
Hedged, tied and backup requestsHedged, Tied
Micro-partitions, selective replication, probationMicro-partitions, Probation
Good-enough results and canary requestsGood enough and canaries
Measuring correctlyCoordinated omission, Histograms, Latency SLOs
Regions, edge, anycast, read-local/write-globalGeography
Formulas, knobs, error messagesMechanics
CodeGo, Laravel
Classic incidents and fixesSolving the classic problems
Which technique whenChoosing
Monolith to multi-regionIn architecture
Run the numbers yourselfLab
Wrong beliefs, summary, quiz, termsMisconceptions, 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).

QuantityNumberSource or method
Speed of light in fibreabout 200,000 km/s, so about 5 µs per km one way, 1 ms RTT per 100 kmWikipedia, Optical fiber (secondary): "around 200,000 kilometers per second"
Round trip within one datacenter0.5 msDean, "Numbers Everyone Should Know" (LADIS 2009)
California to the Netherlands and back150 msDean, same slide
Frankfurt to Virginia (6,550 km)fibre floor about 65 ms RTT; expect 80 to 95 msEstimate: 2 × 6,550 km × 5 µs
Frankfurt to Singapore (10,260 km)floor about 103 ms RTT; expect 150 ms or moreEstimate
Sydney to New York (16,000 km)"minimum delay of 80 milliseconds" one wayWikipedia, Optical fiber
New TCP connection1 RTT before the first request byteRFC 9293 three-way handshake
TLS 1.3 full handshake+1 RTT ("1-RTT"); 0-RTT on resumption, replayableRFC 8446
TLS 1.2 full handshake+2 RTTRFC 5246, Figure 1 message flow

Percentiles and fan-out.

If each backend is slow with probability pand one request waits for N of themP(the request is slow) = 1 − (1 − p)^N
1 in 100 (its p99 is slow)N = 11%
1 in 100N = 109.6%
1 in 100N = 10063% (Dean and Barroso)
1 in 10,000 (its p99.99 is slow)N = 2,00018%, "almost one in five" (Dean and Barroso)
To make the request's p99 fastwith N = 100each 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.

TechniqueOne lineCostWorks when
Deadline per hopEvery hop gets "what is left minus a margin"Nothing; prevents wasted workAlways
Hedged / backup requestSecond copy after the p95 delay, take the first answerAbout 5% extra loadIdempotent reads, replicas exist
Tied requestEnqueue on two servers; the first to start cancels the otherUnder 1% extra disk in Google's testServer-side queueing dominates
Micro-partitionsMany more partitions than machines, moved one at a timeMetadata, rebalancingLoad imbalance, slow machines
Selective replicationExtra copies of hot itemsStorageSkewed popularity
Latency-induced probationStop sending real traffic to a slow server, keep probing itTemporary capacity lossOne machine is slow for a while
Good-enough resultAnswer when enough leaves repliedSlightly incomplete answersSearch, ranking, optional widgets
Canary requestSend to one or two leaves before thousandsA little latencyHuge fan-out with risky queries
A. Frankfurt user straight to us-east-1 origin (RTT ~90 ms), new connection: 330 msTCP 1 RTT90TLS 1.3 1 RTT90HTTP 1 RTT90app50B. Same user via a Frankfurt edge PoP (RTT ~10 ms) holding warm connections to the origin: 180 msedge to origin, warm90app50300 ms page budgetfirst 10 = DNS from a nearby resolverfirst four boxes = DNS + TCP + TLS + HTTP to the edge, 10 ms eachBack-of-envelope estimates. Every new connection costs round trips before the first byte; only distance sets the RTT.Moving the handshakes next to the user and reusing connections is worth more than any code optimisation in the app box.

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 caseEngineering for the tail
Measures the mean or the medianMeasures p99, p99.9 and the max, per hop and end to end
Assumes every call costs the sameAssumes a few calls are 100x slower and plans for it
Gives every hop a fixed, generous timeoutGives 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 fastCan drive utilisation higher "without lengthening the latency tail" (Dean and Barroso)
Single region, single answer pathPlaces 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 ​

  1. "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.
  2. "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).
  3. "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 ​

text
     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 histograms

Little 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.

text
     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 ms

Real 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).

text
     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 ms

Real 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.

text
     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 ms

Real 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:

ProductConnection reuse / handshake savingDefault to know
Go net/http TransportKeep-alive pool, HTTP/2 multiplexingDefaultMaxIdleConnsPerHost = 2; TLSHandshakeTimeout: 10 * time.Second in DefaultTransport
Laravel HTTP client (Guzzle/cURL)cURL reuses connections within one handle; PHP-FPM workers start fresh per processtimeout 30 s, connectTimeout 10 s
NGINX upstreamkeepalive connections to upstreamsOff unless configured
Envoy / IstioPooled upstream connections, mTLS in the sidecarPer-cluster pools
Cloudflare / CloudFrontTLS terminates at the edge; warm connections to the originEdge close to the user
HTTP/3 (QUIC)1-RTT setup, 0-RTT resumptionSee 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).

text
     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 calling

Real 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:

ProductPrimitivePropagates?
gRPCDeadline; grpc-timeout on the wire (relative)Yes, when the incoming context is passed on
Gocontext.WithTimeout, http.NewRequestWithContextNo header; this page's budget package stamps Request-Timeout-Ms
LaravelHttp::timeout(float), connectTimeout()No; this page's LatencyBudget computes per-hop values
EnvoyRoute timeout, per_try_timeout, x-envoy-expected-rq-timeout-msInside the mesh
NGINXproxy_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.

text
     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:

ProductHow it computes percentilesAggregatable across instances?
Prometheus histogram (classic)histogram_quantile(0.99, sum by (le) (rate(..._bucket[5m])))Yes, sum the buckets
Prometheus native histogramhistogram_quantile(0.99, sum(rate(...[5m])))Yes
Prometheus summaryClient-side quantilesNo: avg(...{quantile="0.95"}) is "statistically nonsensical"
OpenTelemetry exponential histogramBuckets by scale; backend computesYes ("perfect subsetting")
HdrHistogramgetValueAtPercentile; merge by addingYes
PostgreSQLpercentile_cont, percentile_disc on raw rowsExact, but needs raw data
Laravel PulseAggregates avg, count, max, min, sumNo 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).

0.00.20.40.60.81.01500100015002000servers a request fans out to (N)P(request slow)0.63 at N=1000.18 at N=20001 in 100 calls slow1 in 1,0001 in 10,000P = 1 - (1 - p)^NPoints from Dean andBarroso, CACM 2013
text
     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 off

Real 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".

0x5x10x15x20x0%20%40%60%80%100%utilisation rho = arrival rate / service rateresponse time / service time50%: 2x80%: 5x90%: 10x95%: 20xkneecliffM/M/1: W = S / (1 - rho); p99 = ln(100) x WLittle: L = lambda x W (requests in system)
text
     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 system

Real 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).

text
     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:

SourceProduct knobEffect
Go GCGOGC, GOMEMLIMIT (via runtime/debug)Fewer cycles means fewer assists and pauses
JVM GCG1, ZGC, Shenandoah collectorsLow-pause collectors trade throughput
Warm-upKubernetes readinessProbe, startupProbe, slow-start in Envoy and NGINX PlusNo traffic until warm, then ramp up
AWS Lambda cold startProvisioned Concurrency, SnapStartPre-initialised environments
PHPOPcache preloading, Laravel Octane (persistent workers)No per-request bootstrap
Background workThrottling, scheduling off-peak, Dean and Barroso's synchronised disruptionFewer 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."

text
     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).

Hedged request: send a copy only when the first one is slower than p95ClientReplica AReplica BA busy: GC pause / compaction (would answer at 1,000 ms)B: 10 mst=0 send to At=15 ms (p95): hedge to Bt=25 ms: use B, cancel AcancelCost: only the ~5% of requests slower than p95 get a copy, so about 5% extra load (Dean and Barroso).Tied request: enqueue on both, the first to start cancels its twinClientReplica AReplica BA: queued behind other workqueuedB executessend to A, tag B; 1 ms later send to B, tag AB starts: "cancel your copy"A drops it before running itanswer from B
text
     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:

ProductFeatureNote
gRPChedgingPolicy (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"
Cassandraspeculative_retry table option ("rapid read protection"), e.g. 99percentileCoordinator sends an extra read to another replica when the first is slower than that percentile
This page, Gohedge.Do with a token-bucket BudgetDelay 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.

text
     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 req

Real 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".

text
     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 partition

Real 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."

text
     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 up

Real 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."

text
     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."

text
     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 s

Real 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:

FamilyBucket layoutPrecisionAggregation
HdrHistogramLog-linear; fixed significant digits ("3 significant digits ... no larger than 1/1,000th (or 0.1%) of any value")Configurable, 1 to 5 digitsExact merge by adding counts
Prometheus classic histogramExplicit 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 histogramExponential schema, sparse buckets, one series"Limited by the configured resolution"Any; layouts reconciled automatically
OpenTelemetry exponential histogrambase = 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 histogramDefault boundaries [0, 5, 10, 25, 50, 75, 100, 250, 500, 750, 1000, 2500, 5000, 7500, 10000]CoarseLike classic
text
     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 close

Real 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.

text
     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.

Read-local, write-global: one anycast address, edges near users, data with a home regionUser in FrankfurtUser in VirginiaEdge PoP (anycast)TLS ends here, ~10 msEdge PoP (anycast)TLS ends here, ~10 msRegion eu-central-1Region us-east-1App serversPrimary: EU users(their home)Replica of USusers (stale by lag)App serversPrimary: US users(their home)Replica of EUusers (stale by lag)EU user's write from US: ~85 ms RTTasync replication (lag)Reads stay in-region (~1 ms); only writes for another region's users cross the ocean. RTTs are fibre estimates.
text
     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 write

Real 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:

NeedProducts
Edge termination and cachingCloudflare, AWS CloudFront, Fastly, Akamai
Anycast entry into a backboneCloudflare, AWS Global Accelerator ("two static IPv4 addresses ... anycast from the AWS edge network"), Google Cloud global load balancer
GeoDNS / latency routingAWS Route 53 latency-based and geolocation routing, NS1, Cloudflare load balancing
Read-local replicasPostgreSQL read replicas, Aurora Global Database, DynamoDB global tables, Redis replicas
Write-global consistencySpanner, 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 ​

QuantityFormulaExample
Propagation delay (one way)distance × 5 µs/km in fibre6,550 km → 33 ms
RTT floor2 × distance × 5 µs/kmFrankfurt–Virginia 65 ms
Transmission delaysize / bandwidth1 MB at 100 Mbit/s → 80 ms
Cold HTTPS request (TCP + TLS 1.3)3 RTT + server time3 × 90 + 50 = 320 ms
Warm keep-alive request1 RTT + server time90 + 50 = 140 ms
Sequential chainsum of hop latencies4 × 50 = 200 ms
Parallel fan-outmax of leaf latenciesdominated by the slowest leaf
Per-hop timeoutmin(callee p99.9, remaining − margin)min(120, 300 − 60) = 120 ms

Fan-out and percentile arithmetic ​

QuestionFormulaExample
P(request slow), N independent leaves1 − (1 − p)^Np = 0.01, N = 100 → 0.634
Leaf quantile needed for end-to-end qq^(1/N)q = 0.99, N = 100 → 0.9999
Users who see at least one slow page per session of k pages1 − (1 − p_page)^kp_page = 0.01, k = 20 → 18%
Extra load of hedging at delay dP(latency > d) per hedge levelhedge at p95 → about 5%
Benefit of one hedgeP(both slow) ≈ p² if independent0.01 → 0.0001

Queueing formulas (M/M/1 intuition) ​

QuantityFormulaNote
Utilisationρ = λ/μMust be under 1 for stability
Little's lawL = λWAny stable system, any distribution
Mean response timeW = 1/(μ − λ) = S/(1 − ρ)S = 1/μ service time
Mean queueing delayρ/(μ − λ) = W − SWaiting before service
p99 response timeln(100) × W ≈ 4.6 WM/M/1 response time is exponential
Pool size from Littleworkers ≥ λ × W200 req/s × 0.05 s = 10 busy workers, size for 15 to 20

Handshake costs ​

SetupRTTs before the first request byte arrivesSource
TCP + TLS 1.2 (full)3RFC 9293 + RFC 5246 Figure 1
TCP + TLS 1.3 (full)2RFC 8446
TCP + TLS 1.3 with 0-RTT early data1 (data rides with ClientHello)RFC 8446; replayable
TCP Fast Open + TLS 1.3 0-RTT0 extra for data in SYN (rare in practice)RFC 7413
QUIC / HTTP/3 (new)1RFC 9000
QUIC 0-RTT (resumed)0RFC 9000; replayable
Reused keep-alive / HTTP/2 connection0Connection pooling

Histogram precision ​

HistogramSettingWorst-case relative error
HdrHistogram3 significant digits0.1%
HdrHistogram2 significant digits1%
OTel exponentialscale 3 (base 1.0905)about 9% bucket width
OTel exponentialscale 8 (base 1.0027)about 0.27%
Prometheus nativeNativeHistogramBucketFactor 1.1about 10% bucket width
Prometheus classicbuckets 0.2, 0.3, 0.45 sup to the bucket width (150 ms around 0.3 s)
This page's Go hist3 digits, 1 µs to 1 h0.1%, fixed memory
This page's Laravel LatencyHistogram8 buckets per power of 2under 9.1%

Knobs that shape latency ​

ProductKnobDefaultLatency meaning
Go http.ClientTimeout0 (no timeout)"includes connection time, any redirects, and reading the response body"
Go http.TransportResponseHeaderTimeout0Server think time limit
Go http.TransportTLSHandshakeTimeout10 s in DefaultTransportCap the handshake RTTs
Go http.TransportMaxIdleConnsPerHost2Too low forces new handshakes
Go runtimeGOGC, GOMEMLIMIT100, no limitGC frequency: fewer cycles, fewer assists
Laravel HTTP clienttimeout() / connectTimeout()30 s / 10 sPer-hop limits; float seconds allowed
Laravel HTTP clientretry(times, sleep, when, throw)noneRetry only while the budget allows
Laravel HTTP clientHttp::pool(..., concurrency: n)unboundedParallel fan-out
Laravel PulseSlowRequests / SlowOutgoingRequests threshold1,000 msAlign with the SLO threshold
gRPChedgingPolicy.hedgingDelay, maxAttempts (max 5)offHedging (not in grpc-go)
Envoyroute timeout, per_try_timeout, hedge_policy15 s route timeoutDeadline and hedging in the mesh
EnvoyLEAST_REQUEST choice_count2Power of two choices
Finagleidempotent(maxExtraLoad)0 = offBackup requests
AWS LambdaProvisioned Concurrency0Removes cold starts for that capacity
PrometheusNativeHistogramBucketFactoroff (classic)Exponential buckets
OpenTelemetry SDKMaxSize, MaxScale160, 20Exponential histogram resolution

Error messages you will actually see ​

WhereMessageMeaning
Gocontext deadline exceededThe hop's budget ran out
Go net/httpnet/http: TLS handshake timeoutTLSHandshakeTimeout fired
Go net/httpnet/http: timeout awaiting response headersResponseHeaderTimeout fired
Go (this page)budget: exhausted before the call startedThe call was refused because it could not finish
LaravelIlluminate\Http\Client\ConnectionException (cURL error 28)timeout() or connectTimeout() exceeded
gRPCDEADLINE_EXCEEDEDDeadline passed
Envoyupstream request timeout (504)Route timeout
Elasticsearch"timed_out": true in a search responsePartial (good-enough) results
Prometheusinfo annotation on reconciled NHCB layoutsBucket 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.

go
// 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.

go
// 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))
	}
}
go
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.

go
// 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
}
go
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):

go
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.

go
// 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) }
go
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%.

go
// 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
}
go
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.

go
// 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
}
go
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):

go
// 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 featureUse for latencyNote
context.WithTimeout, ctx.Deadline()Budgets and propagationPass ctx first; every blocking call should take it
http.NewRequestWithContextCancel an in-flight call when the budget ends or a hedge winsWithout it, losers keep running
http.Transport pool fieldsAvoid handshakes (MaxIdleConnsPerHost, IdleConnTimeout)DefaultMaxIdleConnsPerHost = 2
net/http/httptrace.ClientTraceDNS, connect, TLS, first byte timings"hooks to run at various stages of an outgoing HTTP request"
golang.org/x/sync/errgroupBounded fan-out (SetLimit); WithContext cancels on first errorUse plain Group when one failure must not cancel the rest
time.Timer, selectHedge delays, per-leaf deadlinesStop/drain timers before Reset
runtime/debug.SetGCPercent, SetMemoryLimitGC frequencyGC guide: "reducing GC frequency may also lead to latency improvements"
runtime/trace, go tool traceSee GC assists, scheduler delayGC guide: latency sources "are visible in execution traces"
github.com/HdrHistogram/hdrhistogram-goProduction HdrHistogramThe hist package here is a teaching version
github.com/prometheus/client_golangHistogram with Buckets or NativeHistogramBucketFactorExport, 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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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 featureUse for latencyNote (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 retriesThe when callable may modify $request before the next attempt
Http::pool(fn (Pool $pool) => [...], concurrency: 5)Parallel fan-outConnection-level failures come back as ConnectionException instances
Http::batch(...)->concurrency(5)->send()Fan-out with callbacksProgress and completion hooks
Http::globalOptions([...])Default limits for every requestSet in AppServiceProvider::boot
Terminable middleware (terminate())Record metrics after the responseA fresh middleware instance is resolved for terminate
Redis::pipeline(), dynamic commandsCheap histogram updates"you may call any Redis command on the facade"
Laravel PulseSlow requests, slow outgoing requests, slow queries, slow jobs; Pulse::record with avg, count, max, min, sumThresholds default to 1,000 ms; no percentiles
Pulse Redis ingestPULSE_INGEST_DRIVER=redis + php artisan pulse:workMoves recording off the request path
Laravel OctanePersistent workersRemoves per-request bootstrap (a warm-up cost)
Laravel HorizonSeparate supervisors per queueAvoids head-of-line blocking between job classes

Solving the classic problems ​

"The average is fine but users complain" ​

SolutionHowAdvantageCost / limitation
Histograms everywherePrometheus/OTel histograms at the edge and per hopReal p99, aggregatableCardinality per label
SLO on "fraction under threshold"Bucket boundary at the SLOExact, alertableNeeds a decided threshold
Look at the max and p99.9Dashboards with full spectrumShows pauses and stallsNoisy 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:

sql
-- 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 ​

SolutionHowAdvantageCost / limitation
Paralleliseerrgroup / Http::poolLatency = max, not sumConcurrency limits needed
Reduce NBatch endpoints, precomputed views, cachesFewer tail drawsStaleness, more code
Good-enoughOptional parts with short leashesBounded latencyPartial pages
Hedge stragglershedge.Do at p95p99 near p952 to 5% extra load
Leaf targets from q^(1/N)Per-leaf SLO at p99.9 or p99.99Honest budgetsHarder leaf SLOs

A cross-region call blows the budget ​

SolutionHowAdvantageCost / limitation
Edge terminationCloudflare/CloudFront/Global Accelerator near usersHandshakes cost 10 ms RTTsAnother layer to run
Data localityRead replicas in each regionReads in 1 msReplication lag
Home regionPin writes to the data's homeOne cross-region RTT, only for writesRouting logic
Async instead of syncReplicate events, not callsNo RTT on the hot pathEventual consistency

Load test said p99 = 2 ms, production says 800 ms ​

SolutionHowAdvantageCost / limitation
Constant-rate generatorwrk2 -R, k6 constant-arrival-rateNo coordinated omissionMust pick a realistic rate
Measure from intended timeSchedule-based start timesTrue latency during stallsNeeds a model of arrivals
Corrected recordingHdrHistogram recordValueWithExpectedIntervalFixes old dataApproximation
Test at production utilisationRun near the planned peakShows the kneeCost of the test environment

Per-instance p99s averaged on a dashboard ​

SolutionHowAdvantageCost / limitation
Histograms, then quantilehistogram_quantile(0.99, sum by (le) (rate(...)))Correct fleet p99Bucket precision
Native/exponential histogramsPrometheus native, OTel exponentialMergeable at high resolutionNewer tooling
Never avg(quantile)Code review ruleAvoids nonsense numbers-

Latency spikes at every deploy ​

SolutionHowAdvantageCost / limitation
Readiness after warm-upstartupProbe, warm caches and pools before readyNo cold trafficSlower rollout
Slow startEnvoy/NGINX Plus slow-start rampGradual loadConfig
Persistent workersLaravel Octane, Go long-lived processesNo per-request bootstrapMemory leaks matter
Pre-provision serverlessAWS Lambda Provisioned Concurrency, SnapStartNo cold startsPaid idle capacity

p99 explodes above 80% CPU ​

SolutionHowAdvantageCost / limitation
Scale on latency or concurrencyHPA on in-flight requests, not 85% CPUStays left of the kneeMore instances
Bounded queues + sheddingReject early with 503 + Retry-AfterProtects p99 for admitted requestsSome requests fail fast
Separate interactive and batchDifferent pools/queuesNo HOL blockingCapacity split

One slow replica drags every fan-out ​

SolutionHowAdvantageCost / limitation
Latency-induced probationEject on per-host p99, shadow-probe, reintroduceRemoves the stragglerTemporarily less capacity
P2C balancingEnvoy LEAST_REQUESTSlow hosts get less load naturallyNeeds request counts
Micro-partitionsMove 5% slices off the hostFast rebalancingPartition metadata
HedgingSecond copy to another replicaMasks it immediatelyExtra load

Choosing ​

Which tail technique ​

SituationRecommendedExtra techniqueReason
Single call, idempotent read, replicas existHedge at p95 with a 5% budgetCancel losersCheapest big p99 win
Writes / non-idempotent callsNo hedging; deadlines + idempotency keysRetry within budget onlyDuplicates have side effects
Server-side queueing dominates, you own the serversTied requestsShallow OS queues + priorityDuplicates cost only a queue slot
Large fan-out search / rankingGood-enough + canary requestsSelective replication of top docsWaiting for all is unbounded
Optional widgets (ads, recs, spell check)Short leash, drop when lateCache last good valueUser does not miss them
One host intermittently slowProbation / P2C balancingMicro-partitionsRemove the straggler
Hot keysSelective replication or edge cacheRequest coalescingSkew is the cause
High utilisation tierCapacity to 50-70% + load sheddingSeparate batch trafficQueueing is the cause
Users far awayEdge PoP + anycast + regional replicasHome region for writesPhysics is the cause
GC-heavy serviceReduce allocation, tune GOGC/GOMEMLIMITHedging masks the restVariability is the cause

Which histogram ​

SituationRecommendedWhy
New Prometheus instrumentationNative histogramHigh resolution, mergeable, no boundaries
Existing dashboards on classic histogramsKeep, add a boundary at each SLO thresholdExact SLO fractions
OpenTelemetry pipelineBase-2 exponential histogram aggregationPerfect subsetting, default 160 buckets
Load tester or benchmarkHdrHistogram with 3 digitsFull spectrum, coordinated-omission correction
Per-instance precise quantile, never aggregatedSummaryOnly then
Laravel app without PrometheusRedis log-linear histogram (this page)Mergeable minutes, cheap writes

Which geography ​

SituationRecommendedLatency effect
Users on one continentOne region, multi-AZ, CDN for staticSimple; edge saves handshakes
Global users, read-heavyEdge + regional read replicas, one write regionFast reads, writes pay one RTT
Global users, writes by user/tenantHome-region partitioning (read-local/write-local, write-global for shared data)Most writes local
Global strongly consistent dataSpanner/CockroachDB with regional placementCommits pay cross-region quorums
Real-time multiplayer / chatAnycast edge + regional servers + async fan-outLow 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.

ConcernIn-process nowWhen extracted
Cost of a callNanoseconds to microseconds0.5 to 2 ms in-region RTT plus serialisation
TimeoutNone neededPer-hop timeout from the budget
TailGC and DB onlyPlus network, queueing, the callee's GC
Fan-outLoop over modules is cheapLoop 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.

text
     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-out

What 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.

EffectWhere it hurtsMitigation
Cross-region synchronous readEvery request pays 80 to 150 msRegional replica or cache
Consensus write across regionsEach commit waits for a remote quorumHome-region data; regional tables
Replica lagRead-your-writes after a writePin reads to the home region briefly
Cache miss storm after deployp99 jumps to the database'sWarm-up, request coalescing (Caching)
Hot partitionOne shard's p99 dominatesSelective replication, micro-partitions
Clock skewAbsolute deadlines wrong across hostsSend remaining time, not timestamps

Scaling path: 1x, 10x, 100x ​

LoadWhat changesExample
1xHistograms, explicit timeouts, one region, CDN for staticOne Laravel app or one Go service, Pulse thresholds at the SLO
10xBudgets propagated, fan-out parallel and bounded, hedging on hot reads, capacity at 50-70% utilisation, constant-rate load tests5 to 20 services, Prometheus native histograms, k6 or wrk2 in CI
100xMulti-region with edge and anycast, home-region data, micro-partitions, probation, good-enough results, canary requests for fan-outHundreds 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.

  1. Run the tests (all packages, including the TLS reuse test):
bash
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
  1. Run the simulation and compare its three tables with the concept blocks:
bash
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.00s
  1. Change one parameter at a time in tailsim and 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%).

  2. Measure handshake phases with curl (expected, not run; numbers depend on your RTT):

bash
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)
  1. Coordinated omission with wrk vs wrk2 against a test server that pauses (expected, not run):
bash
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
  1. Prometheus queries (expected, not run):
bash
# 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"})
  1. Laravel histogram report after some traffic (expected, not run):
bash
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 ms

Common misconceptions ​

BeliefReality
The average describes the user experienceLatency 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 affectedSessions and fan-out make far more users meet a p99 event
p99s can be averaged across serversQuantiles do not aggregate; merge histograms, then compute
More bandwidth means lower latencyPropagation depends on distance; bandwidth only cuts transmission time
TLS is slow because of CPUThe cost is round trips; TLS 1.3 and connection reuse remove most of it
Hedging doubles loadHedging after p95 costs about 5% (2% in Google's BigTable test)
Hedging is safe for any requestOnly for idempotent reads or keyed writes with dedup
85% CPU is efficientPast the knee queueing dominates: 5x service time at 80%, 10x at 90% in M/M/1
Load tests show production latencyClosed-loop generators suffer coordinated omission
Removing a server under load hurts latencyPutting a slow server on probation improves it
Multi-region makes everything fasterReads yes; consistent writes pay cross-region quorums
Caching fixes tail latencyDean and Barroso: caches "do not directly address tail latency" unless the whole working set fits
Each service can pick its own timeoutTimeouts must come from one end-to-end budget

Cheat sheet ​

TopicRemember
Fibre5 µs/km one way; 1 ms RTT per 100 km; real paths 1.3-2x longer
Dean's numbersDC RTT 0.5 ms; CA-NL-CA 150 ms
HandshakesTCP 1 RTT; TLS 1.3 +1; TLS 1.2 +2; QUIC 1 total; reuse = 0
BudgetEnd-to-end, with a percentile and a measurement point; 15-25% margin
Per-hop timeoutmin(callee p99.9, remaining − margin); refuse below callee p50
PropagationSend remaining ms, not timestamps
Fan-outP(slow) = 1 − (1 − p)^N; leaf target q^(1/N)
QueueingW = S/(1 − ρ); stay at 50-70% on latency-critical tiers
Little's lawL = λW; size pools with it
HedgingDelay ≈ p95, cap copies, 5% budget, cancel losers, reads only
TiedEnqueue twice, cancel on start, second copy after ~2x network delay
Partitions10-100x more partitions than machines; replicate hot ones
Good enoughRequired vs optional dependencies; mark partial responses
MeasuringConstant-rate load, intended start time, record timeouts
HistogramsNative/exponential; bucket at SLO threshold; never avg quantiles
GeographyEdge near users, data near reads, writes to the home region

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
LatencyTime someone waits for a result; usually response time at a named point
Response timeTime from sending a request to receiving the last byte, as measured by the client
Service timeTime a server actually spends working on the request
Queueing delayTime spent waiting before service starts
Propagation delayDistance divided by signal speed (about 5 µs/km in fibre)
Transmission delayMessage size divided by bandwidth
Speed of light in fibreAbout 200,000 km/s, two thirds of the vacuum speed
RTTRound-trip time: there and back; the unit of handshake cost
Latency budgetThe end-to-end response-time target, split across components and hops
Timeout budgetThe remaining time a hop may spend, derived from the end-to-end budget
Deadline propagationPassing 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 latencyThe slow end of the distribution (p99 and above)
The Tail at ScaleDean and Barroso's 2013 CACM article on tail-tolerant techniques
Tail-tolerantDesigned to stay responsive despite slow components
Fan-outOne request calling many backends in parallel (scatter-gather)
Hedged requestA second copy sent after a delay; the first answer wins, others are cancelled
Backup requestFinagle's name for a hedged request
Tied requestCopies enqueued on two servers that cancel each other when one starts
Micro-partitionOne of many small partitions per machine, moved for load balancing
Selective replicationExtra replicas only for hot items
Latency-induced probationTemporarily excluding a slow server while shadow-probing it
Good-enough resultA slightly incomplete answer returned to meet the latency target
Canary requestA 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 lawL = λW: items in system = arrival rate × time in system
M/M/1Queue with Poisson arrivals, exponential service, one server
KneeThe utilisation range where queueing delay starts to dominate
Head-of-line blockingA slow first item delaying independent items behind it
GC pauseTime the garbage collector stops or slows application work
Warm-upThe period after start when caches and pools are cold
Cold startServerless environment setup before the first invocation runs
JitterVariation in delay (network), or deliberate randomisation (retry backoff)
Coordinated omissionA measurement bug where the load generator stops sending during stalls
HdrHistogramGil Tene's high dynamic range histogram with fixed significant digits
Histogram bucketsValue ranges with counts; Prometheus classic buckets use le
Exponential histogramBuckets growing by base 2^(2^-scale) (OpenTelemetry; Prometheus native)
Native histogramPrometheus histogram type with dynamic exponential buckets in one series
SummaryPrometheus metric with client-side quantiles; not aggregatable
Latency SLOTarget share of requests faster than a threshold over a window
Error budgetThe allowed share of requests that miss the SLO
Multi-regionRunning the service in more than one geographic region
Read-localServing reads from replicas in the user's region
Write-globalSending writes to a record's home region or a global consensus group
Edge / PoPA point of presence near users that terminates connections and caches
AnycastOne address announced from many locations; routing picks a near one
GeoDNSDNS answers chosen by the resolver's location
Power of two choices (P2C)Pick two random backends, send to the less loaded
0-RTTSending application data in the first flight on resumption (TLS 1.3, QUIC); replayable

References ​

Built by Morteza Negahi