Low-Latency Personalized Feed Ranking Service Design
System DesignModel answerLast updated
Design an end-to-end personalized feed service for millions of users: data pipelines, feature consistency, retrieval and ranking, cold start, latency budgets, experiments, and failure handling.
You are designing the personalized feed for a large consumer mobile app. Each time a user opens the feed, the backend must return a ranked list of items tailored to that person, and the feed must react quickly to what the user just did.
Requirements
- Service-layer P95 latency under roughly 100 ms, from request arrival to response.
- Millions of daily active users.
- A catalog of tens of thousands of active items, with items being added and retired continuously.
- New interactions (views, clicks, purchases, and similar) should influence what is shown within seconds to minutes.
Walk through your design, covering these areas
- Architecture and data flow. Trace data from event generation, through training, to online serving. Separate the offline, nearline, and online layers.
- Features and feature store. Which user, item, context, and cross features would you use? How would you build a feature store so that training and serving see consistent values?
- Modeling. Propose a simple baseline, then a stronger deep-learning approach. Explain why you would split the system into retrieval (candidate generation) and ranking stages, or another decomposition.
- Cold start. Cover brand-new users and brand-new items, with several strategies for each (content signals, popularity, exploration, and so on).
- Latency versus accuracy. How do you shape the serving path under a hard latency budget (precomputation, caching, approximate search)? Where do caches go, and what TTL or consistency policy would you pick?
- Measurement. Which offline and online metrics matter? How would you run experiments? What would you monitor in production (drift, skew, latency, errors), and how would you react?
- Scale and reliability. What storage, streaming, and queueing choices would you make? How does the system degrade gracefully when the ranking service is slow or down?
State your assumptions explicitly (traffic, catalog size, event volume) and justify choices with rough numbers where possible.
Hints
Hint 1
Start with back-of-envelope sizing: requests per second at peak, events per second, and the memory footprint of item embeddings. These numbers tell you whether you need approximate nearest-neighbor search or whether exact scoring over the catalog is affordable.
Hint 2
Write down a per-stage latency budget (gateway, feature fetch, retrieval, ranking, re-ranking, tail headroom) and make each design decision justify itself against that budget. Fetch independent features in parallel.
Hint 3
Training/serving skew is the classic failure: define each feature once, materialize it into an online and an offline store, use point-in-time joins, and ideally log the exact feature vector served with each request ID and train on that.
Hint 4
For cold start, separate the two problems. New items can be placed using content embeddings, priors from category/creator, and a reserved exploration slot. New users need contextual popularity, onboarding signals, and fast in-session adaptation from the streaming path.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Assumptions and sizing
- 10M DAU, about 20 feed loads per user per day: 200M requests/day, roughly 2.3K QPS average and about 10K QPS at peak.
- About 50K active items; thousands added or retired per day. Each response returns about 20 items.
- About 100 events per user per day: 1B events/day, roughly 12K events/s average and 50K/s peak.
- Objective: a weighted blend of click, dwell time, and conversion, with guardrails on diversity, freshness, and content policy.
- Sizing: a 64-dim float32 embedding is 256 B, so 50K items is about 13 MB and fits in memory on every serving replica. User features at about 2 KB each total roughly 20 GB, which belongs in a distributed key-value store.
2. Architecture
Offline (hours to days). Raw events land in a data lake. Batch jobs (Spark/Beam) compute long-window features such as 30-day category affinity and item CTR priors, build training sets by joining impressions with outcomes, train and validate models, and publish to a model registry. Item embeddings and the retrieval index are rebuilt here.
Nearline (seconds to minutes). Clients emit events to Kafka or Pub/Sub; Flink or Dataflow updates short-window features (last-N clicked items, session category counts, 1-hour item CTR, trending scores) and writes them to the online store. New items get content embeddings at ingestion and are inserted into the index incrementally.
Online (per request). Gateway, then parallel fetch of user and context features, then multi-source retrieval, then candidate feature hydration, then ranking, then re-ranking and rules, then response and impression logging with a request_id and model version.
| Stage | Budget |
|---|---|
| Gateway/network | 10 ms |
| Feature fetch | 10-15 ms |
| Retrieval | 15 ms |
| Ranking | 35 ms |
| Re-rank | 5 ms |
| Tail headroom | ~20 ms |
3. Features and the feature store
- User: long-term category/creator affinities, user embedding, last-50 interaction sequence, activity level, purchase aggregates.
- Item: category, text/image embeddings, age, price, creator stats, CTR and conversion over 1h/1d/7d windows, smoothed with Bayesian priors so low-traffic items are not noisy.
- Context: time of day, device, locale, surface, session depth.
- Cross: user-category affinity against item category, prior engagement with the creator.
Consistency. Define each feature once and materialize it twice: an online store (Redis/Bigtable/Cassandra, keyed by entity, optimized for multi-get) and an offline store (partitioned Parquet/warehouse). Use point-in-time joins so training sees values as of the impression time. The strongest guard against skew is to log the served feature vector per request_id and train on those logs joined with labels. Add feature versioning, per-group TTLs, and explicit defaults for missing values.
4. Modeling
Why two stages. Scoring 50K items with a heavy model at 10K QPS means about 500M evaluations per second, which is unaffordable. Cheap, high-recall retrieval narrows to about 500-1,000 candidates; an expensive, high-precision ranker scores only those.
Baseline. Segment-level popularity plus item-to-item co-occurrence for candidates; logistic regression or GBDT on hand-built features for ranking. It is fast, interpretable, and a meaningful bar to beat.
Advanced retrieval. Union several sources:
- A two-tower model (user tower on features and history, item tower on item and content features), trained with in-batch negatives and logQ correction for popularity bias. At 50K items, exact dot product is about 3M multiply-adds (around 1 ms), so brute force works; use ANN (HNSW/ScaNN) when the catalog grows to millions.
- Real-time item-to-item neighbors of the user's recent clicks, updated by the stream.
- Trending and fresh-item sources.
Advanced ranking. A multi-task network (MMoE or DCN-v2) with heads for P(click), expected dwell, and P(purchase), combined by a tunable weighted score. Attention over the recent sequence captures current intent. A position-bias tower is used in training and dropped at inference to debias logged data.
Re-ranking. Diversity (MMR or category caps), dedup of seen items, policy filters, and an exploration slot.
5. Cold start
New users: popularity by locale/device/time, onboarding interest picks, context-only user-tower inputs with learned defaults for missing history, and fast in-session adaptation: after one or two clicks the streaming features and item-to-item retrieval take over.
New items: content embeddings place them in the embedding space with zero interactions; CTR priors come from category and creator; a dedicated fresh-item source and exploration slot (epsilon-greedy or Thompson sampling) gather early signal, with a cap on impressions per item so exploration cost is bounded.
6. Latency versus accuracy
- Precompute what does not change per request: item embeddings, ANN index, long-term user embeddings.
- Keep the item table in process memory; fetch features with batched multi-gets in parallel.
- Reduce ranker cost with feature pruning, quantization (int8/fp16), batching candidates in one forward pass, and distillation of a large model into a smaller serving model. A cascade (light ranker on 1,000, heavy ranker on top 100) is a good trade.
- Caches: item-feature cache with short TTL (about 1-5 min); user-embedding cache with TTL of minutes, invalidated on strong events like purchases; result cache for anonymous/cold users keyed by segment (TTL 30-60 s). Accept bounded staleness for popularity and long-term features; keep session features uncached or very short-lived.
7. Metrics, experiments, monitoring
- Offline: AUC/log-loss per head, calibration, recall@K for retrieval, NDCG@K, coverage and diversity, and counterfactual estimates (IPS) with caution about logging bias.
- Online: CTR, dwell, conversion, long-term retention, plus guardrails (latency, diversity, complaints, creator fairness).
- Experiments: user-level randomization with sticky assignment, a holdout for long-term effects, A/A checks, and sample-ratio monitoring. Watch for interference effects when creators or inventory are shared across arms.
- Production monitoring: feature distribution drift (PSI/KS), null rates, training/serving skew via logged vectors, prediction-score distribution, calibration drift, P50/P95/P99 latency, error and timeout rates, index freshness. Alert, then roll back the model or feature version, with automated retraining triggers.
8. Reliability and degradation
- Stream and queue layers are replicated and partitioned by user ID; processing is idempotent with exactly-once or deduplicated writes.
- Per-stage timeouts with hedged requests for tail latency.
- Degradation ladder: ranker slow or down, return retrieval order with a light model; features unavailable, use defaults and cached embeddings; retrieval fails, serve segment-level popular items from cache; everything fails, serve a static curated list. Use circuit breakers and load shedding, and canary every model rollout with instant rollback.
Common mistakes
- Ignoring training/serving skew and leakage from non-point-in-time joins.
- Running a heavy model over the whole catalog.
- Evaluating only offline accuracy with no guardrails or long-term metrics.
- Having no fallback path, or no plan for new items.
- Caching with no thought to staleness for fast-changing features.