Design the Infrastructure Behind a Recommendation Feed
System DesignModel answerLast updated
Design the serving and storage layers for a recommendation service, covering API shape, data flow, storage schemas, caching, and how batch training coexists with live traffic.
The Problem
A product team wants to launch a personalized recommendation feed — think a home feed, a "you might also like" rail, or a weekly digest email. Your job is to design the backend infrastructure that powers it.
You are not designing the ML model itself. You are designing everything around it: how clients fetch recommendations, how user interactions are collected and stored, how the model reads training data, and how the serving layer stays fast and available under load.
A strong answer will:
- State your scale assumptions before drawing any boxes
- Sketch the API contract for both fetching recommendations and logging events
- Describe the high-level architecture, including the read and write paths separately
- Define the storage schemas for users, items, and interaction events — including indexing and partitioning choices
- Explain how a daily batch training job and a low-latency serving layer can share the same data without interfering with each other
- Discuss how you would handle scaling, fault tolerance, and freshness requirements
There is no single correct architecture. Interviewers want to see that you can reason through trade-offs, not that you have memorized a diagram.
Hints
Hint 1
Start by separating the read path (serving recommendations) from the write path (ingesting interaction events). They have very different scale characteristics and should be designed independently before you connect them.
Hint 2
Think carefully about how the interaction log is stored in multiple forms for different purposes: a message bus for transport, an object store for training, and a row store for online feature lookups. Each has different access patterns and consistency requirements.
Hint 3
Train/serve skew is one of the most common failure modes in real recommendation systems. Think about how you would log the exact features used at serve time so you can reproduce training labels accurately.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Step 1: Pin Down Requirements and Scale
Never start drawing boxes before agreeing on what you are building. State your assumptions out loud.
Functional scope:
- Return a ranked list of items for a given user and surface (home feed, similar items, digest email).
- Ingest interaction signals: impressions, clicks, add-to-cart, purchases, ratings.
- Support daily batch model retraining on historical interaction data.
Scale assumptions (state these explicitly):
- 50M monthly active users, 10M daily active users, 10M items in the catalog.
- Recommendation reads: 10M DAU × 20 requests/day ≈ 200M/day → ~2.3k QPS average, ~10k QPS peak.
- Interaction writes: ~100 events/user/day → 1B/day → ~12k writes/s average, ~50k/s peak.
- At ~150 bytes per event, that is ~150 GB/day raw, or roughly 50 TB/year uncompressed.
Non-functional targets:
- p99 end-to-end latency < 200 ms; p99 server-side < 100 ms.
- Event ingestion is fire-and-forget from the client's perspective.
- A new click should influence recommendations within seconds to a few minutes; model retraining can be daily.
- Item takedowns (out of stock, policy removal) must stop surfacing within roughly one minute.
- 99.9%+ read availability. A degraded response (popular or trending items) is preferable to an error.
The central insight is that this system is write-heavy on events and read-heavy on recommendations. Those two paths must be decoupled end to end.
Step 2: API Design
GET /v1/recommendations?surface=home&limit=20&cursor=abc
Authorization: Bearer <token> # user_id is derived from token, never in the URL
→ 200 {
"request_id": "r-789",
"items": [
{ "item_id": "i-001", "score": 0.91, "reason": "because_you_viewed" }
],
"next_cursor": "xyz"
}
POST /v1/events # batched, async from the client
{
"events": [
{
"event_id": "uuid-123", # client-generated idempotency key
"item_id": "i-001",
"signal": "click",
"ts": "2024-05-01T12:00:00Z",
"request_id": "r-789" # ties the click back to the exact list served
}
]
}
→ 202 Accepted
Three design details worth calling out explicitly:
request_idlinks every downstream click or purchase back to the exact ranked list that was shown. This is essential for attribution, CTR measurement, and point-in-time feature logging.event_idis a client-generated UUID. The server deduplicates on it, so client retries on network failures do not inflate event counts.- Client-side batching: flush events every few seconds or on page unload. Cursor-based pagination on the read side ensures a user scrolling to page 2 does not see duplicates.
Step 3: High-Level Architecture
Read path
Client → CDN/edge (TLS termination, auth, rate limiting) → L7 load balancer → stateless Rec API servers (autoscaled, multi-AZ).
On each request the Rec API:
- Checks a per-user rec cache in Redis (
rec:{user_id}:{surface}, TTL 10–30 min). - On a miss, runs candidate generation in parallel: ANN lookup over item embeddings, co-visitation lists, trending items, and the user's recent interactions. Targets ~1,000 candidates total.
- Fetches features from the online feature store (batched multi-get).
- Calls the ranking model server for scored predictions.
- Applies post-filters: already purchased, out of stock, policy blocks, diversity rules.
- Returns the response and asynchronously logs the served list with its features, keyed by
request_id.
Approximate server-side latency budget:
| Step | Budget |
|---|---|
| Cache check | 2 ms |
| Candidate generation (parallel) | 20 ms |
| Feature fetch | 15 ms |
| Ranking inference | 30 ms |
| Filtering | 5 ms |
| Headroom | ~28 ms |
Write path
Client → Event Collector (stateless, horizontally scaled) → Kafka (topic interactions, partitioned by user_id hash for per-user ordering, 7-day retention for replay).
Three consumer groups read from Kafka independently:
- A stream processor (Flink or similar) updates online features and short-window counters (e.g., item clicks in the last hour) within seconds.
- A lake sink writes Parquet files to object storage, partitioned by
dt/hour. - A metrics consumer feeds dashboards and anomaly detection.
Step 4: Storage Schemas
Users — relational (Postgres, sharded by user_id when needed):
users(user_id PK, created_at, locale, country, segment, consent_flags, updated_at)
Low write volume, source of truth for profile and consent data.
Items — relational source of truth with CDC to downstream caches and the ANN index:
items(item_id PK, title, category_id, brand, price, status, attributes JSONB, created_at, updated_at)
Index on (category_id, status) for cold-start and popular-by-category queries. Status changes propagate via CDC within seconds, which is how you meet the one-minute takedown SLA.
Interaction log — stored in three separate representations, each optimized for a different access pattern:
- Kafka (transport): fields
event_id, user_id, item_id, signal, value, event_ts, ingest_ts, request_id, surface. Partitioned byuser_id. - Lake (training): immutable Parquet, partitioned by
dt/hour, sorted byuser_id. Training scans by time range, uses event time for windows, and deduplicates onevent_idduring compaction. - Online recent-interactions store (Cassandra / Bigtable / DynamoDB): partition key
user_id, clustering keyevent_ts DESC, TTL 90 days, capped at ~500 rows per user. Serves "last N interactions" in a single partition read. Do not partition by time — that creates a hot partition on "now".
Feature store:
- Offline: keyed by
(entity_id, feature_ts)for point-in-time-correct joins during training. - Online: a KV store with
user:{id}anditem:{id}feature vectors, updated by both batch and streaming jobs.
Step 5: Batch Training and Online Serving Coexisting
The core rule is that training never touches production OLTP stores or the online serving path. Everything flows through Kafka into the lake first.
- Single event log as the source of truth. Both the batch pipeline and the stream processor derive from the same Kafka topic. This prevents the two pipelines from diverging.
- Avoiding train/serve skew. Log the exact features used at serve time (keyed by
request_id) and join them with labels offline. Without this, the model trains on recomputed features that may differ from what it actually saw, which silently degrades performance. - Artifact versioning. Each training run produces a model, item embeddings, and an ANN index, all tagged with a single version identifier. The serving layer loads new versions blue/green: warm up the new version, run it in shadow mode, then atomically flip a pointer. Rollback is just flipping the pointer back.
- Freshness without daily retraining. The stream processor updates recent-interaction lists and short-window counters within seconds. The ranking model consumes these as input features, so it reacts to fresh signals even though the model weights themselves only update daily.
Step 6: Scaling, Consistency, and Fault Tolerance
Scaling knobs:
- API tier is stateless — autoscale on CPU and QPS, deploy across multiple availability zones.
- Add Kafka partitions and consumer instances as write volume grows.
- Hot items (viral content) get local in-process caches and Redis read replicas to avoid thundering-herd on the feature store.
- Hot users (bots, crawlers) are rate-limited at the edge before they reach origin servers.
Fault tolerance:
- If the ranking model server is unavailable, fall back to a simpler scoring heuristic (recency × popularity) using only cached data.
- If the rec cache is cold (after a deployment or cache eviction), the ANN index and candidate sources still return a usable response — just uncached.
- Kafka's durability and consumer-group offsets mean a stream processor restart replays from its last committed offset without losing events.
Consistency trade-offs:
- Interaction writes are eventually consistent by design. The lake and the online store may lag by a few seconds. That is acceptable for recommendations.
- Item takedowns require near-real-time propagation (CDC → cache invalidation) because showing unavailable items is a user-facing error, not just a ranking imperfection.
Common mistakes to avoid:
- Putting event ingestion behind a synchronous, low-latency API. Use async Kafka ingestion and return 202 immediately.
- Partitioning the online interaction store by time. Always partition by
user_id. - Forgetting to log serve-time features. Without them, you cannot correctly attribute outcomes to model decisions.
- Coupling training jobs directly to the production database. They will compete for IOPS at the worst possible time.