Courses / System Design Interview / Chapter 20
Module 4 · Building Blocks III: Limits, Storage and Search · Chapter 20 of 49
Distributed Search
Builds on Non-Functional Requirements: Availability, Scale, Latency and More, Building Blocks: The Parts Every Design Reuses, Databases: Choosing, Replicating and Partitioning and Design a Distributed Key-Value Store. Next up: Distributed Logging.
Part 1 · What search has to do
Finding, ranking, keeping up
A food app with 10 lakh recipes, a college site with every past paper, a shop with lakhs of products: all of them need a search box that answers in a fraction of a second. Search means finding the documents that match a query, putting the best ones first, and doing it while the data keeps changing.
A document is the unit that search returns: a recipe, a product, a page. It can have several fields, such as a title and a description. A query is what the user types. The search system returns a ranked list of document ids, and the caller then fetches the details it wants to show.
Why not ask the database with WHERE description LIKE '%paneer%'? A pattern with a leading wildcard cannot use an ordinary index, so the database reads every row. It has no idea which match is better. Depending on its settings, it may also treat "paneer" and "Paneer" as different words. At 10 lakh documents and many queries a second, the scan is too slow, and the unranked answer is not useful anyway.
A search system is built around three requirements that a plain database does not give you.
| Requirement | Meaning | What goes wrong without it |
|---|---|---|
| Recall | Documents that should match are found | The user sees "no results" for something that exists |
| Ranking | The most relevant documents come first | The best answer is on page 40 |
| Freshness | New and changed documents become searchable soon | A product added this morning cannot be found tonight |
Recall is the share of the relevant documents that the search finds. Precision is the share of the returned documents that are relevant. They pull against each other: returning everything has perfect recall and poor precision. Relevance is how well a document answers the query, and a ranking function turns it into a number so that documents can be sorted.
Two phases, and why one machine is not enough
Every search engine splits its work into two phases. At index time, when a document is added or changed, the system analyses its text and updates a data structure built for fast lookup. At query time, the system uses that structure to find and score the matching documents. Work done once at index time saves work on every query.
The data structure is the inverted index, a map from each word to the documents that contain it. Ranking is a scoring function applied to the matches. For a large catalogue the index does not fit on one machine, so both have to keep working when it is spread over many.
The pressures that force a distributed design are the usual two. The index may be bigger than one machine's disk or memory, and the query load may be more than one machine can answer. Both are solved the way other building blocks solve them: split the data into pieces, called shards, and keep copies of the pieces, called replicas.
Search adds a twist. A query is not about one key, so it cannot be sent to one shard. It must be asked of many shards, and the answers have to be combined and ranked again. That is why tail latency matters so much here: the slowest shard decides how long the user waits, a point the last lesson returns to.
| Term | Meaning |
|---|---|
| Document | The unit a search returns |
| Recall | The share of relevant documents that are found |
| Precision | The share of returned documents that are relevant |
| Index time | When documents are analysed and added to the index |
| Query time | When a query is matched and scored against the index |
| Shard | One slice of the index, held on one machine |
Part 2 · The inverted index
Terms to documents
A book has an index at the back: for each important word, the pages where it appears. An inverted index is the same idea for documents. For each term, which is a word after processing, it stores the list of documents that contain it. That list is the term's postings list, and each entry in it is a posting: a document id, and usually how many times the term appears there, called the term frequency.
Answering a query then needs no scan. To find the documents with paneer and tikka, fetch the postings list of each term and keep the document ids that appear in both. The work depends on the length of those two lists, not on the size of the whole collection.
Before terms go into the index, the text goes through analysis. It breaks the text into tokens, which is tokenising, and makes them comparable, which is normalising. The simplest analysis lower-cases everything and splits on anything that is not a letter or a digit. Real engines add more: removing very common words, reducing words to a stem so that chillies and chilli meet, and handling accents and other scripts. The key rule is that the same analysis must run on the documents and on the query. If it does not, a term in the query never equals a term in the index.
Analysis decides what the user can find, so it is a product decision. If 10 is dropped as a stop word, a search for 10 min recipes loses meaning. If words are not stemmed, a search for recipe misses recipes.
A small index in code
The corpus is 200 made-up recipe lines, generated with a fixed random seed so that the run can be repeated. Each has a style, a dish, two filler words and one to five cooking steps. The code below tokenises, builds the postings, and answers an AND query by intersecting sets.
import random DISHES = ["paneer tikka", "dal tadka", "masala dosa", "veg biryani", "aloo paratha", "rajma chawal", "idli sambar", "palak paneer", "chole bhature", "curd rice", "upma", "poha"] STYLES = ["spicy", "mild", "crispy", "creamy", "tangy", "smoky"] STEPS = ["fry the onions", "add the spices", "simmer for ten minutes", "roast the cumin", "mix in the curd", "garnish with coriander", "serve hot with chutney", "add a little salt", "heat the oil"] FILLER = ["recipe", "curry", "home", "style", "easy", "quick", "dinner"] def make_docs(n=200, seed=3): rng = random.Random(seed) docs = {} for i in range(1, n + 1): head = [rng.choice(STYLES), rng.choice(DISHES)] head += rng.sample(FILLER, 2) steps = [rng.choice(STEPS) for _ in range(rng.randint(1, 5))] docs[i] = " ".join(head) + ": " + ", ".join(steps) return docs
corpus.py: the 200 made-up recipe lines, repeatable with the seed
import re from collections import defaultdict def tokenize(text): return re.findall(r"[a-z0-9]+", text.lower()) def build(docs): postings = defaultdict(dict) # term -> {doc id: term count} lengths = {} for doc_id, text in docs.items(): tokens = tokenize(text) lengths[doc_id] = len(tokens) for t in tokens: postings[t][doc_id] = postings[t].get(doc_id, 0) + 1 return postings, lengths def search_all(postings, terms): # documents holding every term sets = [set(postings.get(t, {})) for t in terms] return sorted(set.intersection(*sets)) if sets else []
index.py: tokenise, build postings, intersect
build returns the postings and the length of every document in tokens. Lengths are not needed for matching, but the ranking in the next lesson uses them.
The run prints one document, shows how a messy string is tokenised, counts the terms, and shows a few postings for paneer. It then answers paneer tikka from the index and checks the answer against a full scan of all 200 documents. It was run with Python 3.12.10.
import sys from corpus import make_docs from index import tokenize, build, search_all print(sys.version.split()[0]) docs = make_docs() print("doc 14:", docs[14]) print("tokens:", tokenize("Spicy Paneer-Tikka, ready in 10 min!")) postings, lengths = build(docs) print("documents:", len(docs), " distinct terms:", len(postings)) p = postings["paneer"] print("postings for 'paneer':", dict(list(p.items())[:5]), "...") print(" 'paneer' is in", len(p), "documents") hits = search_all(postings, tokenize("paneer tikka")) print("paneer AND tikka:", len(hits), "documents:", hits[:8]) words = {"paneer", "tikka"} scan = [d for d, t in docs.items() if words <= set(tokenize(t))] print("a full scan agrees:", scan == hits) print("the scan read all", len(docs), "documents")
l2_run.py: build the index and query it
What the run shows, and the quiz
The tokeniser turned Spicy Paneer-Tikka, ready in 10 min! into seven lower-case tokens and dropped the punctuation, so the hyphen split Paneer-Tikka into two terms. There are 200 documents and only 58 distinct terms, because the generator draws from small word lists. A real collection has far more terms than this, and the postings lists of common terms are very long.
The postings of paneer are a map from document id to count: {3: 1, 5: 1, 7: 1, 14: 1, 39: 1} and so on, 35 documents in all. The query paneer tikka returned 15 documents by intersecting two lists, and the full scan, which had to read all 200 documents and tokenise each, returned the same 15. The result is the same, and only the cost differs. With 200 documents the difference is invisible. With 20 crore documents, one is a lookup and the other is not practical.
Postings lists are kept sorted by document id. Sorted lists can be intersected by walking both at once, without building sets, and they compress well, because consecutive ids differ by small numbers. That is why real indexes store the gaps between ids and not the ids themselves.
What is stored in a posting, and what is a postings list?
- A posting is a document id plus the term's count in that document.
- A postings list is all the postings of one term.
A query is tokenised with lower-casing, but the documents were indexed without it. What happens to a search for Paneer?
- The query term
paneerand the indexed termPaneerdiffer, so the search finds nothing. - Documents and queries must go through the same analysis.
The run found 15 documents for paneer tikka both ways. Why prefer the index?
- The index reads only two postings lists, while the scan reads and tokenises every document.
- The gap grows with the collection.
Part 3 · Ranking with BM25
Why matching is not enough
A query for paneer salt matches many documents. Some mention the words once in a short line, and others repeat a word inside a long page. Ranking decides the order, and the order is what users judge a search by.
A first attempt is to count: score a document by how many times the query terms appear in it. It is easy to compute, and it goes wrong in two ways. First, a word that appears in almost every document tells you nothing. A document that says curry three times is not special when the whole collection is about curries. Second, a long document has more chances to repeat a word, so counting favours length.
TF-IDF fixes the first problem. It multiplies the term frequency (tf) by the inverse document frequency (idf), a weight that is high for rare terms and low for common ones. BM25 is a refinement that also fixes the second problem. It is the ranking function in Lucene's BM25Similarity class. Lucene is an open-source search library that other search engines are built on.
BM25 has two settings. The parameter k1 controls saturation: how quickly extra occurrences of a term stop adding to the score. The parameter b controls length normalisation: how strongly a long document is penalised. The Lucene documentation gives the defaults as k1 = 1.2 and b = 0.75, which this lesson uses.
The score of a document for a query is a sum over the query terms. Here N is the number of documents, n is how many documents contain the term, len is the document's length in tokens, and avglen is the average length.
score(doc) = sum over query terms t of idf(t) * boost(t, doc) idf(t) = ln(1 + (N - n + 0.5) / (n + 0.5)) boost = tf * (k1 + 1) / (tf + k1 * (1 - b + b * len / avglen))
The classic BM25 form. Engines differ in small constants.
The idf line is the one the Lucene documentation gives for its BM25 class. Implementations differ slightly in the term-frequency part, so another engine may print different scores for the same data, with a similar order.
The code, and a ranking that changes
import math from index import tokenize K1, B = 1.2, 0.75 def idf(n_docs, df): return math.log(1 + (n_docs - df + 0.5) / (df + 0.5)) def bm25(postings, lengths, terms, k1=K1, b=B, stats=None, df=None): avg = sum(lengths.values()) / len(lengths) n, avg = stats or (len(lengths), avg) scores = {} for t in terms: plist = postings.get(t, {}) w = idf(n, df[t] if df else len(plist)) for d, tf in plist.items(): norm = tf + k1 * (1 - b + b * lengths[d] / avg) scores[d] = scores.get(d, 0) + w * tf * (k1 + 1) / norm return sorted(scores.items(), key=lambda x: (-x[1], x[0])) def raw_count(postings, terms): scores = {} for t in terms: for d, tf in postings.get(t, {}).items(): scores[d] = scores.get(d, 0) + tf return sorted(scores.items(), key=lambda x: (-x[1], x[0]))
bm25.py: idf, BM25 and a raw-count ranking
The run uses the same 200 documents and the query paneer salt. It first prints the idf of each term and the average document length. It then lists the top five by raw count, with ties broken by document id, next to the top five by BM25.
from corpus import make_docs from index import tokenize, build from bm25 import bm25, raw_count, idf docs = make_docs() postings, lengths = build(docs) avg = sum(lengths.values()) / len(lengths) n = len(docs) print(f"documents {n}, average length {avg:.1f} tokens") for t in ("paneer", "salt"): df = len(postings[t]) print(f"{t!r}: in {df} documents, idf {idf(n, df):.2f}") terms = tokenize("paneer salt") print("raw count (ties by id) against BM25 (k1=1.2, b=0.75)") raw = raw_count(postings, terms)[:5] bm = bm25(postings, lengths, terms)[:5] for (d1, s1), (d2, s2) in zip(raw, bm): print(f"raw: doc {d1:3} score {s1} " f"bm25: doc {d2:3} score {s2:.2f} len {lengths[d2]}") print("first BM25 hit:", docs[bm[0][0]]) top = raw[0][0] print(f"first raw hit: doc {top}, {lengths[top]} tokens, " f"salt x{postings['salt'][top]}")
l3_run.py: raw counts against BM25
documents 200, average length 14.9 tokens 'paneer': in 35 documents, idf 1.73 'salt': in 51 documents, idf 1.36 raw count (ties by id) against BM25 (k1=1.2, b=0.75) raw: doc 128 score 3 bm25: doc 82 score 3.70 len 9 raw: doc 5 score 2 bm25: doc 89 score 3.09 len 15 raw: doc 48 score 2 bm25: doc 169 score 3.09 len 15 raw: doc 60 score 2 bm25: doc 128 score 3.05 len 23 raw: doc 65 score 2 bm25: doc 5 score 2.93 len 17 first BM25 hit: creamy paneer tikka dinner curry: add a little salt first raw hit: doc 128, 23 tokens, salt x2
Reading the ranking, and saturation
paneer is in 35 of the 200 documents and salt in 51, so paneer is the rarer term and has the higher idf, 1.73 against 1.36. A match on paneer counts for more.
The two rankings disagree from the first line. Raw counting puts document 128 first: it has 23 tokens and repeats salt twice, so its count is 3. BM25 gives it 3.05 and places it fourth. BM25 puts document 82 first, a document of only 9 tokens that has each term once. A short document that contains both words is a tighter match than a long one that mentions them in passing, and length normalisation expresses that.
The second run shows saturation. It prints how much a term contributes for a document of average length, as its count grows.
k1 = 1.2 print("term count -> contribution (document of average length)") for tf in (1, 2, 3, 5, 10, 20, 50): print(f"{tf:3} -> {tf * (k1 + 1) / (tf + k1):.2f}") print(f"the ceiling is k1 + 1 = {k1 + 1:.1f}")
l3b_run.py: the effect of k1 on repeated terms
term count -> contribution (document of average length) 1 -> 1.00 2 -> 1.38 3 -> 1.57 5 -> 1.77 10 -> 1.96 20 -> 2.08 50 -> 2.15 the ceiling is k1 + 1 = 2.2
One occurrence contributes 1.00 and ten contribute 1.96, not ten times as much. The contribution can never pass k1 + 1, which is 2.2 here, so repeating a word 50 times in a page cannot beat a document that has the word once and matches the other query terms. That also limits the damage from keyword stuffing.
Why does a rare term get a higher idf than a common one?
- A rare term separates documents better, since few contain it.
- A term in nearly every document tells you almost nothing about relevance.
In the run, document 128 had the highest raw count but ranked fourth under BM25. Why?
- It is long, 23 tokens against an average of 14.9, and BM25 reduces the score of long documents.
- Document 82 is short and contains both terms.
Part 4 · Building and updating the index
Segments that are never edited
The inverted index is built for fast reading. Changing a postings list in place is awkward, because a new document touches the list of every term it contains, and readers are searching at the same time. The Lucene file-format documentation says an index may be composed of segments, each a fully independent index, and that an index evolves by creating new segments for new documents and by merging existing ones. In the design described here a segment is never edited after it is written, so updates and deletions go through new data.
A segment is a small, complete, immutable index of a batch of documents: once it is written, it is never changed. New documents wait in an in-memory buffer. At a refresh, the buffer is turned into a new segment, and from then on its documents are searchable. A search runs against every segment and combines the answers.
That gives the freshness property from the first lesson: a document becomes searchable at the next refresh, not instantly. This is often called near real-time search. The delay is a setting, because refreshing more often makes documents appear sooner and produces more small segments.
Immutability makes deletes and updates indirect. A deleted document is not removed from its segment: its id goes into a record of deleted documents, a tombstone as in the key-value store chapter, and searches skip it. An update is a delete of the old version plus an add of the new one.
Left alone, segments pile up, and each search has to visit all of them. The system therefore merges segments in the background. A merge reads several segments, skips the tombstoned documents, and writes one larger segment. Only then are the old segments dropped, and the deleted documents really leave the disk.
Two practical points follow. First, the buffer lives in memory, so a crash would lose the documents in it. Search engines therefore typically also append each change to a log on disk, and rebuild the buffer from that log after a restart. Second, the number of segments is a trade-off. Every search must look up each term in every segment, so many small segments make queries slower, while merging many large segments costs disk and processing time. A merge policy decides which segments to combine and when, and a segment that is mostly tombstones is a good candidate.
A segmented engine in code
from index import build, search_all, tokenize class Segment: """An immutable mini index, never changed after it is built.""" def __init__(self, docs): self.docs = dict(docs) self.postings, self.lengths = build(self.docs) def entries(self): return sum(len(p) for p in self.postings.values()) class Engine: def __init__(self): self.buffer, self.segments, self.deleted = {}, [], set() def add(self, doc_id, text): self.buffer[doc_id] = text # not searchable yet
segments.py, part 1: a segment and the engine's buffer
def refresh(self): # flush the buffer if self.buffer: self.segments.append(Segment(self.buffer)) self.buffer = {} def delete(self, doc_id): self.deleted.add(doc_id) # a tombstone only def search(self, query): terms, hits = tokenize(query), [] for seg in self.segments: hits += [d for d in search_all(seg.postings, terms) if d not in self.deleted] return sorted(hits) def merge(self): live = {d: t for s in self.segments for d, t in s.docs.items() if d not in self.deleted} self.segments, self.deleted = [Segment(live)], set()
segments.py, part 2: refresh, delete, search and merge
search asks each segment and drops any hit that is in the deleted set. merge rebuilds one segment from the live documents of all segments and clears the tombstones.
Run: refresh, delete, merge
The run adds the 200 documents in four batches with a refresh after each, which makes four segments. It then adds one more document without refreshing, refreshes, deletes five of the hits, and merges.
from corpus import make_docs from segments import Engine docs = make_docs() eng = Engine() ids = sorted(docs) for start in range(0, 200, 50): # four batches for d in ids[start:start + 50]: eng.add(d, docs[d]) eng.refresh() size = lambda: sum(s.entries() for s in eng.segments) print("segments:", len(eng.segments), " posting entries:", size()) before = eng.search("paneer tikka") print("paneer tikka:", len(before), "hits") eng.add(201, "fresh paneer tikka special: add the spices") print("new document before refresh:", len(eng.search("paneer tikka"))) eng.refresh() print("after refresh:", len(eng.search("paneer tikka")), " segments:", len(eng.segments)) for d in before[:5]: eng.delete(d) print("after 5 deletes:", len(eng.search("paneer tikka")), " posting entries:", size()) eng.merge() print("after merge: segments", len(eng.segments), " hits", len(eng.search("paneer tikka")), " posting entries:", size())
l4_run.py: four segments, a new document, deletes, a merge
segments: 4 posting entries: 2556 paneer tikka: 15 hits new document before refresh: 15 after refresh: 16 segments: 5 after 5 deletes: 11 posting entries: 2563 after merge: segments 1 hits 11 posting entries: 2507
Four segments hold 2,556 posting entries between them, and paneer tikka has 15 hits. The new document, which also matches, is not found before the refresh and is found after it: 16 hits and five segments. Five deletes bring the hits to 11, but the posting entries went up to 2,563: the deletes removed nothing from the segments, and the refresh had added the seven entries of the new document. The merge leaves one segment with the same 11 hits and 2,507 entries, and the tombstones are gone.
The cost of this design is write work in the background. Merging rewrites data, and a store that updates many documents spends much of its effort on it. In return, readers never wait for writers, segments can be cached, and a crash cannot leave a half-edited postings list.
A document is added and a search runs immediately. Why might it not be found?
- The document is still in the buffer. It becomes searchable at the next refresh, when a segment is written.
Part 5 · Sharding and scatter-gather
Splitting the index
One machine cannot hold or serve an index of unlimited size, so the index is cut into shards. The Elasticsearch documentation describes a shard as a self-contained Lucene index that holds a subset of an index's documents. Each document lives in one primary shard. The number of primary shards is fixed when the index is created, so it has to be chosen with growth in mind. Changing it later means creating a new index.
There are two ways to cut an index.
- Partition by document. Each shard holds whole documents and builds a full index for them. A document goes to a shard by hashing its id. Every shard can score its own documents completely.
- Partition by term. Each shard holds the postings lists of some terms, for all documents. A query goes only to the shards that own its terms.
Partitioning by document is the usual choice, because a query is then answered by each shard working alone on its own data. Partitioning by term seems efficient, since a query touches only a few shards, but a multi-word query must bring long postings lists together from different shards to intersect them. The lists of common words are huge, so the network cost can be large.
With document partitioning, a search runs as scatter-gather, as in the databases chapter. A coordinator receives the query, sends it to every shard, which is the scatter, and each shard returns its own top k results. The coordinator merges those lists, keeps the best k overall, and returns them, which is the gather. It works because, when scores are comparable across shards, the overall top k is contained in the union of the shards' top k.
Why local scores can mislead
There is a catch. BM25 uses collection statistics: the number of documents, the average length, and how many documents contain each term. Each shard knows only its own. A term that is rare overall may look common in one shard, and the scores that shards return are then not on one scale.
Watch for the same query reaching every shard at once
Read it as steps
The coordinator sends one query to three shards and merges their top results.
The code splits the 200 documents into three shards by a hash of the id and compares three answers to paneer salt: one big index as the reference, scatter-gather with each shard's local statistics, and scatter-gather where the shards are given the global statistics. It uses the shards.py module below.
import hashlib, heapq from index import build, tokenize from bm25 import bm25 def shard_of(doc_id, n_shards): h = hashlib.sha256(str(doc_id).encode()).digest() return int.from_bytes(h[:4], "big") % n_shards class Shard: def __init__(self, docs): self.postings, self.lengths = build(docs) def top_k(self, terms, k, stats=None, df=None): scored = bm25(self.postings, self.lengths, terms, stats=stats, df=df) return scored[:k] def split(docs, n_shards): parts = [{} for _ in range(n_shards)] for d, text in docs.items(): parts[shard_of(d, n_shards)][d] = text return [Shard(p) for p in parts] def merge(lists, k): # lists of (doc, score) flat = [x for lst in lists for x in lst] return heapq.nsmallest(k, flat, key=lambda x: (-x[1], x[0]))
shards.py: shard routing, a shard, and the merge
Run: local against global statistics
from corpus import make_docs from index import build, tokenize from bm25 import bm25 from shards import split, merge docs = make_docs() terms, K = tokenize("paneer salt"), 5 postings, lengths = build(docs) ref = [d for d, _ in bm25(postings, lengths, terms)[:K]] print("one big index :", ref) shards = split(docs, 3) print("docs per shard:", [len(s.lengths) for s in shards]) local = merge([s.top_k(terms, K) for s in shards], K) print("local stats :", [d for d, _ in local]) df = {t: len(postings[t]) for t in terms} # global statistics stats = (len(docs), sum(lengths.values()) / len(lengths)) glob = merge([s.top_k(terms, K, stats, df) for s in shards], K) print("global stats :", [d for d, _ in glob]) print("global equals one index:", [d for d, _ in glob] == ref)
l5_run.py: three ways to answer one query
one big index : [82, 89, 169, 128, 5] docs per shard: [57, 64, 79] local stats : [82, 128, 48, 89, 169] global stats : [82, 89, 169, 128, 5] global equals one index: True
The three shards hold 57, 64 and 79 documents, an uneven split that hashing produces with so few documents. Scatter-gather with local statistics returned a different top five from the single index. It had document 48 in place of document 5, and put the others in a different order. Each shard computed its own idf and average length, so a document's score depended on which shard it landed in.
When the coordinator supplied the global document count, average length and term counts to every shard, the merged answer matched the single index exactly. Engines handle the issue in different ways, for example by gathering statistics from the shards before scoring, or by accepting small differences, which shrink as shards grow bigger and more alike.
The last run compares the cost of the two partitionings for the same query.
import hashlib from corpus import make_docs from index import build, tokenize docs = make_docs() postings, _ = build(docs) N = 3 def term_shard(term): h = hashlib.sha256(term.encode()).digest() return int.from_bytes(h[:4], "big") % N terms = tokenize("paneer salt") print("sharded by document: the query goes to all", N, "shards") print("sharded by term:") shipped = 0 for t in terms: n = len(postings[t]) shipped += n print(f" {t!r} lives on shard {term_shard(t)}, {n} postings") print("postings to bring together to intersect:", shipped)
l5b_run.py: which shards a query touches
sharded by document: the query goes to all 3 shards sharded by term: 'paneer' lives on shard 0, 35 postings 'salt' lives on shard 1, 51 postings postings to bring together to intersect: 86
Part 6 · Replicas, tail latency and freshness
Replicas
A shard on one machine is a single point of failure. Each shard therefore has replicas, which are copies on other machines. The Elasticsearch documentation says a replica is a duplicate of a primary shard, that replicas add redundancy against hardware failure, and that they also increase capacity to serve read requests such as searches. It also says the number of replicas can be changed at any time, without interrupting indexing or queries.
This makes replicas the way to scale read traffic. If a search for a shard can be answered by any of its three copies, three machines share that load. Adding replicas raises query capacity, and adding shards raises the amount of data the index can hold. They solve different problems.
Writes go to the primary first and are copied to the replicas. A replica can therefore be a little behind, so two searches a moment apart may be answered by different copies and see slightly different results. For a product search this is acceptable. For a page that must show a change the user has just made, the caller can send its search to the primary or wait for the next refresh.
The slowest shard decides
Scatter-gather has a cost: the coordinator can answer only when the slowest shard has answered. If each shard is slow one time in a hundred, the chance that some shard of n is slow is 1 minus 0.99 to the power n. With three shards that is about 3 percent of queries. With 100 shards it is about 63 percent, so most queries wait for a slow shard. The non-functional chapter introduced this effect, and Dean and Barroso's paper "The Tail at Scale" argues that tail latency becomes harder to control as systems grow.
Two defences help here. A deadline limits how long the coordinator waits. When it expires, the coordinator returns what it has and marks the answer as partial. The user gets a fast answer with possibly missing results instead of a slow complete one. A hedged request, defined in the non-functional chapter, sends the request to a second replica if the first has not answered within a short time, and takes whichever answers first.
import asyncio, sys, time from corpus import make_docs from index import tokenize, build from bm25 import bm25 from shards import split, merge K, terms = 5, tokenize("paneer salt") shards = split(make_docs(), 3) async def ask(shard, delay): await asyncio.sleep(delay) # the shard's response time return shard.top_k(terms, K) async def scatter(delays, deadline=None): tasks = [asyncio.create_task(ask(s, d)) for s, d in zip(shards, delays)] done, late = await asyncio.wait(tasks, timeout=deadline) for t in late: t.cancel() return merge([t.result() for t in done], K), len(late)
l6_run.py, part 1: ask a shard, scatter with a deadline
async def hedged(shard, delays, after): # try a second replica first = asyncio.create_task(ask(shard, delays[0])) done, _ = await asyncio.wait({first}, timeout=after) if not done: second = asyncio.create_task(ask(shard, delays[1])) done, rest = await asyncio.wait( {first, second}, return_when=asyncio.FIRST_COMPLETED) for t in rest: t.cancel() return done.pop().result()
l6_run.py, part 2: a hedged request to a second replica
Run: a slow shard, a deadline and a hedge
The shards are the three real Shard objects from the previous lesson. Their response times are simulated with asyncio.sleep: 20, 30 and 20 ms normally, and 800 ms for a slow third shard. Four cases are timed. The times are real, on this machine, and they vary from run to run. The printed lines at the top work out the chance of a slow shard from the previous section.
async def main(): print(sys.version.split()[0], "- shard delays are simulated") for n in (3, 100): # if 1 reply in 100 is slow slow = 1 - 0.99 ** n print(f"{n} shards: a slow shard in {slow:.1%} of queries") for label, delays, deadline in [ ("all fast", [0.02, 0.03, 0.02], None), ("one slow, wait", [0.02, 0.03, 0.80], None), ("one slow, 0.2 s deadline", [0.02, 0.03, 0.80], 0.2)]: t0 = time.perf_counter() res, late = await scatter(delays, deadline) ms = (time.perf_counter() - t0) * 1000 print(f"{label:25} {ms:4.0f} ms late={late} " f"{[d for d, _ in res]}") t0 = time.perf_counter() parts = await asyncio.gather( hedged(shards[0], [0.02, 0.02], 0.05), hedged(shards[1], [0.03, 0.03], 0.05), hedged(shards[2], [0.80, 0.03], 0.05)) ms = (time.perf_counter() - t0) * 1000 print(f"{'slow replica, hedged':25} {ms:4.0f} ms late=0 " f"{[d for d, _ in merge(parts, K)]}") asyncio.run(main())
l6_run.py, part 3: the four cases
3.12.10 - shard delays are simulated 3 shards: a slow shard in 3.0% of queries 100 shards: a slow shard in 63.4% of queries all fast 32 ms late=0 [82, 128, 48, 89, 169] one slow, wait 810 ms late=0 [82, 128, 48, 89, 169] one slow, 0.2 s deadline 229 ms late=1 [128, 48, 89, 169, 5] slow replica, hedged 91 ms late=0 [82, 128, 48, 89, 169]
With every shard fast, the answer took 32 ms. When the third shard took 0.8 seconds and the coordinator waited, the query took 810 ms with the same result. With a 0.2 second deadline, the answer came back in 229 ms, but one shard was late, and the result was missing document 82, the best hit, which lived on the slow shard. The partial answer is fast and not complete. In the last case, a second replica of the third shard answered in 30 ms, the hedge was sent after 50 ms, and the full answer came back in 91 ms.
A deadline protects the user's time and trades completeness for speed, so the response should say it is partial. A hedge protects both, at the price of extra load, since some requests are sent twice. Hedging only the slow tail, after a delay, keeps that extra load small.