Design a Distributed Search Engine (Elasticsearch)
hard 75 minFind 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
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
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
criticalA bad mapping or deletion destroys the product's record.
Wrongindex.save(listing)Rightdatabase.save(listing) # change log feeds indexRead very deep offsets
majorEach shard returns an enormous prefix.
Wrongsearch(offset=100000, size=10)Rightsearch(after=[last_score, last_id], size=10)Average shard averages
majorShards have different document counts.
Wrongavg = mean([s.avg for s in shards])Rightavg = sum(s.sum for s in shards) / sum(s.count for s in shards)Retry a whole partial bulk
majorAlready accepted items waste work, and old writes may race.
Wrongbulk(items) # againRightbulk([x for x in items if x.failed]) # source versionsRefresh every write
majorIt creates tiny segments and merge pressure.
Wrongindex(doc, refresh_now=True)Rightindex(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.