Sharded Full-Text Search for Multi-Tenant Tables
System DesignModel answerLast updated
Design a near-real-time, sharded full-text search layer over large structured tables with sub-200ms reads and petabyte scale.
Context
You are designing the search subsystem for a product where customers keep structured records in tables (think spreadsheet-database hybrids). Users expect to type a keyword and instantly see matching rows from their own tables, while rows are being edited, imported, and deleted constantly.
What to design
A search service that indexes row content from a primary transactional database and answers keyword queries scoped to a table, a base (group of tables), or an entire workspace.
Functional requirements
- Keyword search across multiple text columns of a table, plus simple equality filters on columns.
- Ranked, paginated results with highlighted snippets.
- Edits become searchable in near real time (on the order of a second or two, p99).
- Search scope is resolved server-side from the caller's permissions.
Non-functional requirements
- p99 query latency under 200 ms for the common case.
- Scale to roughly 1 PB of indexed content.
- High availability: survive loss of a node and of an availability zone.
- Handle heavy skew — most tables are tiny, a few are hundreds of GB.
Questions your design must answer
- How do row mutations travel from the primary database into the index, and how do you avoid lost or duplicated updates?
- How do you partition the index across machines given extreme table-size skew?
- Describe the full request path from client to aggregated results.
- How do you trade visibility latency against indexing cost, and how would you give an editing user read-your-writes?
Scenarios to reason about
- A user edits one cell in a table with 1 million rows — when does it show up in search?
- One table holds 500 GB of data — how is it spread and searched efficiently?
Hints
Hint 1
Separate correctness (the primary DB is the source of truth, feed the index via change data capture) from freshness (how often segments are made visible) — conflating them is the classic mistake.
Hint 2
Document-based sharding keeps each row in exactly one shard; term-based sharding forces every update and query to touch many shards and creates hot posting lists.
Hint 3
Most tables are small: route them together by base so a query hits a single shard. Give only oversized tables their own hash-partitioned shard set to avoid blanket scatter-gather.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Nail down the numbers first
State assumptions, then let the design follow them.
- Corpus: ~1 PB of row data; inverted index plus stored fields runs roughly 0.5–1× the raw size, so ~1 PB of index; 3 replicas means ~3 PB on disk.
- Shard sizing: 20–50 GB per shard is a good target — big enough to amortize per-shard overhead, small enough that segment merges, recovery, and rebuilds stay cheap. That implies roughly 30–50k primary shards.
- Writes: ~200k row mutations/sec at peak, very bursty (bulk imports, automations).
- Reads: ~50k QPS, and the overwhelming majority are scoped to a single table.
- Skew: most tables are under 10 MB; a handful reach hundreds of GB. This asymmetry is the central design constraint.
Targets: p99 query < 200 ms, update-to-visible p99 ~1–2 s, availability 99.95%+, tolerance of one AZ failure.
2. Ingestion pipeline
Never dual-write from the application into the search cluster. The primary database is the source of truth; if the app crashes between the two writes you get permanent drift, and there is no way to reconcile.
Instead, tail the database's change log (binlog / WAL) with a CDC connector and publish row-level change events to a log (e.g., Kafka), partitioned by table_id. Partitioning by table gives per-table ordering and lets a consumer batch writes destined for the same shard.
Each indexer worker does four things:
- Coalesce several edits to the same row inside a short window (~200 ms) — imports would otherwise generate a write storm.
- Resolve the destination shard from the shard map.
- Bulk-write to the shard's primary.
- Commit the log offset only after the shard acknowledges the write.
Correctness under retries and reordering: attach a monotonically increasing document version (e.g., commit LSN). A shard drops any write whose version is not greater than what it already holds. Replays and duplicates become harmless, and out-of-order delivery cannot resurrect stale content. Deletes become versioned tombstones; segment merging reclaims the space.
Separate traffic classes: schema migrations and bulk backfills go on a low-priority topic so they cannot starve interactive edits.
Rebuild path: snapshot the primary at a recorded log offset, replay forward from that offset. A log retention window of at least a week makes a full index rebuild possible without a fresh snapshot.
3. Sharding strategy
Choose document-based sharding, not term-based. With term-based sharding each posting list lives on one shard: a single row update fans out to one shard per term, multi-term queries require cross-shard posting-list intersection, and common terms create permanent hot nodes. Document-based sharding keeps a complete inverted index over a subset of rows per shard, so a write touches exactly one shard and reads scatter-gather.
Two-tier routing via a metadata service (cached at the query service with local invalidation):
- Small and mid-size tables (the vast majority): route by
base_idand pack many bases onto shared shards. A table-scoped query then hits exactly one shard — no fan-out, latency stays tiny, and the long tail of tiny tables costs almost nothing. - Large tables (above ~20 GB): promote to a dedicated shard set keyed by
hash(row_id) mod N. The metadata service records the shard set per table.
Pre-split into virtual shards. Hash rows into many logical shards (say 256) mapped onto physical nodes. Splitting or rebalancing later just remaps logical shards; no global rehash, no full copy of unrelated data.
The 500 GB example: at ~30 GB per shard that is about 16 shards on 16 different nodes. Each shard only scans ~1/16 of the table, so per-shard work stays in the tens of milliseconds and the fan-out is wide but shallow — well inside 200 ms.
Replication: one primary plus two replicas per shard, spread across AZs. Replicas serve reads. On failure, promote a replica and rebuild a replacement from peer segments.
4. Query path
- API gateway authenticates, rate-limits per tenant.
- Scope resolution: the client sends a scope (table/base/workspace), never a list of table IDs it claims to own. The query service consults a permission service (cached, ~30 s TTL, invalidated on ACL change) to get the allowed tables, then maps them to shards via the shard map.
- Fan-out: send the query to one replica of each relevant shard, using adaptive replica selection (lowest recent latency / load). Attach
table_idfilters so each shard prunes with cached bitsets. - Query phase: each shard returns its local top-k
(doc_id, score). - Fetch phase: retrieve stored fields and highlight fragments for only the global top-k.
- Gather: k-way merge into the final ranked page.
Scoring caveat: BM25 statistics such as IDF are computed per shard. For multi-shard tables, either do a distributed-frequency pre-pass, or accept approximate scores — hash routing keeps shard statistics similar enough that ranking is stable in practice.
Tail-latency control: per-shard timeout around 120 ms, hedged requests (re-issue to another replica once the p95 latency passes), and degrade gracefully with partial: true rather than a hard failure. Cache results keyed by (scope, query, index_generation); paginate with cursors/search_after, never deep offsets.
5. Consistency vs. latency
The index engine only surfaces new writes after a refresh builds a new segment. Refresh on every write produces tiny segments and merge storms that wreck query latency. A ~1 s refresh interval is the standard balance.
End-to-end budget for "edit one cell in a 1M-row table":
| Stage | Time |
|---|---|
| CDC lag | 100–300 ms |
| Log + coalescing window | ~200 ms |
| Bulk index write | ~50 ms |
| Refresh | ≤ 1 s |
| Total | ~1–2 s p99 |
Note the table's total size is irrelevant — only one document is reindexed.
Read-your-writes for the editor: return the commit position with the write response; the client passes it on the next search. If the shard has not yet applied a version at least that new, the query service either waits briefly for the refresh or checks the primary database for the affected row directly, then merges. Avoid making every read wait — the cost is only paid by the writer who just changed something.
Common mistakes
- Dual-writing from the app into the index instead of CDC (silent drift, no recovery).
- Term-based sharding (write amplification, hot posting lists).
- Scatter-gathering every query across all shards even when the table is 2 MB — kills latency and burns fan-out capacity.
- Skipping version numbers, so retries replay stale documents.
- Unsized shards (10 GB vs. 1 TB) or refreshing per write.
- Trusting client-supplied table IDs instead of resolving permissions server-side.