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.
Video lesson · Chapter 1 of 6
Scatter a query and gather candidates
Theory
Read or listen first. About 1 min.
What it is
A distributed search system keeps an index in parts, called shards, on many machines. A coordinator receives a query, sends it to the shards at the same time, and merges their answers. This is scatter-gather.
It works in two phases. In the query phase every shard finds its best few matches and returns only ids and scores. In the fetch phase the coordinator asks for the full text of the few winners. The result is ordered by relevance, usually with BM25.
Why it exists
A large index does not fit in the memory of one machine, and one machine cannot score it fast enough. Cut into ten parts, each part does a tenth of the work at the same time.
The price is that the user waits for the slowest part. Most of the design is about that: timeouts, copies, second requests, caches, and an honest answer when a part is missing.
A short history
2003
Barroso, Dean and Hölzle describe Google's search cluster in IEEE Micro: queries run in parallel, and a partitioned index lets one query use many processors.
8 February 2010
The first version of Elasticsearch is released, with sharding and scatter-gather built in.
2013
Dean and Barroso publish The Tail at Scale. It explains why large fan-outs are slow and how second requests help.
Words to know
- Coordinator
- The node that receives the query, asks the shards and merges.
- Scatter-gather
- Ask all at the same time, then collect.
- Query phase
- Shards return ids and scores of their best matches.
- Fetch phase
- The coordinator gets the documents of the winners.
- BM25
- The usual relevance score: rare words, repeated words with a limit, and document length.
- Tail latency
- The time of the slowest requests, for example p99.
- Partial result
- An answer made without all shards, and marked as such.
How it works
Step through the idea, or press Play.
Scatter. One copy of every shard gets the query
Understand it
Start here
Asking three museum guides
A museum has three rooms and a guide in each. A visitor wants the best blue things. Nobody knows all rooms, so the desk asks all guides at once.
How each room built its drawers is the topic Indexing in distributed search.
Parts
The system on one page
A query and its shards
| Part | Does | Fails like this |
|---|---|---|
| Load balancer | Spreads queries over coordinators | A standby takes over |
| Coordinator | Analyze, route, merge, fetch, cache | Stateless: another one answers |
| Query cache | Keeps answers to frequent queries | Slower, still right |
| Shard | One part of the index, searched locally | A replica answers |
| Replica | A copy for safety and for more reads | Fewer reads a second |
Parallel
All shards work at the same time.
Local first
Each shard joins and scores its own lists.
Small answers
Ids and scores, not documents.
Ranked
BM25, then the rules of the business.
Deadline
Late shards are left out, and it is said.
Cached
Popular queries are answered once.
The path
One query, step by step
- 1
Parse
Analyze the words with the index's own analyzer, check filters, make a plan.
- 2
Look in the cache
Same normalised query, same user rights, same page? Answer at once.
- 3
Scatter
Send to one copy of each shard. An id lookup goes to one shard only.
- 4
Search locally
Read the posting lists, join them, apply filters.
- 5
Score locally
BM25 for each match, best k kept in a heap.
- 6
Gather
Collect k ids and scores from each shard.
- 7
Merge
Take the global best k, with the id as tie-breaker.
- 8
Fetch and return
Get those documents, add highlights, store in the cache, answer.
Query, then fetch
Why two phases
Where the time goes (an example)
| Phase | Time |
|---|---|
| Client to coordinator | 5 ms |
| Parse | 1 ms |
| Scatter | 2 ms |
| Shard search, in parallel | 20 to 50 ms |
| Gather and merge | 5 ms |
| Fetch winners | 5 ms |
| Coordinator to client | 5 ms |
| Together | 43 to 73 ms |
Ranking
BM25, with numbers
The score
The word search: N = 1,000, in 100 documents, average length 200
| Document | Times | Length | Score |
|---|---|---|---|
| A | 5 | 100 words | 4.40 |
| B | 5 | 500 words | 3.35 |
| C | 2 | 100 words | 3.68 |
The four parts
| Part | Meaning |
|---|---|
| Term frequency | More often is better, up to a limit |
| Inverse document frequency | Rare words count more |
| Length | Long documents are not favoured for being long |
| k1 and b | How fast the limit is reached, how much length counts |
Relevance is only the first pass. Many systems take the best few hundred by BM25 and order them again with a costlier model or with rules: in stock, fresh, popular.
The same word, two shards
The tail
The slowest shard decides
How often a query meets a slow shard
What helps
- Fewer, larger shards
- A deadline for each query, passed to the shards
- Choosing the faster replica
- A second request to another replica after the usual p95
- Enough free CPU, and merges that do not take it
What does not
- More shards: more chances to be slow
- Waiting in sequence, so five-second timeouts add up
- Long timeouts
- Retrying everything at once
- Looking only at averages
A hedged request
Failure
When a shard does not answer
Deadline reached
Elasticsearch returns partial results by default and reports failed shards in the answer. The counts are then too low as well. Show it: some results may be missing.
Cache
What may be cached
| Cache | Holds | Careful |
|---|---|---|
| Whole answers | Popular queries, for about 60 s | Rights, language and page belong in the key |
| Filter results | Document sets for frequent filters | Dropped with their segment |
| Shard results | Counts and aggregations | In Elasticsearch, by default only requests with size 0 |
| Pages of files | Hot index blocks in memory | Leave memory for the operating system |
May this answer be stored?
Pages
Why page 1,000 is expensive
From 10,000, size 10, on ten shards
Cursor (search after)
- Give me 10 after score 3.2, id 881
- Each shard returns 10
- Stable while new documents arrive, with a fixed view
- Next only, no jump to page 500
Offset
- Give me 10 from 10,000
- Each shard returns 10,010
- New documents shift the pages
- Fine for the first pages
The order must be total. Sort by score and then by a unique id, or two equal scores may change places between pages. More in search and filtering in APIs.
Numbers
How many machines?
Assumptions: 100 million searches a day, peak 3 times the average, 10 shards, 20 ms of CPU for one shard search, 40% answered from the cache.
| Question | Arithmetic | Answer |
|---|---|---|
| Average | 100,000,000 / 100,000 | 1,000/s |
| Peak | 1,000 x 3 | 3,000/s |
| After the cache | 3,000 x 0.6 | 1,800/s |
| Shard searches | 1,800 x 10 | 18,000/s |
| Busy cores | 18,000 x 0.020 s | 360 |
| Cores at 50% use | 360 / 0.5 | 720 |
| Machines of 16 cores | 720 / 16 | 45 |
Copies share the reads
Rules
Do and do not
Do
- Set a deadline for each shard
- Cache frequent queries
- Return partial results, marked
- Use replicas for reads and safety
- Watch p95 and p99, and the slow log
Do not
- Return whole result sets
- Search all fields when three matter
- Fetch documents for every match
- Count only the hits you received as the total
- Offer offset 10,000
Summary
The whole topic in one minute.
The coordinator analyzes the query, looks in a cache, asks one copy of each shard, and receives ids and scores. It keeps the best k in a heap, fetches those documents, and answers. Every shard returns at most from plus size entries.
The slowest shard sets the time, and with many shards something is always slow. Give a deadline, use replicas and hedged requests, say when results are partial, and never cache those. Deep pages are replaced by a cursor.
- Scatter to one copy of each shard, gather ids and scores, fetch the winners.
- BM25: rare words, repeated words with a limit, length.
- Scores use local counts. Small shards make them unfair.
- The slowest shard decides: deadline, replicas, hedging.
- Mark partial results, and never cache them.
- Use a cursor instead of deep pages.