AlgoViz

Latency

easy 30 min

Latency is how long one request takes.

Video lesson · Chapter 1 of 6

Follow one round trip

0:00 / 4:59

Latency

1:12Reel

Theory

Read or listen first. About 2 min.

What it is

Latency is the time between asking and getting an answer. You press a button, and some milliseconds later the page reacts. Those milliseconds are the latency of that one request.

It is never one thing. A request travels over a network, waits its turn, is worked on, and travels back. Each part takes time, and the total is the sum of the parts that happen one after another.

It is never one number either. The same page may take 20 ms for one person and 900 ms for the next. A useful description therefore says how many requests are faster than some value: a percentile.

Why it exists

People notice waiting. Long waits break concentration, and software that waits on other software passes the delay on.

Measuring it tells you where to work. If 60 of 80 ms is distance, a faster database is wasted money. If requests wait in a queue, faster code may matter less than more workers.

A short history

  1. 1968

    Robert B. Miller presents a paper on how fast a computer must answer to keep a conversation with a person going.

  2. 1983

    Mike Muuss writes ping in December, a small program that times the round trip of a packet. Ping becomes an everyday word for network latency.

  3. 1993

    Jakob Nielsen's Usability Engineering sums up three limits: 0.1 second feels instant, 1 second keeps the flow of thought, 10 seconds keeps attention.

  4. 2009

    Jake Brutlag at Google publishes experiments in which adding 100 to 400 ms to search lowered searches per person by 0.2% to 0.6%.

  5. 2013

    Jeffrey Dean and Luiz Barroso publish The Tail at Scale: in a system of many parts, rare slow answers become common.

Words to know

Round trip (RTT)
The time for a message to go there and for an answer to come back.
Response time
What the caller waits in total. Often used as a synonym for latency.
Percentile
P95 = 200 ms means 95% of requests took 200 ms or less.
Tail latency
The slow end: P95, P99, P99.9.
Time to first byte
From starting the request until the first byte of the answer arrives.
Queueing
Time spent waiting before anyone works on the request.
Propagation delay
Travel time of the signal. About 5 ms per 1,000 km of fibre, one way.

How it works

Step through the idea, or press Play.

Step 1 of 3

Split. Network, queue, work, storage: one number each

Understand it

Start here

The pizza delivery story

Imagine ordering a pizza. Latency is how long it takes from your call until the pizza is at your door. If the shop is far away you wait longer. If there is traffic you wait longer. If they are busy you wait longer. These are three different problems, with three different fixes.

One pizza, thirty minutes
One pizza, please18:000 minThe clock starts

5 + 10 + 15 = 30. The nearer shop: no wait, 5 minutes of baking, 3 minutes of road.

It is also called response time, delay, lag, or ping for the network part. It is measured in milliseconds (ms), microseconds (µs) and nanoseconds (ns): 1 ms = 1,000 µs = 1,000,000 ns.

The idea

Why it matters

What a person feels

  • Under about 100 ms

    Feels instant: the screen seems to obey.

  • 100 to 300 ms

    A small delay that people notice.

  • Over 1 second

    The train of thought starts to break. Show progress.

  • Over 10 seconds

    Attention is gone. People do something else.

The limits at 0.1, 1 and 10 seconds are Nielsen's. The middle band is a common rule of thumb.

What it did to some businesses

WhoWhat was reportedRead it as
Google, 2009100 to 400 ms more: 0.2% to 0.6% fewer searches a personA published controlled experiment
Google, 200630 results took 0.9 s instead of 0.4 s; traffic and revenue in the test fell 20%A talk, retold in a blog. The page also held more results
Amazon, before 2006Steps of 100 ms caused "substantial and costly drops in revenue"A former engineer's account; often quoted as 1% per 100 ms, without published data
Google, 201653% of mobile visits likely abandoned above 3 sA study of mobile sites of its time
The direction is the same in all four. Do not promise your own product the same numbers: test it.

Types

The four parts of a wait

A trip by car has the same parts: the length of the road, the work at each stop, and the line of cars in front of you.

  • Network

    Propagation (distance), transmission (size divided by bandwidth), and routers on the way.

  • Processing

    CPU work, database queries, business logic.

  • Queueing

    Waiting in the request queue, for a thread, or for a pooled connection.

  • Disk I/O

    Seek on a spinning disk, the read or write itself, file system overhead.

One request, with its milliseconds

A user sends a request across 20 milliseconds of network to our system: a load balancer taking 1 millisecond, then one application server working 15 milliseconds, which asks a database taking 10 milliseconds. The answer returns the same way.
Blue is the way in, orange the way back. Example values.

Add up the round trip

2+20+1⏟in+15+10⏟work+1+20+2⏟back=71 ms\underbrace{2 + 20 + 1}_{\text{in}} + \underbrace{15 + 10}_{\text{work}} + \underbrace{1 + 20 + 2}_{\text{back}} = 71\ \text{ms}
Client 2, network 20, balancer 1, application 15, database 10. Reaching the end of the work takes 48 ms. Only the travel happens twice, so the total is 71, not 96.

In order or at the same time?

In sequence, add. In parallel, take the slowest. Only calls that do not need each other's answer can overlap.

Sizes

Numbers every engineer should know

Orders of magnitude

OperationAboutCompared with memory
L1 cache reference1 ns100 times faster
L2 cache reference4 ns25 times faster
Main memory reference100 ns1
Small random read, local SSD100 µs (16 µs on fast drives)1,000 times slower
Round trip in one zoneunder 1 ms, say 0.5 ms5,000 times slower
Seek on a spinning disk2 to 10 ms20,000 to 100,000 times slower
US east to US west, round tripabout 70 ms700,000 times slower
US east to Europe, round trip70 to 90 msabout 800,000 times slower
Rules of thumb, the same as in Numbers that decide. The last two match Microsoft's published medians between Azure regions (East US to West US 69 ms, to UK South 78, to West Europe 83).

The floor under distance

tRTT≥2d200,000 km/sNew York to London: 2×5,570200,000≈56 mst_{\text{RTT}} \ge \frac{2 d}{200{,}000\ \text{km/s}} \qquad \text{New York to London: } \frac{2 \times 5{,}570}{200{,}000} \approx 56\ \text{ms}
Light covers about 300 km per ms in empty space but only about 200 in glass fibre. Real cables are not straight, so measured values are higher.

Percentiles

Why averages lie

Sort 100 requests from fastest to slowest. P50 is the 50th, P95 the 95th, P99 the 99th. It is like lining up 100 test papers by score: you point at a position in the line, and one paper is still beyond the 99th.

Percentiles show it

  • P50 = 10 ms
  • P90 = 10 ms
  • P95 = 410 ms
  • P99 = 410 ms
  • One request in ten is 41 times slower. Now we know

Average: 50 ms

  • 90 requests took 10 ms
  • 10 requests took 410 ms
  • (90 × 10 + 10 × 410) / 100 = 50
  • Nobody waited 50 ms
  • Looks great, and hides the problem

Common percentiles

PercentileMeaningUsed for
P50, the medianHalf of the requests are this fast or fasterThe typical experience
P9090% areA general target
P9595% areA stricter target
P9999% areWatching the tail
P99.999.9% areCritical systems, large fan-out, very high volume
It counts requests, not people. Someone who makes 100 requests will probably meet the slowest 1% at least once.

How the tail reaches everyone

P(page is slow)=1−0.99nn=10: 9.6%n=100: 63.4%P(\text{page is slow}) = 1 - 0.99^{n} \qquad n = 10:\ 9.6\% \qquad n = 100:\ 63.4\%
A page that needs n independent answers, each slow 1% of the time, is as slow as its slowest answer.

Shape

Draw the distribution

Python
import mathcounts = [40, 60, 80, 95, 80, 60, 40, 30, 20, 15, 10, 8, 5, 3, 2, 1]total = sum(counts)def bucket_of(p):    rank, seen = math.ceil(total * p / 100), 0    for i, c in enumerate(counts):        seen += c        if seen >= rank:            return imarks = {bucket_of(p): f"P{p}" for p in (50, 95, 99)}for i, c in enumerate(counts):    print(f"{i * 30:3d}-{i * 30 + 30:3d} ms {'#' * (c // 3 or 1):32s}{marks.get(i, '')}")
Sixteen buckets of 30 ms. A fast hump and a long tail. The percentile is read from the running total.
Edit and run it in your browser

A histogram also shows two humps, for example cache hits and cache misses. No single number shows that.

Queues

Why a busy machine is a slow machine

Waiting grows near 100%

W=S1−ρS=10 ms:ρ=0.5→20,0.7→33,0.9→100,0.95→200 msW = \frac{S}{1 - \rho} \qquad S = 10\ \text{ms}:\quad \rho = 0.5 \to 20,\quad 0.7 \to 33,\quad 0.9 \to 100,\quad 0.95 \to 200\ \text{ms}
The simplest queueing model: one server, random arrivals, random work. SS is the time of the work alone and ρ\rho how busy the server is. Real systems differ in detail, not in shape.

Connection

The life of a request

A first HTTPS request, round trip 15 ms

5 + 15 + 15 + 35 + 15 = 85 ms. A connection kept open skips the first three: 35 + 15 = 50 ms.

Optimise

Six ways to cut it

A fast food counter answers quickly for three reasons: drinks are poured in advance, several cashiers work at once, and there is a shop near you. Those are caching, parallel work and edge locations.

Strategy, techniques, and the price

StrategyTechniquesWatch out
Caching: keep it near and fastRedis, CDN for static files, browser cache, query cacheOld data. See caching
Connection pooling: reuseDatabase pools, HTTP keep-alive, long-lived gRPC connectionsA pool that is too small makes a queue
Async work: do not waitMessage queues, background jobs, fire and forgetThe work is slower, only hidden. Fire and forget can lose it
Geography: be closerSeveral regions, CDN edges, DNS routingWrites still cross the distance
Compression: send lessgzip or Brotli, Protocol Buffers, image sizesCosts CPU; photos are already compressed
Indexing: look up fasterDatabase indexes, search indexes, Bloom filtersSlower writes, more storage

Quick wins

  1. 1

    Turn on compression

    Text such as HTML and JSON often shrinks by 60 to 80%. Measure yours.

  2. 2

    Reuse connections

    Saves the handshakes: one round trip for TCP and one for TLS 1.3.

  3. 3

    Use a CDN

    Files come from a place tens of milliseconds nearer.

Shorten the trip

A user in London asks a nearby CDN edge, 10 milliseconds away. Only on a miss does the edge ask the application server in Virginia, inside our system, 80 milliseconds away, which reads the database.
A hit costs 10 ms. A miss costs 90 ms and the work. Dashed means only on a miss. Example values.

Which part do I attack?

Three moves for the tail

  1. 1

    Timeout

    Stop waiting at a limit set from the usual P99, so one slow part does not hold everything.

  2. 2

    Hedge

    If no answer comes by the P95 time, ask a second copy and use the first answer. Adds about 5% load. Only for requests that are safe to repeat.

  3. 3

    Degrade

    Answer without the slow part: the page without its recommendations.

A hedged read

Two slow copies at the same moment are rare, so the first answer is usually quick.

Measure

Tools and good habits

What to measure with

KindExamplesAnswers
APM (monitoring of running apps)Datadog, New Relic, DynatraceHow slow, for whom, since when
TracingJaeger, Zipkin, AWS X-RayWhich part of this request
Load testingk6, Locust, JMeterWhat happens at twice the load

Measurement habits

  1. 1

    Measure at the client

    Only there are all network hops included. Keep the server's number too: the difference is the network and the queue in front of you.

  2. 2

    Track percentiles, not only averages

    P95 and P99 reveal the tail.

  3. 3

    Use histograms

    They show the whole shape and can be added across servers.

  4. 4

    Set alerts

    On a target such as P99 under 300 ms for 30 days, not on one slow request.

  5. 5

    Correlate with deployments

    Mark each release on the graph and regressions become visible.

  6. 6

    Keep failures apart

    Errors are often very fast, and would make the numbers look better.

Summary

The whole topic in one minute.

Latency is the time one request takes: travelling, waiting, working, storing. Write the parts down, add those in sequence, and take the slowest of those in parallel.

Describe it with P50, P95 and P99. To cut it, remove trips, shorten trips, wait less and do less before answering. Distance is the floor, and queues grow steeply when a machine is nearly full.

  • Latency is the time of one request: network, queue, work, disk.
  • In sequence add, in parallel take the slowest. Only travel counts twice.
  • Say P50, P95, P99. An average can be a time nobody had.
  • Fibre is about 200 km per ms: distance is a floor.
  • Keep machines near 70%, reuse connections, cache near, do the rest later.

Sources