Design an E-Commerce Search and Typeahead System
System DesignModel answerLast updated
Architect a low-latency prefix typeahead and full-catalog product search system capable of handling high traffic spikes and near real-time inventory updates.
Scenario
Design the search subsystem for a global e-commerce platform. The system powers two core features in the user search flow:
- Prefix Autocomplete: As users type into the input field, the interface displays matching query terms and product categories in under 30 milliseconds.
- Product Catalog Search: When a user submits a query, the platform presents ranked product listings with multi-attribute filtering (such as price, condition, category, and delivery options), dynamic facets, sorting, and pagination.
System Requirements
Functional Scope
- Provide the top 5 to 10 matching query terms and category links as the user types (prefix matching).
- Perform full-text search over product titles, descriptions, and metadata.
- Support faceted search, multi-field filtering, custom sorting (e.g., price, relevance, creation date), and pagination.
- Ensure prompt reflection of catalog updates (out-of-stock items, price drops, or newly created listings).
- Utilize user interactions (click-through rates, searches, conversion rates) to continuously update suggestion rankings and search relevance.
Constraints & Operational Targets
- Catalog Volume: 500 million active inventory items.
- Traffic Volume: 20,000 requests per second (RPS) average for full search (peaking at 60,000 RPS). Autocomplete traffic peaks at 100,000 RPS at the origin prior to edge throttling/caching.
- Latency Budgets:
- Autocomplete p99 < 30 ms.
- Catalog Search p99 < 150 ms.
- Availability Target: 99.99% availability.
Evaluation Criteria
Your design should cover:
- Data Ingestion & Invalidation: How changes in inventory status flow into search indices and autocomplete dictionaries.
- Dual Execution Paths: Trade-offs between dedicated custom trie engines versus off-the-shelf distributed search indices (e.g., OpenSearch / Elasticsearch completion engines) for typeahead.
- Caching Strategy: Multi-tiered caching layer across client, CDN, and backend caches to offload high-volume keystroke operations.
- Pagination Mechanics: Efficient mechanisms for deep pagination and handling transient listing updates during user sessions.
- Relevance & Content Moderation: Filtering zero-result queries, suppressing offensive or forbidden terms, and evaluating ranking performance.
Hints
Hint 1
Decouple the typeahead latency path from the heavy catalog search path, as their SLA, memory profiles, and query models differ significantly.
Hint 2
Estimate the size of the curated autocomplete dictionary; you may find it fits entirely inside RAM, which simplifies horizontal scaling via full replication.
Hint 3
Avoid offset-based deep pagination (e.g., OFFSET 10000) on distributed search engines; use cursor-based pagination with a point-in-time snapshot instead.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
System Architecture Overview
To achieve both p99 < 30 ms typeahead suggestions and p99 < 150 ms full-catalog search with complex filtering, the design splits the workflow into two dedicated sub-systems:
- Autocomplete Service: Optimized for sub-millisecond prefix-lookups over a curated string dictionary.
- Search Cluster: Optimized for full-text inverted indexing, structured attribute filtering, dynamic facet generation, and relevance scoring across 500M items.
+-------------------------------------------------------------------------------+
| Client |
| (Debounce 100ms, Client Caching) |
+---------------------------------------+---------------------------------------+
|
HTTPS requests
|
v
+-------------------------------------------------------------------------------+
| CDN / Edge Processing |
| (Cache short prefixes e.g. "a", "ap") |
+---------------------------------------+---------------------------------------+
|
v
+-------------------------------------------------------------------------------+
| API Gateway |
| (Authentication, Rate Limiting, Routing) |
+-------------------+-----------------------------------+-----------------------+
| |
GET /v1/suggest GET /v1/search
| |
v v
+-----------------------------------+ +---------------------------------------+
| Autocomplete Service | | Search Service |
| (In-Memory Custom Trie Nodes) | | (Query Parser, Blending, Facets) |
+-----------------+-----------------+ +-------------------+-------------------+
^ |
| Read-through v
+-----------------+-----------------+ +---------------------------------------+
| Redis Cluster | | Search Cluster |
| (Hot Prefix Cache) | | (OpenSearch / Vespa Shards) |
+-----------------------------------+ +---------------------------------------+
1. Capacity & Scale Estimation
Catalog & Search Index Scale
- Active Listings: 500 million documents.
- Document Payload: ~2 KB of searchable text and metadata per item.
- Raw Document Data: $500\text{M} \times 2\text{ KB} = 1\text{ TB}$.
- Index Overhead: Including inverted index postings, doc values for facets, and triply-replicated search shards: $$\text{Total Storage Requirement} \approx 1\text{ TB} \times 2\text{ (index ratio)} \times 3\text{ (replication factor)} = 6\text{ TB}$$
Autocomplete Dictionary Scale
- Unique Suggestions: Assuming 20 million high-quality query strings per market/locale after pruning low-volume queries.
- Memory Footprint:
- 20 million terms $\times$ ~30 bytes average length $\approx 600\text{ MB}$ raw strings.
- Formatted into a weighted radix/trie tree storing top-10 candidate string IDs per node: $$\text{Trie Memory Footprint} \approx 4\text{ GB -- } 8\text{ GB per locale}$$
- Key Insight: Because 8 GB easily fits into a single instance's RAM, the entire suggestion dictionary can be fully replicated across all suggestion nodes rather than sharded.
2. API Design
2.1 Autocomplete API
GET /v1/suggest?q=iph&locale=en_US&limit=8
Response (200 OK):
{
"prefix": "iph",
"suggestions": [
{
"text": "iphone 15 pro case",
"type": "query"
},
{
"text": "iphone chargers",
"type": "query"
},
{
"text": "iphone",
"type": "category",
"category_id": 9355,
"category_name": "Cell Phones & Accessories"
}
]
}
2.2 Search API
GET /v1/search?q=iphone+15&locale=en_US&category=9355&price_min=100&price_max=500&sort=relevance&limit=48&cursor=eyJzY29yZSI6OS4yLCJpZCI6OTg0MzIxNX0=
Response (200 OK):
{
"total_hits": 14200,
"next_cursor": "eyJzY29yZSI6OC45LCJpZCI6MTIwNDk4Mn0=",
"items": [
{
"id": "item_9843215",
"title": "Apple iPhone 15 - 128GB - Unlocked",
"price": 499.99,
"currency": "USD",
"condition": "Used",
"seller_rating": 4.9,
"image_url": "https://cdn.example.com/items/9843215.jpg"
}
],
"facets": {
"categories": [
{"id": 9355, "name": "Cell Phones", "count": 12100},
{"id": 1014, "name": "Accessories", "count": 2100}
],
"conditions": [
{"name": "New", "count": 8200},
{"name": "Used", "count": 6000}
]
}
}
3. Dedicated Typeahead Engine vs. Search Cluster Suggester
Evaluating architecture choices for the Typeahead engine:
| Metric | In-Memory Custom Trie Service | Distributed Search Suggester (e.g., OpenSearch Completion) |
|---|---|---|
| p99 Latency | < 2 ms (Direct RAM pointer traversal) | 10–25 ms (Lucene FST evaluation over multiple segments) |
| Memory Efficiency | High (Custom compact data structures) | Moderate (JVM heap overhead, garbage collection pauses) |
| Deployment Complexity | Requires custom binary build pipeline | Out-of-the-box system reuse |
| Dynamic Real-Time Filtering | Custom implementation needed | Built-in context filtering support |
| Scaling Pattern | Standard horizontal read-replica scaling | Shard replication + JVM scaling |
Decision: Deploy a specialized In-Memory Trie Service written in C++/Rust or Go for reading operations, backed by snapshot loading from Object Storage (S3). Fall back to OpenSearch completion suggesters only for low-traffic locales where maintaining custom deployment infrastructure is cost-prohibitive.
4. End-to-End Data Pipelines & Freshness
[ Batch Pipeline ]
+-------------------+ +-------------------------+ +-------------------+
| Logs (Search, | ---> | Spark Offline Pipeline | ---> | Base Trie |
| Clicks, Purchases)| | (Decay, Filtering) | | Snapshot (S3) |
+-------------------+ +-------------------------+ +---------+---------+
|
v
+-------------------+
| Trie Service |
| Memory Swap |
+---------^---------+
|
[ Real-Time Path ] |
+-------------------+ +-------------------------+ +---------+---------+
| Listing DB | ---> | CDC (Debezium / Kafka) | ---> | Flink Delta Engine|
| (Updates, Sales) | +------------+------------+ | (Suppression) |
+-------------------+ | +-------------------+
v
+-------------------------+
| Search Indexer Service |
| (OpenSearch Bulk Writes)|
+-------------------------+
4.1 Autocomplete Pipeline
- Offline Processing (Daily):
- Aggregates the last 30 days of search queries, click logs, and purchases from Kafka/S3 using Apache Spark.
- Applies an exponential time decay score to prefer recent trends: $$\text{Score} = \text{Searches} \times \text{CTR} \times \text{Conversion Rate} \times e^{-\lambda t}$$
- Runs a filtering job:
- Removes terms with zero active inventory matches.
- Strips profanity and policy-violating strings using a blocklist filter.
- Outputs an optimized Trie data structure snapshot to S3.
- Real-Time Delta Processing:
- Apache Flink monitors CDC events for item deletions or out-of-stock changes.
- If a query's active result count drops to 0, a Suppression Message is broadcast to all Trie nodes to temporarily suppress the term from output via a dynamic dynamic bitset.
4.2 Catalog Indexing Pipeline
- Database writes (price edits, inventory deductions) trigger CDC events published to Kafka topics, partitioned by
item_id. - The Search Indexer processes updates in batches using bulk operations sent to the Search Cluster.
- Near real-time (NRT) updates become visible for search operations within 1–2 seconds.
5. Multi-Tier Caching Strategy
+-------------------------------------------------------------------------------+
| Client Browser: Debounce (100ms) + Local Session Storage Cache |
+---------------------------------------+---------------------------------------+
| (Cache Miss)
v
+-------------------------------------------------------------------------------+
| Edge / CDN: Cache 1-3 char prefixes (TTL: 10 mins, Key: locale:prefix) |
+---------------------------------------+---------------------------------------+
| (Cache Miss)
v
+-------------------------------------------------------------------------------+
| Redis Cluster: Top 100k hot prefixes (TTL: 60 seconds) |
+---------------------------------------+---------------------------------------+
| (Cache Miss)
v
+-------------------------------------------------------------------------------+
| Trie Nodes: In-Memory Read Traversal |
+-------------------------------------------------------------------------------+
- Client Tier:
- 100 ms debounce on keyboard inputs prevents sending unneeded requests.
- In-memory request caching maps inputs to results during the active session.
- Stale out-of-order API responses are ignored via request sequencing tokens.
- Edge / CDN Tier:
- Short prefixes (e.g.,
a,ip,iph) exhibit high access overlap across users. - Cache short prefixes at CDN POPs with a short TTL (5–10 minutes).
- This absorbs up to 50% of peak keystroke traffic before it reaches origin servers.
- Short prefixes (e.g.,
- Application Cache Tier:
- Hot queries for both autocomplete and search page 1 results are kept in a Redis cluster with an LRU eviction policy.
6. Pagination & Deep Browsing Mechanics
To navigate search listings safely without high latency or memory spikes, avoid deep offsets (such as from: 10000, size: 48). Deep offsets force every search shard to collect, sort, and return from + size items to the coordinator host, resulting in $O(\text{shards} \times (\text{offset} + \text{limit}))$ processing costs.
Cursor-Based Navigation (search_after)
Use cursor-based pagination backed by point-in-time (PIT) index states:
- Sort queries using a composite key containing the target ranking score along with a unique tie-breaker:
[score DESC, item_id ASC]. - Generate an encrypted, opaque cursor token encoding the sort values of the final item on the current page.
- The client submits this token with the next request, enabling shards to seek directly past the corresponding index entry:
{
"size": 48,
"query": { "match": { "title": "iphone 15" } },
"search_after": [8.9, "item_1204982"]
}
This reduces computational overhead on deep pages to $O(\text{shards} \times \text{limit})$.
7. Operational Guardrails & Edge Cases
- Zero-Result Prevention:
- The offline dictionary generator validates candidate terms against the primary catalog index. Terms generating zero search hits are excluded during dictionary generation.
- Handling Inventory Depletion:
- Item status updates (e.g.,
status: sold) write partial updates to the primary search index. - Search queries include a mandatory filter:
status = active.
- Item status updates (e.g.,
- Flash Sales & Event Traffic Spikes:
- Edge networks handle basic rate-limiting per IP address.
- If origin load reaches critical levels, the system serves typeahead suggestions exclusively from edge caches and fallback static dictionaries, bypassing origin compute clusters completely.
Common Pitfalls to Avoid
- Unified Infrastructure Bottlenecks: Combining autocomplete prefix execution and full-catalog multi-attribute search into the same search cluster infrastructure leads to noisy-neighbor issues and SLA violations.
- Naïve Offset Pagination: Using
OFFSETpagination for deep result sets causes high memory usage and response degradation on search clusters. - Trie Sharding via First Character: Partitioning trie systems by first character (e.g., Routing 'a' to Node 1, 'b' to Node 2) creates severe load hot-spotting on popular letters like 's' or 'a'. Prefer hash-based partitioning or full dataset replication.
- Real-Time Synchronous Trie Edits: Applying mutation updates directly to production trie memory structures can induce lock contention and memory fragmentation. Use immutable snapshot replacement with real-time delta suppression filters instead.