Design an In-Memory Auto-Complete Service and Scale It Self-Contained
System DesignModel answerLast updated
Design an autocompletion engine using a custom in-memory trie, cover node memory optimizations and hot swaps, and scale out horizontally without adding third-party clusters.
Design an autocompletion service for a search input field. When a user types characters into the search bar, the service returns a ranked list of relevant search terms starting with that prefix.
Requirements & Constraints
- Initial Scope: You must construct the suggestion index yourself as an in-memory Trie data structure embedded within the application service, rather than relying on external search platforms (e.g., Elasticsearch, OpenSearch) or external key-value stores.
- Self-Contained Scaling: When system traffic grows beyond a single host, you must scale the architecture out horizontally without introducing any new external middleware or platforms (such as external distributed caches, external coordination clusters like ZooKeeper/Etcd, or dedicated search engines).
Structure Your System Design Response Into Four Parts:
-
Part 1: Requirements & Resource Estimates
- Define functional capabilities (ranking criteria, top-$K$ limits, freshness).
- Define SLA metrics (latency target, peak QPS, target dataset size).
- Provide a back-of-the-envelope memory budget for storing the dataset in a custom Trie structure versus alternative systems.
-
Part 2: In-Memory Trie Architecture & Storage Mechanics
- Detail the internal node layout, pointer structures, and child lookup strategies.
- Explain how top-$K$ suggestions per prefix are calculated and cached at intermediate nodes without needing full subtree traversals during runtime queries.
- Describe string deduplication strategies to minimize memory overhead.
-
Part 3: Read Path, Dynamic Updates, & Zero-Downtime Hot Swaps
- Walk through the step-by-step query execution flow from the edge client to the final response.
- Discuss the write path: handling real-time popularity score updates vs. batch index rebuilds.
- Explain the mechanism for atomic index updates ("hot swapping") on a live instance without blocking concurrent read operations or causing tail-latency spikes.
- Outline index validation and failure recovery/rollback strategies.
-
Part 4: Distributed Scaling Without External Dependencies
- Propose a horizontal partitioning (sharding) and replication topology managed strictly within the application instances.
- Detail request routing logic: evaluate prefix-based vs. hash-based sharding and address query fan-out costs.
- Explain how you handle traffic hot-spots (e.g., short or popular prefixes like "a", "sh", "iphone").
- Describe how batch rebuilds and real-time score updates propagate across distributed nodes.
Hints
Hint 1
Calculate the memory cost per node assuming standard 64-bit memory addresses versus array-indexed offsets.
Hint 2
Caching top-K candidate references directly at prefix root nodes eliminates DFS traversals during query execution, reducing query complexity to O(L) where L is prefix length.
Hint 3
For zero-downtime batch updates, consider double-buffering using an atomic pointer swap (Read-Copy-Update pattern) combined with memory mapped files or shared memory segments.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
System Architecture: Self-Contained In-Memory Autocomplete Engine
Part 1 — Requirements & Resource Estimates
Functional Requirements
- Prefix Match: Given a query string prefix of length $L$, return the top $K=5$ most relevant completion keywords.
- Deterministic Ranking: Ranking is based on a composite score derived from search frequency, historical click-through rates (CTR), and a recency decay factor: $$\text{Score}(w) = \text{Freq}(w) \times \text{CTR}(w) \times e^{-\lambda t}$$
- Freshness Target:
- Batch Updates: Daily re-indexing for global search frequency and vocabulary updates.
- Real-Time Adjustments: Hot search score bumps reflected within $\le 60 \text{ seconds}$.
- Normalizations: Case-insensitive matching, basic Unicode folding (accent removal), and whitespace stripping.
Non-Functional Requirements & Metrics
- Dataset Size: 10,000,000 (10M) unique valid completion phrases.
- Average Phrase Length: 20 characters ASCII ($\sim 20 \text{ bytes}$).
- Latency Target: $p_{99} \le 10 \text{ ms}$ server-side response time ($p_{95} \le 5 \text{ ms}$).
- Throughput Target: Peak load of $50,000 \text{ Queries Per Second (QPS)}$.
- Availability: $99.99%$ uptime.
Memory Estimation
Let's compare a naive implementation against an optimized Trie:
-
Naive Standard Pointer Trie:
- Total characters across 10M words (assuming partial prefix sharing): $\sim 50\text{M nodes}$.
- Each node contains a map or fixed array of 26 pointers ($26 \times 8 \text{ bytes} = 208 \text{ bytes}$) + payload pointers + flags $\approx 240 \text{ bytes/node}$.
- Total Memory: $50\text{M nodes} \times 240 \text{ bytes} \approx 12 \text{ GB}$.
-
Optimized Compact Trie Structure:
- Node array storing children using dynamic contiguous arrays or 32-bit offset indices instead of 64-bit pointers.
- Global String Storage: Deduped strings in a single contiguous byte array.
- Node footprint reduced to $\sim 24 \text{ bytes/node}$.
- Total Memory for 50M nodes: $50\text{M} \times 24 \text{ bytes} = 1.2 \text{ GB}$.
- Cache of Top-$K$ references per prefix node: $5 \text{ IDs} \times 4 \text{ bytes} = 20 \text{ bytes}$.
- Total Index Memory Budget: $\sim 2.5 \text{ GB} - 3 \text{ GB}$, easily fitting within standard server RAM (e.g., 16 GB - 64 GB instances).
Buy vs. Build Rationale
While off-the-shelf engines (Elasticsearch, Redis Search) offer completion plugins, an embedded custom Trie avoids network hop overheads, eliminates external operational dependencies, allows microsecond-level prefix lookups, and reduces deployment footprint during early to medium scale stages.
Part 2 — Trie Internals & Keyword Storage
To minimize garbage collection overhead and memory fragmentation, the entire Trie is laid out inside contiguous arrays (flattened Trie representation).
[ Global Keyword Table ]
ID 0: "apple" (Score: 9800)
ID 1: "app store"(Score: 8500)
ID 2: "application" (Score: 6200)
[ Trie Node Memory Layout ]
+-----------------------+------------------------+----------------------------------+
| Child Map / Encoding | Word ID (If Terminal) | Top-K List [ID_0, ID_1, ... ID_4]|
| (Dense/Sparse Format) | (-1 if non-terminal) | (Fixed array of 4-byte integers) |
+-----------------------+------------------------+----------------------------------+
Node Structure Design
struct TopKEntry {
uint32_t keyword_id;
float score;
};
struct CompactTrieNode {
// Top 5 pre-computed recommendations for the prefix represented by this node
uint32_t top_k[5];
uint8_t top_k_count;
// Terminal state: Index into central Keyword Repository; UINT32_MAX if non-terminal
uint32_t keyword_id;
// Child management:
// If child_count <= 4: Inline array of char-to-index pairs
// If child_count > 4: Index into a dynamically allocated contiguous child vector
uint8_t child_count;
union {
struct { char c; uint32_t child_idx; } inline_children[4];
uint32_t indirect_children_offset;
} children;
};
Memory Optimizations & String Deduplication
- Central Keyword Repository: Strings are stored exactly once in a single global read-only buffer (
char[]). Keywords are identified across the Trie by auint32_t keyword_id. - Pre-computed Top-$K$ at Node Level:
- Each node explicitly caches the top $K$
keyword_ids present in its subtree. - Query Complexity: For a prefix of length $L$, lookup time is strictly $\mathcal{O}(L)$. Once the node corresponding to character $L$ is reached, the pre-calculated
top_karray is returned immediately in $\mathcal{O}(1)$ without traversing child subtrees.
- Each node explicitly caches the top $K$
Part 3 — Read Path, Updates, & Hot Swaps
The Read Path
- Request Ingress: HTTP/2 or gRPC request arrives with prefix string $P$ (e.g.,
P = "app"). - Normalization: Clean input (lowercase, strip trailing spaces, unicode fold) $\rightarrow$
"app". - Prefix Traversal:
- Start at Trie Root (
node_idx = 0). - For character $c$ in
"app": locate child matching $c$. If child does not exist, return empty list[].
- Start at Trie Root (
- Materialization:
- Extract
top_karray from final node"app". - Resolve
keyword_ids to string literals and scores from the global string table.
- Extract
- Response Delivery: Return JSON/Protobuf array to client. Target execution duration: $< 0.5 \text{ ms}$.
Client ----( "app" )----> [ Autocomplete Host ]
|
1. Normalize("app") -> "app"
|
2. Trie Walk: Root -> 'a' -> 'p' -> 'p'
|
3. Read Node.top_k -> [ID_0, ID_1, ID_2]
|
4. Dereference IDs from Keyword Table
|
<--- [ "apple", "app store", "application" ] ---
The Write Path & Incremental Updates
High-frequency, real-time rank adjustments are stored in an In-Memory Score Override Hash Map:
std::unordered_map<uint32_t, float> real_time_score_deltas;
When reading top_k results, if real-time overrides exist, the engine merges the static base scores with the delta scores dynamically in a local min-heap before sending output.
Zero-Downtime Hot Swapping (Read-Copy-Update / Double Buffering)
For heavy batch updates (e.g., full daily trie rebuilds), in-place updates risk race conditions or expensive locking overhead. Instead, we use double buffering with an atomic pointer swap:
class AutocompleteEngine {
private:
struct IndexBuffer {
std::vector<CompactTrieNode> nodes;
std::vector<std::string> keyword_table;
};
std::shared_ptr<const IndexBuffer> active_index_;
std::mutex rebuild_mutex_;
public:
// Read Path (Lock-Free)
std::vector<std::string> Query(const std::string& prefix) {
auto index = std::atomic_load(&active_index_);
// Traverse index->nodes safely without locking
return SearchTrie(index, prefix);
}
// Write Path (Hot Swap)
void SwapNewIndex(std::unique_ptr<IndexBuffer> new_index) {
std::lock_guard<std::mutex> lock(rebuild_mutex_);
// Atomically replace pointer. Old index reclaimed when existing queries finish.
std::atomic_store(&active_index_, std::shared_ptr<const IndexBuffer>(std::move(new_index)));
}
};
Validation & Rollback Strategy
- Health Verification: Before swapping, validate candidate snapshot metrics: check total node counts, verify non-empty top-$K$ for canary prefixes (e.g.,
"a","th"), and measure structural integrity. - Rollback: Maintain the previously active
IndexBufferreference in memory for a 5-minute grace period. If query error rates exceed $0.01%$, immediately triggeratomic_storeback to the fallback index.
Part 4 — Distributed Scaling Without External Dependencies
When total throughput exceeds $50,000 \text{ QPS}$ or the dataset scales beyond single-host memory boundaries, we scale horizontally using self-managed peer-to-peer clustering built directly into application binary instances.
Sharding Topology: Range / Fixed Prefix vs. Hash Sharding
| Strategy | Routing Logic | Pros | Cons |
|---|---|---|---|
| Hash-Based | Hash(keyword) % N | Uniform memory distribution across nodes. | High Query Fan-Out: Prefix searches must query all $N$ shards and merge top-$K$ results ($O(N)$ fan-out cost). |
| Prefix Range Sharding | First char/2-chars assigned to specific Shard Node (e.g., Node 1 handles a-c, Node 2 handles d-f). | Zero Fan-Out: Queries route to exactly 1 shard ($O(1)$ routing cost). | Traffic & Data Skew: Common prefixes like s, t, a receive disproportionate traffic. |
Selected Approach: Partitioned Range Sharding with Dynamic Sub-Prefix Splitting.
- Shard key is determined by the first 2 characters of the prefix (e.g.,
"ap","ba"). - Single-character queries (
"a") fan out to all sub-shards handling prefixes starting with"a", or are served directly by local top-$K$ root caches duplicated across all instances.
[ Edge Load Balancer / Proxy ]
|
+-----------------------+-----------------------+
| (Prefix: "app") | (Prefix: "ba") | (Prefix: "c")
v v v
+-------------------+ +-------------------+ +-------------------+
| Shard Group A-E | | Shard Group F-O | | Shard Group P-Z |
| (Primary + Repls) | | (Primary + Repls) | | (Primary + Repls) |
+-------------------+ +-------------------+ +-------------------+
Hot-Spot Handling Strategy
- Replication Ratio Scaling: Heavily accessed shards (e.g., prefixes starting with
"s","i") are assigned higher replication counts (e.g., 10 replica nodes) compared to low-traffic shards (e.g.,"z"having 2 replica nodes). - Top-Level Prefix Caching at Gateway Layer:
- A static pre-computed index of 1-character and 2-character prefix completions (which account for $\sim 40%$ of total query volume) is embedded in memory on all application instances. Queries of length $L \le 2$ are answered directly at the entry node without hitting shard networks.
Peer-to-Peer Cluster State Synchronization
Without ZooKeeper or Consul:
- Gossip Protocol: Node membership, status, and prefix-to-shard mapping tables are shared across all instances via a background Gossip protocol (SWIM protocol implementation).
- Snapshot Propagation: When a primary index builder node finishes generating a new serialized binary Trie snapshot, it notifies cluster peers over HTTP/2. Nodes pull the snapshot file directly via HTTP range requests and perform an atomic local hot-swap.