← Building blocks

Rank instead of sorting by time

Data processing & searchstaff

Chronological feeds bury the posts users care about.

Say it like this

A chronological feed buries what the user cares about, so I fetch a few hundred candidate ids cheaply, score them with features in a ranking service under a strict latency budget, and keep chronological as the fallback when the ranker is slow or down.

Basic solution

Fetch candidates cheaply, score them with a model or heuristics, keep the top N; sit the ranker between the cache and the client.

feature storecandidate generation + scoringlearning-to-rank

Candidates, features, scores, top N

The feed service collects a bounded set of candidate ids, fetches features in two batched calls, scores all candidates in one model call, applies product rules and only then hydrates the survivors. Every stage has a timeout that drops to chronological order.

How it works

  1. Candidate generation: collect a bounded set of post ids from cheap sources, without reading any post bodies: the last 500 ids in the user's precomputed timeline, recent posts from the celebrities they follow, and a few ids from recommendation sources. Typically 300 to 1,000 candidates.
  2. Filtering: remove candidates that must never appear: deleted posts, posts from blocked authors, posts the user already saw, posts matching muted words. Each check is a lookup against a small set held in memory or cache.
  3. Feature fetch: for every remaining candidate, gather the numbers the model needs in one batched call per store: post features (age, like count, media type), author features (follower count, how often this user interacts with them), and user features (interests, time of day). A feature store serves these from precomputed tables, so this is two MGET-style calls rather than hundreds of queries.
  4. Scoring: send all candidates with their features to the model in one request. The model predicts, per candidate, the probability of each kind of engagement (like, reply, dwell), and the final score is a weighted sum of those probabilities.
  5. Re-ranking rules: adjust the ordered list for product rules the model does not know: no three posts from one author in a row, a boost for very fresh posts, a slot for ads every N items. Then keep only the top 20 to 50.
  6. Logging: record which candidates were shown, their scores and the features they were scored with, so the next model can be trained on what users actually did with what they saw. Only now fetch the bodies, for the final list only.

Where it sits

  • Between the timeline cache and the client. Reads are still one cache range query; ranking adds a feature fetch and a model call, so it has its own latency budget and its own fallback to chronological order.

Worked example

Home timeline for the news feed

  • 50M DAU, 10 feed loads per user per day: 500M ranked requests per day, about 6K per second average and 20K per second at peak.
  • Candidates: 500 ids from the user's Redis timeline plus up to 100 from celebrity caches, 600 total per request. After filtering seen and blocked, about 400.
  • Features: 20 post features x 400 = 8,000 values from the post feature table, 400 author rows, 1 user row. Served from a feature store (Redis or a key-value store) in two MGET-style calls, about 15 ms p99.
  • Scoring: a gradient-boosted model or a small neural net; 400 candidates in one batch take about 10 ms on a CPU inference server. 20K peak requests per second x 400 = 8M candidate scores per second across the fleet; at 40K scores per second per core that is 200 cores plus headroom.
  • Latency budget: 150 ms end to end for the feed. Cache range 5 ms, filter 5 ms, features 15 ms, scoring 10 ms, rerank 2 ms, hydrate bodies 20 ms, which leaves 90 ms of slack for tail latency. Each stage has a timeout; if features or scoring exceed 50 ms the request falls back to chronological order of the 400 candidates.
  • Logging: 500M requests x 20 shown items = 10B impression rows per day with scores and features, written to the event log and archived for training; about 2 TB per day compressed.
  • What the interviewer wants to hear: candidates stay cheap and bounded, scoring is batched, there is a fallback, and the logged impressions close the loop for the next model.

Variants and when each wins

Heuristic scoring

  • A hand-written formula such as recency decay multiplied by engagement count multiplied by author affinity. It wins as the first version and as the permanent fallback, because it needs no model infrastructure and is easy to reason about.

Two-stage learned ranking

  • A light model scores thousands of candidates quickly, then a heavy model re-scores only the top 100. It wins at scale because the cheap first stage keeps the expensive second stage inside the latency budget.

Online learning and bandits

  • Scores are updated from live feedback, with a share of slots reserved for exploring new creators or formats. It wins when the catalogue changes fast; it adds a serving-time update path and needs careful limits on how much exploration users see.

Ranking at write time

  • Compute a ranked timeline per user when posts arrive, so reads are a plain list. It wins on read cost, but the order goes stale, inactive users cost work for nothing, and real-time features such as time of day cannot be used.

Recommendation: heuristic ranking first with full impression logging, then a learned model trained on those logs, keeping chronological as the always-available fallback.

Failure modes

Ranker down takes the feed down

  • The feed returns 500s whenever the model service is deploying. It happens because the scoring call is on the critical path with no fallback, so when it fails the whole request fails. Put a timeout on the scoring call, fall back to chronological order of the candidates you already have, and wrap the ranker in a circuit breaker.

Feature skew between training and serving

  • Offline metrics improve with a new model but online engagement drops. It happens because a feature was computed one way in the training pipeline and another way at serving time, for example a different time zone or a different window length, so the model saw different inputs in production. Compute each feature once in a feature store that both training and serving read, and log the served features with every impression.

Feedback loop

  • The same 50 creators dominate every feed. It happens because the model is trained on impressions it chose itself, so it keeps reinforcing its own earlier picks. Add diversity rules in the re-rank step, reserve exploration slots for content the model would not pick, and evaluate on a slice of random, unranked traffic.

Latency creep

  • The p99 climbs from 150 ms to 400 ms over several months. It happens because new features and candidate sources were added one at a time with no budget to stop them. Give each stage a latency budget enforced by a timeout, cap the number of candidates and features, and load test every release against the budget.

Stale or deleted content shown

  • A deleted post stays visible for minutes. It happens because the candidate ids came from a cache that never received the deletion. Filter against a fresh set of deleted ids at hydration, which is the last step and reads the freshest data anyway.

Interviewer follow-ups

Answer out loud before you open each one.

Why fetch ids first and bodies last?

Ids are tiny and the ranker only needs features, not text, so scoring 400 candidates costs a few kilobytes of ids plus feature lookups. Hydrating 400 bodies would be 400 KB and most of it is thrown away; hydrate only the 20 that survive.

How do you evaluate a new ranking model safely?

Offline first against logged impressions with a metric like NDCG or predicted engagement, then an online A/B test on a few percent of users with guardrail metrics such as session length and reports. Impression logging with served features is what makes both possible.

What is the latency budget and what happens when a stage blows it?

Each stage gets a slice of the end-to-end target, for example 15 ms for features and 10 ms for scoring, enforced by timeouts. A stage that times out triggers the fallback for that request, chronological order of the candidates already in hand, so the page always renders.

How do you insert ads or recommendations without breaking the ranking?

Treat them as additional candidate sources with their own scores, then apply slotting rules in the re-rank step: at most one ad per N posts, never two recommendations adjacent. The ranker scores; the re-ranker enforces product rules.

Connections

In study paths
Feeds and fan-out
Built on
Skip list · Heap / priority queue · HyperLogLog · Count-Min sketch
Pairs with
Precompute on write, read cheaply · Cache the hot reads · Batch small operations · Degrade instead of failing · Measure p95 / p99, not the average · Process large data offline
Used in
News Feed (Twitter / X timeline)

The same parts on other clouds

The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.

AWSUsed here asGoogle CloudMicrosoft AzureOpen source and others
Amazon EC2 Auto ScalingFeed serviceCompute Engine managed instance groupsVirtual Machine Scale SetsKubernetes Deployment with a HorizontalPodAutoscaler, Nomad
Amazon ElastiCacheTimeline cache, Feature store, Post cacheMemorystoreAzure Managed RedisRedis, Valkey, Memcached
Amazon SageMakerRanking serviceVertex AIAzure Machine LearningKServe, Ray Serve, NVIDIA Triton
Amazon Kinesis Data StreamsImpression logPub/SubEvent HubsApache Kafka, Redpanda, Apache Pulsar