AlgoViz

Design a Distributed Search Engine (Elasticsearch)

hard 75 min

Find the best ten of ten billion documents while people wait: shards, replicas, scoring, immutable segments, and a rebuild plan.

See it run

Follow a document to a shard, then follow a question through many shards and back.

Operations

Index one document

Acknowledged first, searchable after refresh.

Step 1 of 5

Receive

IndexerCoordinatorPrimary copyAnalyzerOperation logReplica copyMemory bufferSegment

document

wireless headphones

An indexer sends listing 123, version 41, to a coordinator.

Step 1: Receive

def index(doc):    shard = hash(doc.id) % 100    primary = cluster.primary(doc.site, shard)    terms = analyze(doc)    primary.log_and_buffer(doc.version, terms)    for copy in primary.in_sync():        copy.log_and_buffer(doc.version, terms)    return OK          # visible after refresh
Latency
Tens of ms, then refresh
Work
2 copies
Edit all postings in place
random writes, locks

Success says the operation is safe. It does not say that a search already sees it.

In the real world

The same distributed search engine doing real jobs. Pick one and step through it.

Ninety-nine replies have arrived and one has not.

Step 1 of 3

Ask 100

Our systemPersonCoordinatorShard 1Shard 2Shard 100Redis

shard 2

busy merge

A wide query includes one busy copy.

Step 1: Ask 100

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Use the index as the only listing

    critical

    A bad mapping or deletion destroys the product's record.

    Wrong
    index.save(listing)
    Right
    database.save(listing)  # change log feeds index
  • Read very deep offsets

    major

    Each shard returns an enormous prefix.

    Wrong
    search(offset=100000, size=10)
    Right
    search(after=[last_score, last_id], size=10)
  • Average shard averages

    major

    Shards have different document counts.

    Wrong
    avg = mean([s.avg for s in shards])
    Right
    avg = sum(s.sum for s in shards) / sum(s.count for s in shards)
  • Retry a whole partial bulk

    major

    Already accepted items waste work, and old writes may race.

    Wrong
    bulk(items)  # again
    Right
    bulk([x for x in items if x.failed])  # source versions
  • Refresh every write

    major

    It creates tiny segments and merge pressure.

    Wrong
    index(doc, refresh_now=True)
    Right
    index(doc)  # wait for next refresh when needed

Interview tips

  • Lead with the split

    • 30 TB gives 1,000 shards.
    • One site needs 100 of them.
    • 10,000 searches become one million visits.
  • Separate three moments

    • Accepted in the source.
    • Acknowledged by index copies.
    • Visible after refresh.
  • Control the tail

    • Deadline and partial flag.
    • Good replica choice.
    • Limited second requests.
  • Plan a rebuild

    • Snapshot and position.
    • Replay and compare.
    • Alias and rollback.