System Design AI

Design a Typeahead for E-commerce Search: Junior, Senior, and Staff Answers

When an interviewer asks you to design a typeahead for an e-commerce site, they are probing three things: how you reason about massive read-heavy traffic, how you keep the user-perceived latency under a tight budget, and how you balance freshness of catalog data against cost. The problem looks simple—return a list of suggestions as the user types—but the design must survive billions of queries per day, handle spikes during sales, and keep the suggestions relevant as inventory changes.

Core Requirements and Driving Numbers

RequirementDetail
LatencyEnd-to-end response under 50 ms for 95th percentile.
ThroughputRoughly 100 k queries per second (≈8.6 billion per day).
Data sizeTens of millions of SKUs; the title, tags and popularity score that suggestions need come to tens of gigabytes.
FreshnessUpdates to product titles or popularity should appear in suggestions within a few minutes.
Availability99.9 % uptime, graceful degradation under load.

These numbers drive every architectural choice. A 100 k QPS load means each request must be served by a small number of highly optimized nodes, and the data path must answer in a few milliseconds: sub-millisecond from Redis, single-digit milliseconds from DynamoDB.

Request Path, One Hop at a Time

  1. Client → CDN: The browser sends an HTTP GET to a CloudFront edge location. The edge caches recent popular prefixes for a few seconds to shave off latency for hot queries.
  2. Edge → API Layer: If the prefix is not in the edge cache, CloudFront forwards the request to an Application Load Balancer (ALB) that terminates TLS and routes to a fleet of stateless API servers (ECS/Fargate). The request payload contains the typed prefix and optional user context.
  3. API → Cache: The API first checks an ElastiCache Redis cluster for the prefix. Keys are of the form typeahead:{prefix}. A cache hit returns the pre-computed suggestion list immediately.
  4. API → Store: On a miss, the API queries a DynamoDB table that stores a prefix index. Each item holds a prefix (up to 5 characters) and a sorted list of product IDs based on popularity. The query is an exact-match lookup on the partition key, using the typed prefix truncated to 5 characters.
  5. Store → Result Assembly: The API fetches product details (title, image URL, price) from a second DynamoDB table keyed by product ID. It assembles the top-N suggestions, applies any business rules (e.g., filter out out-of-stock items), and writes the result back to Redis with a short TTL (e.g., 5 seconds).
  6. Response → Client: The API returns a JSON array of suggestions. CloudFront caches the response for the TTL, so subsequent identical queries from nearby users hit the edge cache.

Data Model

  • Prefix Index Table (DynamoDB): Partition key = prefix (string, up to 5 chars), no sort key. Each prefix is one item holding up to 50 product IDs, already ordered by popularity score, so the lookup is a single GetItem.
  • Product Detail Table (DynamoDB): Partition key = productId. Attributes = title, imageUrl, price, stockStatus.
  • Redis Cache: Key = typeahead:{prefix} → Value = serialized suggestion list.

Key Choice

Using DynamoDB for the prefix index gives predictable single-digit millisecond latency at any scale and automatic sharding by prefix. Alternatives like Elasticsearch provide richer full-text search but add operational complexity and higher cost for a use-case that only needs prefix matching. The design therefore chooses DynamoDB over Elasticsearch for simplicity, cost, and the ability to guarantee latency.

What a Junior Answer Covers

  • Lists the basic flow (client → API → DB → response).
  • Mentions using a relational store (e.g., MySQL/Aurora) for product data and a simple in-memory cache (Redis).
  • Provides rough latency and QPS numbers.
  • Draws a diagram with the components and notes what each does.
  • Shows awareness of cache-aside pattern and TTL.

What a Senior Answer Adds

  • Introduces a prefix index table to avoid full-text scans.
  • Discusses hot prefixes: one- and two-letter prefixes are a handful of items read by most requests, and DynamoDB cannot split a single item across partitions, so they are served from the edge and Redis (or copied under several suffixed keys) rather than left to the table.
  • Adds read-through cache with Redis and explains cache invalidation via a background worker that consumes product-update events from an SQS queue.
  • Considers fallback to a slower search service (e.g., OpenSearch) for long prefixes or misspelled queries.
  • Mentions monitoring (CloudWatch metrics for cache hit ratio, latency, and error rates) and auto-scaling policies for the API fleet.

What a Staff Answer Adds

  • Failure Modes: Discusses CDN edge cache loss, Redis node failure, DynamoDB throttling, and network partitions. Proposes multi-AZ Redis replication, DynamoDB on-demand capacity, and circuit-breaker patterns in the API.
  • Operations: Details deployment pipeline (CodePipeline → ECS rolling update), canary testing, and log aggregation (CloudWatch Logs). Describes a runbook for cache warm-up after a deployment.
  • Cost Analysis: Rough estimate – DynamoDB is billed per read, and 100 k QPS each needing a prefix lookup plus product reads would be the dominant cost if every request reached the table, so the estimate hinges on the cache hit ratio: with about 99 % of requests served by CloudFront and Redis, the table sees about 1 k QPS; a three-node Redis cluster is a fixed cost on top. Uses cost-benefit argument to justify DynamoDB over a managed Elasticsearch cluster.
  • Trade-off Defense: Defends the decision to limit prefix length to 5 characters to keep the index size manageable, acknowledging that longer prefixes would improve relevance but increase storage and write amplification. Shows how the design can be extended with a fallback to a full-text service for those cases.
  • Data Freshness Pipeline: Describes a Kinesis Data Stream that captures product catalog changes, a Lambda consumer that updates the prefix index in DynamoDB, and a small delay (2-5 minutes) before the new suggestions appear.

Mistakes That Sink This Question

MistakeWhy It Hurts
Ignoring latency budgetLeads to designs that require full database scans, which cannot meet 50 ms target at 100 k QPS.
Over-engineering with heavy NLPAdds unnecessary complexity and cost; typeahead mostly needs prefix matching plus light typo tolerance.
Forgetting misspellingsUsers type quickly; not handling fuzzy matches results in poor UX and shows lack of product thinking.
Not accounting for hot prefixesA few popular prefixes can dominate traffic; without sharding or cache, the system will hot-spot and throttle.
Skipping cache invalidationStale suggestions hurt conversion and demonstrate operational blind spots.

How to Practice This

  1. Study the worked design, Design ML-Ranked Query Autocomplete, part of Pro ($10/month), to see a concrete board that walks through each component and its notes.
  2. Write your own answer on a blank canvas: start with the request path, then add the data model, caching strategy, and finally the staff-level extensions.
  3. Run a mock interview with a peer, or check your sketch against the practice brief's rubric (free to read), and iterate until the senior and staff sections feel natural.

Questions people ask

What latency should I aim for in a typeahead service?

Aim for sub-50 ms response for the 95th percentile. Users expect suggestions to appear instantly as they type.

Why use DynamoDB instead of Elasticsearch for prefix matching?

DynamoDB provides predictable single-digit millisecond reads, automatic sharding, and lower operational overhead. Elasticsearch offers richer text search but adds latency and cost that are unnecessary for strict prefix matches.

How do I handle hot prefixes like "sh" for shoes?

Serve them from the edge cache and Redis, which absorb most of the traffic; if the table still sees too many reads for one prefix, store copies under several suffixed keys (sh#1, sh#2 and so on) and read one at random.

What is a simple way to keep suggestions fresh without breaking latency?

Stream catalog updates through Kinesis, process them with Lambda, and update the DynamoDB prefix index asynchronously. The cache TTL ensures new data propagates within a few minutes.