AlgoViz

Inside a distributed search system

hard 30 min

How 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

0:00 / 4:53

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

  1. 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.

  2. 8 February 2010

    The first version of Elasticsearch is released, with sharding and scatter-gather built in.

  3. 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.

Step 1 of 3

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.

One question, three rooms, one answer
The best blue things?

How each room built its drawers is the topic Indexing in distributed search.

Parts

The system on one page

A query and its shards

Clients reach a coordinator through a load balancer. The coordinator looks in a Redis query cache and asks shard 0, shard 1 and shard 2, each on its own machine.
Any coordinator can serve any query, so add more when CPU for merging is the limit.
PartDoesFails like this
Load balancerSpreads queries over coordinatorsA standby takes over
CoordinatorAnalyze, route, merge, fetch, cacheStateless: another one answers
Query cacheKeeps answers to frequent queriesSlower, still right
ShardOne part of the index, searched locallyA replica answers
ReplicaA copy for safety and for more readsFewer 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. 1

    Parse

    Analyze the words with the index's own analyzer, check filters, make a plan.

  2. 2

    Look in the cache

    Same normalised query, same user rights, same page? Answer at once.

  3. 3

    Scatter

    Send to one copy of each shard. An id lookup goes to one shard only.

  4. 4

    Search locally

    Read the posting lists, join them, apply filters.

  5. 5

    Score locally

    BM25 for each match, best k kept in a heap.

  6. 6

    Gather

    Collect k ids and scores from each shard.

  7. 7

    Merge

    Take the global best k, with the id as tie-breaker.

  8. 8

    Fetch and return

    Get those documents, add highlights, store in the cache, answer.

Query, then fetch

Six small entries travel, then three documents.

Why two phases

10×10×2 KB=200 KB10×10×20 B+10×2 KB=22 KB10 \times 10 \times 2\text{ KB} = 200\text{ KB} \qquad 10 \times 10 \times 20\text{ B} + 10 \times 2\text{ KB} = 22\text{ KB}
Ten shards, ten hits each, documents of 2 KB, 20 bytes for an id and score. Fetching only winners moves about a ninth.

Where the time goes (an example)

PhaseTime
Client to coordinator5 ms
Parse1 ms
Scatter2 ms
Shard search, in parallel20 to 50 ms
Gather and merge5 ms
Fetch winners5 ms
Coordinator to client5 ms
Together43 to 73 ms
Illustrative numbers. The line to attack is the shard search, and its slowest case.

Ranking

BM25, with numbers

The score

∑qln⁡ ⁣(1+N−nq+0.5nq+0.5)⋅f(k1+1)f+k1(1−b+b ∣D∣avgdl)\sum_{q} \ln\!\left(1 + \frac{N - n_q + 0.5}{n_q + 0.5}\right) \cdot \frac{f (k_1 + 1)}{f + k_1 \left(1 - b + b\,\frac{|D|}{avgdl}\right)}
f: times the word is in the document. N documents, n_q with the word. k1 = 1.2 and b = 0.75 are the defaults in Elasticsearch.

The word search: N = 1,000, in 100 documents, average length 200

DocumentTimesLengthScore
A5100 words4.40
B5500 words3.35
C2100 words3.68
A has the same count as B in fewer words. C beats B although it has fewer hits: length matters, and repeating a word pays less and less.

The four parts

PartMeaning
Term frequencyMore often is better, up to a limit
Inverse document frequencyRare words count more
LengthLong documents are not favoured for being long
k1 and bHow 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

ln⁡ ⁣(1+99.51.5)=4.21ln⁡ ⁣(1+50.550.5)=0.69global: 1.36\ln\!\left(1+\tfrac{99.5}{1.5}\right) = 4.21 \qquad \ln\!\left(1+\tfrac{50.5}{50.5}\right) = 0.69 \qquad \text{global: } 1.36
Two shards of 100 documents: one has the word in 1 document, the other in 50. Equal documents get very different scores. With many documents spread by hash this fades. Otherwise collect global counts first: Elasticsearch calls it dfs_query_then_fetch.

The tail

The slowest shard decides

How often a query meets a slow shard

1−0.9910=9.6%1−0.99100=63.4%1 - 0.99^{10} = 9.6\% \qquad 1 - 0.99^{100} = 63.4\%
Each shard is slow in 1 of 100 requests, independently. With 100 shards, most queries are slow.

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

Sent only after the p95 time, it adds about five percent more requests. Elasticsearch also picks the copy by past response times and queue length (adaptive replica selection).

Failure

When a shard does not answer

Deadline reached

Product search: partial. Legal discovery: error. Decide for each use.

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

CacheHoldsCareful
Whole answersPopular queries, for about 60 sRights, language and page belong in the key
Filter resultsDocument sets for frequent filtersDropped with their segment
Shard resultsCounts and aggregationsIn Elasticsearch, by default only requests with size 0
Pages of filesHot index blocks in memoryLeave memory for the operating system
Normalise before making the key: same words, same order of filters. Include every filter, or a user sees results of another.

May this answer be stored?

Two questions before every write to the cache.

Pages

Why page 1,000 is expensive

From 10,000, size 10, on ten shards

10×(10,000+10)=100,100 entries merged, to show 1010 \times (10{,}000 + 10) = 100{,}100 \text{ entries merged, to show } 10
A shard cannot know which of its entries are global winners, so it returns all from plus size. Elasticsearch refuses beyond 10,000 by default.

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.

QuestionArithmeticAnswer
Average100,000,000 / 100,0001,000/s
Peak1,000 x 33,000/s
After the cache3,000 x 0.61,800/s
Shard searches1,800 x 1018,000/s
Busy cores18,000 x 0.020 s360
Cores at 50% use360 / 0.5720
Machines of 16 cores720 / 1645
Without the cache it would be 75 machines. Half-empty machines look wasteful and keep the tail short. With one shard copy on each machine, 720 / 10 = 72 cores for a shard means 5 copies, so 50 machines.

Copies share the reads

A coordinator can ask copy 1 or copy 2 of shard 0 and copy 1 or copy 2 of shard 1. One copy of each shard is asked for a query.
Growing further is the topic Scaling search and indexing.

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.

Sources