System design · Candidate retrieval, staged ranking and freshness

How to design a recommendation system

Do not score every item for every request. Retrieve a bounded candidate set, filter it, apply staged ranking and cache a short-lived result. Model training is offline; the playground does not execute or evaluate models.

Updated · 5 min read

Retrieval feeds filtering, staged ranking, re-ranking and a cached response.

Recommendation System architecture diagram

Retrieval feeds filtering, staged ranking, re-ranking and a cached response.

The short version

  • Retrieve a bounded candidate set from several sources, then filter and rank in stages. Never score the whole catalogue per request.
  • Training runs offline and publishes versioned models and features. Serving loads compatible versions and never trains.
  • Clicks alone are a bad objective. Balance relevance with safety, freshness and diversity, and log what users actually saw.
  • Every source and model call has a deadline and a fallback. A shorter safe page beats a late or unsafe one.

Clarifying questions to ask first

  • What is recommended, and to whom? (Assume a home feed with a large catalogue and distinct results per user.)
  • What objective matters? (Assume useful, safe and fresh results rather than maximising one engagement event.)
  • How quickly should events affect results? (Assume minutes for some signals and seconds for safety changes.)
  • What is the response budget? (Assume p99 under 200 ms at the API boundary, shared by retrieval, features and ranking.)
  • Can the system return fewer items? (Assume yes. A shorter eligible response is safer than violating policy or waiting indefinitely.)

Numbers that shape the design

These are assumptions for scale, not traffic claims.

QuantityAssumptionResult
Requests10 million DAU × 20 feed opens≈ 2,315/s average, 11,575/s at 5× peak
Candidates1,000 per request at peak≈ 11.6 million/s
Scoring20 µs per candidate231.5 CPU-seconds/s before batching
Payload20 IDs + 2 KB metadata≈ 23 MB/s at peak

Cut candidates before costly scoring and benchmark real features. Fetch media separately so API bandwidth doesn't grow with image and video bytes.

API

GET /recommendations?surface=home&cursor=opaque-token

200 {
  generatedAt,
  modelVersion,
  items: [{ itemId, reasonCode }],
  nextCursor
}

Don't expose raw scores or private features without review. The opaque cursor is tied to a bounded page snapshot or stable ordering key, so a retry returns a compatible page; document how new items and removals are handled.

Data model

Items carry creator, publish time, availability, content features and policy labels. User features summarise recent and long-term interests with timestamps and consent. Interaction events have stable IDs, item, type and event time, and live in a durable log; serving features are derived separately. Candidates record their source and retrieval version so each source's contribution can be measured. A ranking result references item ID, model version, feature snapshot and policy decision, because a model score is never the only eligibility record.

High-level design

The event pipeline validates and deduplicates impressions and interactions, then updates aggregates. Offline, a pipeline trains or refreshes artifacts and publishes a compatible version. Online, the API fetches user features, queries retrieval sources, merges and dedupes candidates, filters eligibility, ranks in stages, applies diversity and freshness rules and returns a short-lived page.

Meta's public Instagram Explore post describes multistage retrieval and ranking with caching and precomputation. This is a published example, not a claim the proposed design matches its internals: https://engineering.fb.com/2023/08/09/ml-applications/scaling-instagram-explore-recommendations-system/

Candidate retrieval

Use several sources: similar items, recent creator activity, followed accounts, popular items by region or topic. Some are precomputed, some use recent interactions. Each returns a bounded list with source ID and timestamp under its own deadline and quota, so a slow source is cut off and a large one can't crowd out the rest. Merge, dedupe by canonical item ID and drop stale entries.

With 100 million items, scoring everything per request makes work grow with inventory. Approximate nearest-neighbour indexes and precomputed sources narrow the set but can miss relevant items, so measure recall on a held-out, time-aware set and keep a fallback for sparse profiles. Online clicks alone are biased by the current ranking, because unseen items can't be clicked. A single source creates a feedback loop where popular items get more exposure and more engagement; a small controlled exploration share counters it, within policy and user controls.

Ranking, freshness and diversity

Cheap filters and first-stage scoring shrink the set before costly ranking, and later stages get bounded candidate counts and timeouts. Final ordering combines the product objective with safety, freshness and diversity; predicted clicks alone repeat near-duplicates and narrow the feed. New users get a fallback such as declared interests or a broad eligible pool, and new items get measured exploration. Log exposure so evaluation can tell no response from no opportunity.

Version the feature schema and model together. On a mismatch, fail closed to a compatible earlier version or a simple baseline. Roll out in shadow mode, then a canary with guardrails on latency, safety and diversity. A positive click change doesn't count if hides, complaints or repeated content get worse. Rollback must not require rebuilding every user's cached feed.

Cache pages only when keys hold the material inputs (every raw event in the key kills reuse) and invalidation for deletion, account and policy changes is defined. Eligibility and deletion checks may still need fresh reads (caching strategies, eventual consistency).

Common traps

  • Scoring the entire catalogue online instead of retrieving a bounded set.
  • Treating clicks as the only success metric.
  • Training in the request path instead of publishing versioned artifacts offline.
  • Caching pages with no invalidation for safety, deletion or availability, so removed content keeps showing.
  • Letting a slow feature store or hot source eat the budget. Bound deadlines, measure skew and fall back to a compatible snapshot.

Follow-up questions interviewers ask

  • "How do new users get useful results?" Name the fallback pool and how interactions update their features.
  • "How do you know ranking improved?" Careful offline evaluation plus controlled online tests with guardrails.
  • "The model is unavailable." State the timeout and fallback, with safety filters still applied.

Frequently asked questions

What is the difference between retrieval and ranking?

+

Retrieval finds a bounded set from a large inventory. Ranking orders that set using richer features and product objectives.

How does the system serve a new user?

+

Use an explicit fallback such as eligible popular items, declared interests or permitted context, then update features as interactions arrive.

Should ranking results be cached?

+

A short-lived result can be cached when keys and invalidation rules are clear. Eligibility and deletion checks may still need fresh evaluation.

Does the playground train a recommender model?

+

No. It helps reason about a component graph and traffic, but does not train or evaluate ranking models.

Now fix it yourself.

Run the design under real traffic and see what breaks first. No signup.