Design a Distributed Full-Text Search Engine with Boolean Queries
System DesignModel answerLast updated
Design a scalable search system that indexes short user posts in near real-time and evaluates Boolean queries with stable cursor-based pagination.
Distributed Full-Text Search with Boolean Queries
You are building the search backend for a social platform where users publish short status updates. The search interface lets users express what they are looking for using logical conditions — combining required terms, alternative terms, and excluded terms — with support for grouping via parentheses.
For example, a user might type: (engineering OR product) AND NOT standup
Your job is to design the system end to end.
Functional Requirements
- Newly published posts should become searchable within roughly one second of creation.
- Queries may contain
AND,OR, andNOToperators, arbitrarily nested with parentheses. Standard logical precedence applies. - Results must be paginated. Pagination must be stable: moving from page 1 to page 2 should not skip or repeat posts because new content arrived between the two requests.
Non-Functional Requirements
- The system must remain available and horizontally scalable.
- Updates to the index should reach strong eventual consistency across replicas.
- Write throughput must not degrade search latency.
What Your Design Should Cover
- Index structure: How do you represent the inverted index and organize it across machines? What are the trade-offs between centralizing the index and partitioning it?
- Query pipeline: How do you turn a raw query string into an efficient execution plan? What data structure represents it, and what optimizations matter?
- Ingestion flow: How does a post travel from the moment a user submits it to the moment it appears in search results?
- Pagination strategy: How do you guarantee that pages stay consistent when the underlying index is continuously growing?
Scale Assumptions
- Ingestion rate: 50,000 posts per second
- Query volume: 10,000 searches per second
- Posts average 30 tokens each
- Your design should stay performant even when a query includes very common words like "the" or "update"
Hints
Hint 1
Start with the doc ID scheme. If IDs encode creation time and are monotonically increasing, sorting by recency and building a cursor both become trivial — figure out how to exploit that before designing anything else.
Hint 2
Think about what happens when a user queries a term that appears in millions of posts. Scanning the whole posting list is not viable. Consider how early termination during execution, combined with descending-order posting lists, lets you stop after collecting just one page of results.
Hint 3
Offset-based pagination breaks when the index is live. Sketch out what information a cursor would need to carry so that a shard can resume from exactly the right position and never include posts that were written after the first page was served.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify Scope and Estimate Scale
Before drawing any boxes, confirm a few things: results are ordered by recency (newest first); relevance ranking is out of scope; visibility filtering happens as a post-processing step; and the retention window is 30 days hot, older data cold.
Back-of-envelope numbers:
| Metric | Estimate |
|---|---|
| Posts per day | 50k/s × 86,400 ≈ 4.3B |
| Postings per second | 50k × 30 tokens = 1.5M/s |
| Compressed index growth | ~3 bytes/posting → ~400 GB/day, ~12 TB over 30 days |
| Query fanout | 10k QPS across shards; with 3× replication, each replica serves ~3.3k QPS |
Two facts drive every major decision: the workload is write-heavy, and 12 TB does not fit in one machine's memory. That points directly to a sharded, segment-based design.
2. API Surface
POST /posts {author_id, text} → {post_id}
DELETE /posts/{id}
GET /search?q=(engineering OR product) AND NOT standup
&limit=20&cursor=<opaque>
→ {results: [...], next_cursor}
3. Document IDs and Index Structure
Monotonic doc IDs. Assign each post a Snowflake-style ID: timestamp | shard_id | sequence. This gives three properties: IDs sort by creation time, every new post gets a larger ID than all existing ones, and pagination cursors reduce to a single integer boundary.
Inverted index. The core structure maps term → posting list, where each list is sorted by doc ID in descending order (newest first).
- Compression: delta-encode adjacent IDs, then apply PForDelta or varint encoding. Typical deltas compress to 1–2 bytes per entry.
- Skip pointers: every ~128 entries, store the doc ID and byte offset. An
advance(target)call can binary-search to the right block instead of scanning linearly. This is what makes intersecting a huge list with a rare term fast.
Segment lifecycle (LSM-style). Inspired by systems like Twitter's Earlybird:
- The active segment lives in memory and is append-only. Writers append to it; readers observe a published
max_doc_idwatermark, so no locks are needed. - When a segment reaches ~10M documents it is sealed, optimized, and flushed to disk. Background merges compact segments over time.
- Segments are time-tiered: recent tiers in RAM, older tiers on SSD, cold data on object storage.
Centralized vs. document-partitioned sharding:
- A centralized index is simple but cannot absorb 1.5M postings/s or hold 12 TB. It is also a single point of failure.
- Document-partitioned sharding (chosen): each shard owns a subset of posts and maintains a complete local index over them. Any Boolean query executes entirely within a shard. A stateless broker fans the query out to all shards, collects ranked results, and merges them. Writes distribute evenly.
- The cost of fan-out is mitigated by replicas (serving reads in parallel) and time-tier pruning (skipping old segments that cannot match a cursor-bounded page).
- Term-partitioned sharding would route each term to one shard but requires multi-shard coordination for AND/OR queries, making execution more complex without a clear throughput gain at this scale.
4. Query Parsing and Execution
Step 1: Parse to an AST. Tokenize the raw string and build an abstract syntax tree with a recursive-descent parser. Apply standard precedence: NOT > AND > OR. Normalize each token with the same analyzer used at index time (lowercasing, Unicode folding, stemming). A mismatch between index-time and query-time analysis is one of the most common bugs in search systems.
Step 2: Rewrite the AST.
- Flatten nested same-type operators:
AND(a, AND(b, c))→AND(a, b, c). - Push NOT inward using De Morgan's laws so it attaches only to leaves or bounded subtrees within an AND.
- Reject or bound a bare top-level NOT. "Everything except X" requires a full index scan; either disallow it or rewrite it as
ALL_RECENT AND NOT xwith a time horizon. - Avoid full DNF conversion — it can expand exponentially on complex queries.
Step 3: Optimize the plan.
- Sort AND children by ascending document frequency so the rarest term drives the intersection.
- Treat NOT children as exclusion filters applied after a candidate passes, never as the driving iterator.
- Cache results for hot sub-expressions; invalidate on new segment watermarks.
- Use per-segment bloom filters or term dictionaries to skip segments that cannot possibly contain a term.
Step 4: Execute with an iterator tree. Each node exposes next() and advance(target):
- AND node — leapfrog intersection: advance every child to the current candidate. If all agree, emit the candidate; otherwise jump to the new maximum across children.
- OR node: k-way merge with a min-heap (or max-heap for descending order).
- AND NOT x node: for each candidate
d, callx.advance(d); if it matches, discardd.
Because posting lists are sorted newest-first and the query only needs limit results, execution terminates early once enough candidates are collected. A broad term like "update" stops after ~20 matches rather than scanning millions of entries. This is the primary answer to the high-frequency term performance requirement.
5. Ingestion Pipeline
Post Service ──► Post DB (source of truth)
└──► Kafka "posts" topic (partitioned by doc-ID shard)
└──► Indexer replicas
tokenize → analyze → append to active segment
→ advance max_doc_id watermark
- Each shard replica is an independent Kafka consumer for its partition. Replicas apply the same ordered log, so they converge to identical index state without coordination — this is the strong eventual consistency guarantee.
- At 50k/s across 128 partitions, each partition sees ~400 posts/s. Kafka adds 10–100 ms; indexing adds a few ms. End-to-end latency to searchability is comfortably under one second.
- Replicas snapshot segment state periodically alongside the Kafka offset. Crash recovery means loading the latest snapshot and replaying the log from the saved offset.
- If indexers fall behind, the Kafka log absorbs the backlog; consumer-lag alerts fire before latency degrades for users.
6. Stable Pagination
Offset-based pagination has two problems in this setting: new posts shift every subsequent page, and OFFSET N re-scans everything before it.
Cursor-based approach:
- First request: the broker captures a snapshot watermark
W= currentmax_doc_idacross all shards, then executes the query normally. - Cursor value:
{W, last_doc_id_returned}, encoded as an opaque signed token so clients cannot manipulate it. - Subsequent pages: each shard evaluates the query restricted to
last_doc_id < id ≤ W. With descending posting lists,advance(last_doc_id)seeks directly to the right position — no rescanning. - Merge: each shard returns its top
limitcandidates; the broker merges by doc ID and issues the next cursor.
This is stable because new posts always have id > W, so they are invisible to the paginated session. Deleted posts may leave gaps, but those are handled by tombstone checks at read time — the page never grows unexpectedly, it only potentially shrinks slightly.
Common Mistakes to Avoid
- Mismatched analyzers between index time and query time — this silently returns zero results for valid queries.
- Driving an AND with a high-frequency term — always order AND children by document frequency ascending.
- Bare top-level NOT — without bounding it, it forces a full index scan.
- Using offset pagination in a live index — it is broken by design when writes are continuous.
- Ignoring the fan-out cost — without time-tier pruning and replica scaling, 10k QPS fans into thousands of shard requests per second.