Design a Personalized Feed Recommendation Engine
Machine LearningModel answerLast updated
Design an end-to-end recommendation system for a large e-commerce platform, covering data pipelines, candidate retrieval, ranking, cold start, and evaluation.
Context
You are a senior ML engineer at an e-commerce company. The product team wants to add a "Just For You" section to the homepage. Your job is to design the full recommendation system that powers it.
Scale:
- 10 million products in the catalog, with new items added every day
- 1 million daily active users (DAU), roughly 50 million registered accounts
- Peak traffic of 10,000 requests per second
- End-to-end latency budget: under 200ms at p99
What you need to cover
1. Architecture overview Walk through every major component from raw event collection to serving a ranked list. Explain how data flows through the system and where latency is spent.
2. Data model and features What tables or streams do you need? What features do you compute for users, items, and context? How frequently are they refreshed?
3. Retrieval vs. ranking You cannot score all 10 million items per request. Describe the two-stage funnel: what each stage optimizes, what model you use, and how you balance speed against precision.
4. Cold start How does the system behave for a brand-new user with no history? For a product just added to the catalog?
5. Evaluation Propose metrics for both offline evaluation (model quality during training) and online evaluation (live user behavior). How would you run an A/B test to compare two recommendation algorithms?
Constraints and edge cases to address
- The system must stay within the 200ms latency budget even at peak load
- New products must be surfaceable before they accumulate interaction data
- Out-of-stock and policy-violating items must never appear in results
- The architecture must support running multiple recommendation algorithms simultaneously for experimentation
Hints
Hint 1
Start by estimating event volume and storage needs — those numbers will justify your infrastructure choices and show the interviewer you are reasoning from data, not guessing. For example: 1M DAU × 100 events ≈ 100M events/day, and 10M items × 128-dim float32 embeddings ≈ 5 GB, which fits in memory on an ANN server.
Hint 2
The 200ms budget makes a single-stage approach over the full catalog impossible. Think of the problem as a funnel: a fast, high-recall retrieval stage brings a large candidate set down to ~1,000 items, then a slower, high-precision ranking model scores only those. Sketch out a time budget for each stage (feature fetch, retrieval, ranking, re-rank) that adds up to under 200ms.
Hint 3
Cold start for new items is solved differently from cold start for new users. For items, content-based signals — text embeddings of the product title and image embeddings — give you a useful vector before any clicks exist. For users, lean on session signals and item-to-item retrieval: even 2–3 clicks in a session are enough to start personalizing without a learned user embedding.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify scope and pin down the numbers
Before drawing any architecture, establish the scale — it drives every infrastructure decision.
- Events: 1M DAU × ~100 actions (views, clicks, add-to-cart, purchases) ≈ 100M events/day, or roughly 1–2k events/s on average and ~10k/s at peak.
- Traffic: 10k RPS is a peak target, not an average. Design for it with horizontal auto-scaling.
- Embeddings: 10M items × 128 dims × 4 bytes (float32) ≈ 5 GB — fits in memory on a dedicated ANN server. 50M user embeddings ≈ 25 GB, which warrants a key-value store rather than in-process memory.
- Latency budget breakdown (p99 ≤ 200ms): network + feature fetch ~10ms, retrieval ~25ms, ranking ~60ms, re-ranking ~5ms, serialization ~10ms. Everything else is headroom.
Also ask: what is the primary business objective — clicks, purchases, or GMV? Are there hard constraints such as inventory checks, regional restrictions, or sponsored placements? Answers shape the ranking objective and re-ranking rules.
2. API contract
GET /v1/feed?user_id=U&surface=home&limit=20
Response:
{
"request_id": "...",
"experiment_id": "...",
"items": [
{ "product_id": "...", "score": 0.94, "reason": "based on recent views" }
]
}
Logging request_id and experiment_id on every impression is non-negotiable. Without them, you cannot join clicks back to the model variant that generated the ranking, which means A/B tests are unreliable.
3. Architecture
Online path (per request)
- API gateway → Recommendation service. An experiment-assignment layer hashes
user_idinto buckets and returns the algorithm config: retrieval sources, ranking model version, re-rank policy. - Feature fetch from an online feature store (Redis or Feast) — ~10ms. Returns the user embedding, recent interaction IDs, and aggregate counters.
- Candidate generation (~25ms) runs several sources in parallel and merges ~500–1,000 items:
- Two-tower approximate nearest-neighbor (ANN) retrieval via FAISS or ScaNN (HNSW or IVF-PQ index).
- Item-to-item co-occurrence seeded from the user's last N interactions.
- Content-based retrieval using text and image embeddings — the primary source for cold-start items.
- Trending and popular items by category and region.
- Filtering: remove out-of-stock, previously purchased, and policy-violating items.
- Ranking (~60ms): a GBDT (LightGBM) or deep cross network scores the filtered candidates with rich user×item cross features. Predict multiple objectives (p(click), p(purchase)) and combine them:
score = p(click) × p(purchase|click) × price^α. Handle position bias by including position as a feature at training time and setting it to a neutral constant at serving time. - Re-ranking (~5ms): apply diversity (MMR), business rules, and optional exploration slots (ε-greedy or Thompson sampling for new items).
- Fallback: if retrieval or ranking times out, serve a precomputed daily batch list for the user, or a popularity list for their segment.
Offline and nearline path
- Kafka ingests all client and server events.
- Flink or Spark Streaming updates the online feature store within seconds: recent-click lists, session category affinity, and real-time CTR.
- Data lake (S3 + Parquet/Iceberg) stores full event history. A daily Spark job builds training data by joining impressions with labels using point-in-time-correct feature snapshots to prevent leakage.
- Training pipeline (Airflow or Kubeflow): retrain two-tower and ranking models daily → rebuild the ANN index → push to a model registry → deploy via canary.
4. Features
User: learned embedding, category/brand affinity vectors, price-band preference, recency-weighted interaction history (last 50 item IDs), current-session signals.
Item: ID embedding, text embedding of title and description, image embedding (CLIP-style), category, brand, price, days since listing, and CTR/conversion rates over 1h, 1d, and 7d windows.
Cross features: user–category affinity × item category, cosine similarity between user and item embeddings, prior exposure to the brand.
Context: time of day, device type, region.
Batch features are refreshed daily; streaming features are updated within seconds.
One common mistake is forgetting to log impressions and treating only clicks as training data. Without impression logs there are no true negatives, and position bias goes uncorrected.
5. Retrieval vs. ranking trade-off
| Stage | Input | Output | Model | Goal |
|---|---|---|---|---|
| Retrieval | 10M items | ~1,000 | Two-tower + ANN, heuristics | Maximize recall |
| Ranking | ~1,000 | ~100 | GBDT or deep cross network | Maximize precision |
| Re-ranking | ~100 | 20 | Rules + MMR | Diversity and business logic |
The two-tower model encodes users and items independently, so item vectors can be precomputed and indexed offline. Training uses (user, interacted item) positive pairs with in-batch negatives and a log-Q correction for popularity bias. Running multiple retrieval sources (ANN, co-occurrence, content-based, trending) hedges against the blind spots of any single source.
6. Cold start
New products. Use content features — text and image embeddings — from day one, before any interaction data exists. The item tower takes metadata as input alongside the ID embedding, so a new product gets a meaningful vector immediately. Reserve 1–2 exploration slots per page and use Thompson sampling on CTR to gather interactions quickly. Add new items to the ANN index via an hourly incremental merge.
New users. Start with popular and trending items by region and device. After 2–3 in-session clicks, item-to-item retrieval seeded from session history already personalizes the results meaningfully. The user tower can consume recent item IDs directly instead of requiring a trained user-ID embedding, which means it generalizes to users with no history.
7. Evaluation
Offline:
- Retrieval: Recall@K (how often the item a user interacted with appears in the top-K candidates).
- Ranking: Normalized Discounted Cumulative Gain (NDCG@20), Mean Average Precision (MAP), and calibration of predicted click/purchase probabilities.
Online:
- Click-through rate (CTR), add-to-cart rate, and purchase rate on the recommendation surface.
- Revenue per user session and average order value.
- Diversity metrics: intra-list diversity and catalog coverage to avoid filter bubbles.
A/B testing setup: randomly assign users to control and treatment at the user level (not session level, to avoid carryover). Log experiment_id on every impression. Measure the primary metric (purchases or GMV) and guardrail metrics (latency, error rate). Run for at least one full week to capture day-of-week effects, and use a sequential test or pre-registered stopping rule to avoid peeking inflation.
A common mistake is optimizing solely for CTR. Clicks are a dense signal but a noisy proxy — users sometimes click out of curiosity, not intent. Using a combined score that includes downstream purchase probability aligns the model more closely with business value.