Boolean Keyword Search Engine for a High-Volume Short-Post Feed
System DesignModel answerLast updated
Design a sharded, near-real-time inverted index that answers AND/OR/NOT keyword queries over a stream of 10K new short posts per second within 200 ms.
Build a Boolean Keyword Search Backend for Short Posts
A social product lets people publish short text updates. You are asked to design the backend that lets users find those updates with boolean keyword expressions such as (coffee OR tea) AND NOT cold.
Scale and goals
- About 10,000 new posts per second arrive continuously.
- Search requests must finish in under 200 ms.
- Queries support AND, OR and NOT.
- New posts should become searchable quickly, and removed posts should disappear quickly (soft deletion). A lag of a few seconds is acceptable (eventual consistency).
- The service must stay highly available and evaluate queries efficiently.
What to cover in your answer
- Index layout: What does the inverted index look like? How are posting lists stored and fetched for a term?
- Query evaluation: How is a nested boolean expression executed? How do you intersect and merge lists cheaply?
- Partitioning: How would you shard the index? Compare splitting by document with splitting by term.
- Freshness and correctness: How does asynchronous indexing work, and how do you make update processing idempotent (duplicates, retries, reordering)?
- Failure handling: What happens when a node dies, and how do you avoid losing search coverage?
State your assumptions (retention window, query rate, ranking) and size the system with rough numbers.
Hints
Hint 1
Start with back-of-envelope math: posts per day, tokens per post, postings written per second, and compressed index size for your retention window. This tells you whether the index fits in memory.
Hint 2
If document IDs are assigned in arrival order within a shard, posting lists are append-only and sorted, and newest-first ordering comes for free. Think about how skip pointers and an 'advance to at least X' iterator make AND cheap.
Hint 3
For idempotency, attach a version to every event and keep a post-to-document map. Compare incoming versions with the stored one so replays and out-of-order events become harmless, and let a durable log (with offsets stored alongside snapshots) drive recovery.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Sizing and assumptions
- Ingest: 10K posts/s is roughly 860M posts/day. Assuming about 20 distinct tokens per post, the index absorbs about 200K postings/s.
- Retention: assume the last 30 days are searchable, about 26B posts and about 500B postings. At 1-2 bytes per compressed posting, that is 0.5-1 TB of index, about 3 TB with three replicas. This fits in RAM/SSD on a modest fleet.
- Queries: assume 20-50K QPS, p99 under 200 ms, results returned as top-K (say 20) by recency, with a visibility/privacy filter applied after retrieval.
2. Data model
- Document IDs: each shard assigns a local, monotonically increasing 32-bit doc ID on ingest. ID order equals time order, so new postings are appended and recency sorting is free.
- ID maps:
docID -> (post_id, version)andpost_id -> docIDsit beside the index. - Posting lists:
term -> sorted docIDs, compressed in blocks of 128 (delta plus bit-packing). Each block has a skip entry(maxDocID, offset)so readers can jump without decoding everything. - Segments (LSM style): one mutable in-memory segment takes writes. At around 1M docs it is sealed into an immutable segment. Background merges compact small segments.
- Term dictionary: per segment, an FST or sorted array maps term to posting-list offset.
- Deletes: a per-segment tombstone bitmap. Dead docs are physically dropped at merge time.
3. Query execution
- Parse into an AST.
- Normalize: push NOT to leaves (De Morgan), flatten nested AND/OR, and rewrite
A AND NOT Bas a difference operator. Reject a bare top-level NOT, or run it against the "all live docs" list behind a cost guard. - Build an iterator tree where each node supports
next()andadvance(target)(first docID >= target).- AND: order children by list length; the shortest drives and others
advance()using skip pointers or galloping search. Cost is about O(|shortest| log |longest|), not the sum of the lists. - OR: k-way merge with a min-heap, O(N log k).
- AND NOT: iterate the positive side and probe the negated side with
advance(). - Tombstones: check each candidate against the bitmap at the leaf.
- AND: order children by list length; the shortest drives and others
- Early termination: walk segments newest-first and docIDs descending, and stop after K hits. Recency queries typically touch a tiny part of each list.
Example: (coffee OR tea) AND NOT cold becomes Diff(Union(coffee, tea), cold).
4. Sharding
| Document-partitioned | Term-partitioned | |
|---|---|---|
| Write | One shard per post | Fans out to about 20 term shards |
| Query | Scatter to all shards; each evaluates the full expression locally | Only shards owning the query terms, but lists must be shipped to intersect |
| Hot terms | Load is spread evenly | A trending word becomes a hotspot |
| Tail latency | Slowest of N shards | Fewer hops, large transfers |
Choose document partitioning (hash(post_id)), with time tiers: a real-time tier (hours), a recent tier (days), an older tier (weeks). A broker fans out, merges per-shard top-K by timestamp, and skips older tiers once K results are found.
Tail-latency controls: hedged requests to a second replica after about p95, per-shard deadlines near 150 ms, and a partial=true flag instead of failing the whole query.
Sizing: about 1 TB over ~20 GB shards gives roughly 50 shards per tier, with 3 replicas each. Add replicas as QPS grows.
5. Freshness and idempotency
Pipeline: post service -> Kafka (durable log, partitioned by shard) -> per-shard indexer -> mutable segment -> visible after the next searcher refresh (about 1 s).
- Every event carries
(post_id, version)from the source-of-truth DB. - The indexer compares against the stored version. Events at or below it are dropped, so duplicates and reordering are no-ops. A newer version tombstones the old docID and indexes a fresh one (edit = delete + reinsert).
- A delete sets the tombstone and records its version, so a late
Created v1cannot resurrect a post deleted at v2. - Atomic checkpoints: a sealed segment is committed together with the Kafka offset it covers. On restart, resume from that offset; replaying a few events is safe thanks to the version check.
6. Recovery
- Replication: 3 replicas per shard across failure domains, each consuming Kafka independently (no leader/follower coupling). If one dies, the broker routes around it.
- Snapshots: sealed segments plus offset checkpoints are periodically uploaded to blob storage.
- Rebuild: a new node downloads the latest snapshot, replays Kafka from the checkpoint, and joins the serving pool only once consumer lag is under a threshold. Kafka retention (e.g., 7 days) must exceed the snapshot interval.
- Corruption: discard and rebuild the same way.
- Total shard loss: the broker returns
partial=true. Track consumer lag and shard coverage as SLOs.
7. Trade-offs and common mistakes
- Choosing term partitioning for boolean queries without addressing cross-network list shipping and hot terms.
- Ignoring deletes, or physically removing postings in place instead of tombstoning and compacting.
- Forgetting idempotency: at-least-once delivery will produce duplicates and reordering.
- Evaluating NOT as a standalone complement over the whole corpus.
- Not bounding tail latency (no hedging, deadlines or partial results).
- Skipping capacity math, so the design is never justified by numbers.
Possible extensions: relevance ranking beyond recency, phrase queries (positional postings), per-user privacy filtering, and prefix/typo tolerance.