A search page must come back within 200 ms at 50,000 queries a second. In our toy system, batching the reranker cuts its GPU fleet from 31,667 to 7,167. Hedging the slowest shard then brings the page inside the budget.
Pick a setup, then move the batch size and the cache. Watch the slow request, the GPU count and the price of 1,000 queries. Then we build each part from zero: retrieval, ranking, capacity, the tail, caching, batching, cost, launches and guardrails.
You need some Python and what an average and a probability are. We build the rest from zero.
A guide to what the role builds and the skills it needs. Every system number is an illustrative toy with its arithmetic shown. The one published idea we lean on is Dean and Barroso, The Tail at Scale (2013).
Illustrative toy: 50,000 queries a second and 100 candidates reranked per query. A reranker batch costs 3 ms plus 0.8 ms per pair, and GPUs run 60% busy at $2 an hour. Each of 64 index shards is slow (60 ms) one call in 100. The bar is the slow request: the one that the slowest 1% of users see.
Chapter 0
Follow one search query through the system and see which part each skill owns
A user types "noise canceling headphones under 200". About a fifth of a second later, ten results appear. In that time the system read the query and searched an index of billions of pages. It scored a hundred finalists with a neural network and checked the page for unsafe content.
The web-scale search and recommendations engineer builds and runs that path. A search engine ranks pages for a typed query. A recommender ranks items for a user who typed nothing. Both run the same shape: find candidates, rank them, serve the result fast and cheaply. Step through one query below.
Each press moves the query one stage. The box shows what goes in and what comes out. The ruler adds up the time.
Illustrative: the stage times are typical medians for a system like the one in the hero, not measurements of a real product.
The rerank stage takes 86 of the 156 ms. That is one reason the role is as much about systems as about models. The table maps each part to a skill and to the chapter that teaches it.
| Part of the system | Skill | Chapter |
|---|---|---|
| Find candidates | BM25, vectors, a vector index | 1, 2 |
| Rank them | a cascade of rankers, NDCG | 3 |
| Serve at scale | capacity, tail latency, caching, batching | 4 to 7 |
| Pay for it | cost per request | 7 |
| Change it safely | A/B tests, guardrails | 8, 9 |
Chapter 1
Score a page by the rare query words it holds, with a cap on repeats and a penalty for length
You cannot score billions of pages per query. So the system turns the index inside out. An inverted index maps each word to the list of pages that contain it. For a two-word query you read two lists, not the whole web.
Then you score the pages on those lists. Three ideas decide the score. A rare word says more than a common one. A word that repeats helps, but less each time. A long page holds more words by chance, so it gets a penalty. BM25 is the scoring rule that combines the three.
Name the parts first. Call the count of query word t in page d f. Call how rare the word is across all pages IDF(t), the inverse document frequency. Call the page length |d| and the average length avgdl. Two knobs, k1 and b, set the cap on repeats and the length penalty.
The score of q and d is the sum over t of IDF of t, times f times k-one plus one, over f plus k-one times one minus b plus b times d-length over avgdl.
For each query word, take its rarity IDF(t). Multiply by a repeat factor that grows with f but levels off near k-one + 1. Shrink it if the page is longer than avgdl. Add the words up.
Three pages: D1 "transformer attention mechanism" (3 words), D2 "attention deficit disorder treatment attention" (5), D3 "transformer architecture design transformer" (4). Query "transformer attention", so avgdl = 4 and each word is in 2 of 3 pages: IDF = log(1 + 1.5/2.5) = 0.47. D1 gets 0.47 × 2.2 / 1.975 = 0.52 per word, 1.05 in total. D3 gets 0.65 and D2 gets 0.60. D1 wins because it holds both words.
Blue is what one word adds to the score as it repeats. Grey is a plain count with no cap. Move the cap, the penalty and the page length.
IDF is fixed at 1 so the curve shows only the repeat and length factors.
Read D3 off the curve. It holds "transformer" twice, and its length is the average. The first copy adds a factor of 1.0; the second adds only 0.375 more. Matching both words beats repeating one.
Chapter 2
Turn queries and pages into vectors, then make a billion of them fit in memory
"Leaky faucet" and "dripping tap" share no words but mean the same thing. An embedding model turns a text into a list of numbers, a vector, so that texts with close meanings get close vectors. Retrieval by meaning then finds the page vectors nearest to the query vector.
A bi-encoder encodes the query and the page separately. So you encode every page once, offline, and at query time you encode only the query: one forward pass of a few milliseconds. A cross-encoder reads the query and the page together. It is more accurate but needs one pass per pair, so it only reranks finalists (Chapter 3).
Comparing the query with every page vector is too slow at a billion pages. An approximate nearest neighbour (ANN) index checks only a small part. A graph index (HNSW) walks from neighbour to neighbour. A cluster index (IVF) checks only the few clusters nearest the query. Both trade a little recall for a large speed-up.
Every vector must sit in memory. Memory is the vector count times the bytes per vector. With 1 billion pages at 128 numbers of 4 bytes each, that is 512 GB. Store each number in 1 byte (int8) and it drops to 128 GB. Product quantization (PQ) cuts each vector into 64 pieces and stores one byte per piece: 64 GB.
Pick how many pages, how long each vector is, and the format of each vector. The bars compare the four formats; the read-out counts the machines.
Illustrative: one machine holds 200 GB of index, with 2 copies of each shard. The count ignores graph links and IDs, which add more.
Production systems run both retrievers and merge the lists. BM25 catches exact strings such as an error code. Vectors catch paraphrases.
Chapter 3
Spend cheap models on many candidates and the expensive model on few, then score the order with NDCG
Retrieval returns about 1,000 candidates. The cross-encoder is the best judge, but it costs about 0.8 ms per pair in our toy. On 1,000 pairs that is most of a second. So ranking runs as a cascade: each stage is costlier and sees fewer items.
| Stage | Items in | Items out | Model |
|---|---|---|---|
| Retrieve | billions | 1,000 | BM25 and vectors |
| Light rank | 1,000 | 100 | gradient-boosted trees on features |
| Rerank | 100 | 20 | cross-encoder on a GPU |
| Assemble | 20 | 10 | rules: diversity, safety |
How do you score a ranked list? Users look at the top first, so a good page at position 1 is worth more than at position 5. Give each result a grade gi from human raters, 0 (useless) to 3 (perfect), where i is its position. DCG, discounted cumulative gain, adds the grades with a discount for depth.
DCG equals the sum over i of two to the g-i minus one, over log base two of i plus one.
For each position i, turn the grade g-i into a gain, divide by the discount and add. Then divide DCG by the DCG of the best possible order, the IDCG. That gives NDCG, from 0 to 1.
With made-up grades 3, 2, 3, 0, 1: the terms are 7, 1.89, 3.5, 0 and 0.39, so DCG = 12.78. The ideal order 3, 3, 2, 1, 0 gives IDCG = 13.35. NDCG = 12.78 / 13.35 = 0.957.
Each row is a result with its grade. Tap a row to swap it with the one above. Find the order that reaches 1.000.
Illustrative grades. Real teams average NDCG at 10 over thousands of rated queries.
Swap rows 2 and 3 of the start list and NDCG rises from 0.957 to 0.997. One swap near the top moves the score more than any change at the bottom.
Chapter 4
Turn traffic and time per request into a fleet size, and leave room so queues stay short
A launch plan says 50,000 queries a second at peak. How many retrieval servers do you order? The answer comes from one rule of queues: the number of requests in flight equals the arrival rate times the time each one takes. That is Little's law. At 50,000 a second and 0.2 s each, 10,000 requests are in flight at any moment.
Name the parts. Call the arrival rate λ and the time one request holds a machine W. Call the requests one machine serves at once c. Call the share of time you let a machine work u, the target busy share.
N equals lambda times W, over c times u.
Lambda times W is the work in flight. Divide by c to get busy machines. Divide by u to add spare room.
With made-up numbers: a retrieval shard takes W = 0.03 s, a server has c = 32 threads, and u = 0.6. N = 50,000 × 0.03 / (32 × 0.6) = 78.1, so order 79 servers per shard group.
Why not run machines at u = 1? A request that arrives at a busy machine waits in a queue. In the simplest queue model the mean wait is u/(1 − u) times the service time. At 60% busy that is 1.5 times; at 90% it is 9 times; at 95% it is 19 times.
The curve is queue wait against the busy share. The dot is your target. Push it right and watch the wait climb.
Illustrative: c = 32 requests per server. The wait curve is the M/M/1 queue, the simplest model; real queues differ, but the steep climb near 100% is the same.
Chapter 5
See why a query that waits for 64 shards is often slow, and how a second request fixes it
The index is too big for one machine, so it is cut into shards. A query goes to every shard and waits for all the answers. This is fan-out, also called scatter-gather. The query is as slow as its slowest shard.
Each shard is fast most of the time. Now and then one pauses, for a memory clean-up or a busy disk. Call the chance that one shard call is slow p and the number of shards n. What is the chance that the whole query is slow?
P-slow equals one minus, one minus p, to the n.
The query is fast only if all n shards are fast. Multiply the chance 1 − p by itself n times. Whatever is left over is P-slow.
With p = 0.01 and n = 64: 0.99 to the 64 is 0.526, so P-slow = 0.474. A pause that hits 1 shard call in 100 slows 47 queries in 100.
Dean and Barroso described the fix in The Tail at Scale: a hedged request. Send a shard call. If no answer comes within a short delay, send the same call to a copy of that shard and take whichever answers first. The call is slow only if both copies are slow.
Each dot is one query. Red means it waited for a slow shard. Add shards, then turn on hedging.
Illustrative: a fast call takes 10 ms, a slow one 60 ms, and copies are slow independently. With hedging, the slow request costs about 15 + 10 = 25 ms.
Hedging costs little. The second call fires only for calls still waiting at 15 ms, which is the 1% that are slow. So the shards see about 1% more calls, and P-slow falls from 0.474 to 0.0064.
Chapter 6
Answer repeat queries from memory, and see how much a cache of a given size can catch
"weather", "news" and "facebook" arrive thousands of times a minute. Running the full pipeline for each one repeats the same work. A result cache stores the finished page for a query and serves it again. A hit is a query found in the cache; a miss runs the pipeline.
Query traffic leans hard to one side. A few queries make up a large share, and a long tail of queries each come rarely. A common model is Zipf's law: the query of rank k comes with frequency proportional to 1/ks. The larger s is, the more the head dominates, and the more a small cache catches.
Name the parts. Call the hit rate h, the time of a hit thit and the time of a miss tmiss.
T-bar equals h times t-hit, plus one minus h times t-miss.
Weight each path by how often it happens. A share h of queries take t-hit; the rest take t-miss. Add the two.
With made-up numbers: h = 0.2, t-hit = 2 ms, t-miss = 120 ms. T-bar = 0.2 × 2 + 0.8 × 120 = 96.4 ms. The GPUs also do 20% less work.
The curve is the hit rate for each cache size. Slide the size, then switch the traffic shape.
Illustrative: 100 million distinct queries following Zipf's law, with the most frequent ones cached. Real traffic has more one-off queries than this model, so real hit rates are lower.
Ten times the cache buys a slow climb, not ten times the hits. With s = 0.8, going from 10,000 to 100,000 entries lifts h from 13.9% to 23.4%. A semantic cache also catches near-repeats by vector distance, with a risk of wrong answers.
Chapter 7
Feed the reranker many pairs at once, then turn GPU time into dollars per 1,000 queries
Each call to the GPU pays a fixed cost before it does any work: it launches the kernels and reads the model weights from memory. Send one pair per call and you pay that cost 100 times per query. Send 64 pairs in one call, a batch, and you pay it twice.
Name the parts. Call the fixed time per batch t0, the extra time per pair t1 and the batch size B.
X equals B over t-zero plus t-one times B.
One call takes t-zero plus t-one per pair. It scores B pairs. Divide B by the call time.
With the toy numbers: at B = 1, X = 1 / 3.8 ms = 263 pairs a second. At B = 64, X = 64 / 54.2 ms = 1,181 pairs a second, 4.5 times more. X can never pass 1 / t-one = 1,250.
Now price it. Call the GPU's price per hour r, the GPU seconds one query uses T, and the target busy share u from Chapter 4.
C equals one thousand times r times T, over thirty-six hundred times u.
Divide r by 3,600 to get the price of one GPU second. Multiply by the T seconds a query uses, and by 1,000 queries. Divide by u, because you also pay for idle time.
With made-up r = $2: 100 pairs in batches of 64 make 2 calls, so T = 2 × 3 + 100 × 0.8 = 86 ms. C = 1000 × 2 × 0.086 / (3600 × 0.6) = $0.080. One pair per call gives T = 380 ms and C = $0.352.
Purple is pairs per second. Grey is how long one batch takes. Grow the batch, then change the GPU price.
Illustrative reranker: 3 ms per call plus 0.8 ms per pair, 100 pairs per query, u = 0.6. We made up the prices; check your provider's price list.
Fleet size follows from T too. At 50,000 queries a second, 50,000 × 0.086 = 4,300 GPUs are busy at every moment. At u = 0.6 you pay for 7,167.
Chapter 8
Gate a change offline, then measure it on real users with enough of them to trust the result
A new reranker wins offline: NDCG rises from 0.712 to 0.719. Does it help users? Offline grades are a proxy. An A/B test sends a random share of users to the new system (B) and keeps the rest on the old one (A). Then it compares a user metric, such as the share of searches that end in a click.
How many users do you need? Name the parts. Call the baseline click rate p and the smallest lift worth finding δ. Two numbers come from the normal curve: zα/2 sets the false-alarm rate, and zβ sets the chance of catching a real lift.
n equals two times, z-alpha-over-two plus z-beta, squared, times p times one minus p, over delta squared.
The noise in each arm is p(1 − p). The lift delta must stand clear of that noise by the two z margins. Halve delta and you need four times the users.
With made-up p = 0.30 and a 1% relative lift, delta = 0.003: n = 2 × 7.85 × 0.21 / 0.000009 = 366,281 users per arm. At 200,000 users a day per arm that is 2 days, so run a full week.
The curve is users per arm for each lift. Drag the lift down and watch the count climb.
Standard two-sided test for two rates, 5% false alarms, 80% power. Users per day means per arm.
The formula assumes independent units. Randomize by user, not by query: one user's queries move together. Also track guardrail metrics that must not get worse, such as p99 latency and cost per query. See experiment design for the full method.
Chapter 9
Block unsafe queries and results with a classifier, and count what each threshold costs at web scale
Some queries ask for harm. Some pages in the index are scams or worse. A guardrail is a check on the path that can block or demote a result. Most guardrails are classifiers. A model gives each query or page a score from 0 (safe) to 1 (harmful). A threshold decides what to block.
Scale changes the arithmetic. At 50,000 queries a second, a day holds 4.32 billion queries. Say 0.2% are harmful. A classifier that wrongly blocks 0.1% of safe queries, its false positive rate, blocks 4.32 billion × 0.998 × 0.001 = 4.3 million good queries a day.
Warm is safe queries and grey is harmful ones, by classifier score. The guardrail blocks everything right of the line; red shows the mistakes. Move the line.
Illustrative classifier: safe scores centre on 0.25, harmful on 0.75, both with spread 0.09. 50,000 queries a second, 0.2% harmful. The bell curves are not drawn to scale: safe queries are 499 times more common.
No threshold makes both counts zero. So teams pick per harm. For the worst harms they block at a low threshold and accept wrong blocks. For mild harms they demote a result in place of blocking it.
| Design choice | What to do |
|---|---|
| Where it runs | in parallel with retrieval, so it adds no time to the path |
| When it fails | fail closed for severe harms (block), fail open for mild ones (serve) |
| Kill switch | a flag that removes a bad result everywhere in minutes |
| Monitoring | block rate per hour, with an alarm on a sudden jump |
Chapter 10
Keep the terms, the numbers, a checklist and the core arithmetic in one place
The role is one loop: find candidates, rank them, and serve them inside a time and money budget. Change the system only when a test proves it helps and the guardrails hold.
| Term | Meaning | Toy number on this page |
|---|---|---|
| p99 latency | the time 99 of 100 requests beat | 171 ms batched and hedged |
| BM25 | word match score with a repeat cap and a length penalty | k-one 1.2, b 0.75 |
| Vector index memory | vectors × bytes per vector | 512 GB fp32, 64 GB PQ |
| NDCG | order quality, 0 to 1 | 0.957 |
| Fleet size | λW / (cu) | 79 retrieval servers |
| Fan-out tail | 1 − (1 − p)n | 47.4%, hedged 0.64% |
| Cache | h thit + (1 − h) tmiss | 96.4 ms at h = 0.2 |
| Batch throughput | B / (t0 + t1B) | 1,181 pairs/s at B = 64 |
| Cost per 1,000 | 1000 rT / (3600u) | $0.080 |
| A/B sample | users per arm | 366,281 |
| Wrong blocks | queries a day × FPR | 4.3 million at 0.1% |
pythonimport math from statistics import NormalDist def fleet(qps, w_s, slots, util): # Little's law with headroom return math.ceil(qps * w_s / (slots * util)) def p_slow(p, shards, hedged=False): # fan-out tail q = p * p if hedged else p # hedged: both copies slow return 1 - (1 - q) ** shards def gpu_seconds(pairs, batch, t0=0.003, t1=0.0008): return math.ceil(pairs / batch) * t0 + pairs * t1 def cost_per_1k(rate_hr, gpu_s, util, hit=0.0): # misses pay GPU time return 1000 * rate_hr * gpu_s * (1 - hit) / (3600 * util) def ab_users(p, delta, alpha=0.05, power=0.8): z = NormalDist().inv_cdf return math.ceil(2 * (z(1 - alpha / 2) + z(power)) ** 2 * p * (1 - p) / delta ** 2) T = gpu_seconds(100, 64) # 0.086 s print(fleet(50_000, T, 1, 0.6)) # 7167 GPUs print(round(p_slow(0.01, 64), 3)) # 0.474 print(round(cost_per_1k(2.0, T, 0.6), 4)) # 0.0796 print(ab_users(0.30, 0.003)) # 366282 (366,281.05 rounded up)
Now press Present or Teach and explain from memory why 64 shards make slow pages common, and how batching cuts the cost. Then go back to the hero and fit the query inside 200 ms again, saying which chapter each control comes from.