Inside a distributed search system
hard 30 minHow one query is answered by many machines: a coordinator asks every shard, each returns its best few, the lists are merged, and only the winners are fetched.
See it run
One query on three shards: scatter, score, merge, fetch. Then what makes it slow.
Operations
One query
Nine steps for the query distributed systems.
Step 1 of 9
The query arrives
Top 3, please
A user asks for distributed systems.
Step 1: The query arrives
def search(q, k): key = normalise(q) if key in cache: return cache[key] terms = analyze(q) rows = gather(s.query(terms, k) for s in shards) best = nsmallest(k, rows, key=rank) hits = [fetch(r) for r in best] if all_answered(rows): cache[key] = hits return hitsdef shard_query(terms, k): docs = join(lists(terms)) return top(k, ((bm25(d), d) for d in docs))- You get
- Parallel work
- You pay
- Wait for the slowest
Say ids and scores first, documents second. It shows that you know what travels.
In the real world
The same inside a distributed search system doing real jobs. Pick one and step through it.
The same document text on two small shards.
Step 1 of 4
Shard 1
| Where | Documents | With the word | Weight |
|---|---|---|---|
| shard 1 | 100 | 1 | 4.21 |
Rare
100 documents, the word is in 1. It looks very rare.
Step 1: Shard 1
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Fetching every match
criticalA shard with 120 matches loads 120 documents, although three are shown.
Wronghits = [fetch(d) for d in matches]Rightbest = top(k, matches)hits = [fetch(d) for d in best]Timeouts one after another
majorWaiting up to 5 s for each shard in turn can take 50 s for ten shards.
Wrongfor f in futures: f.result(timeout=5)Rightwait(futures, timeout=0.2)Total from received hits
majorEach shard sent only its best ten. The total is not a hundred.
Wrongtotal = len(all_hits)Righttotal = sum(s.total for s in answers)Caching a partial answer
criticalOne slow shard becomes a minute of wrong results.
Wrongcache[key] = pageRightif not partial: cache[key] = page
Interview tips
How to explain it
- Scatter, gather, fetch.
- The slowest shard decides.
- Partial answers are marked.
Memory trick: SEARCH
- Scatter, Execute.
- Aggregate, Rank.
- Cache, Hand off.
Numbers to say
- 100 shards, 1% slow: 63%.
- Offset 10,000 on ten shards: 100,100 entries.
- 22 KB instead of 200 KB.
Watch out
- Local counts on small shards.
- Rights in the cache key.
- Ties need a second sort key.