Design a Trending Content Feed with Near-Real-Time Ranking
System DesignModel answerLast updated
Architect a system that ranks articles by engagement velocity with 1–2 minute freshness, covering ingestion, streaming aggregation, storage tiers, and cheap high-QPS serving.
You are asked to design a backend that shows readers which articles are trending right now, at very large scale.
Scope to pin down with the interviewer first:
- Read APIs: fetch a trending list for a scope (worldwide, country, language), optionally filtered by category; optional per-user re-ranking on top of a global list; cursor-based pagination that must not duplicate or skip items while a reader pages through.
- "Personalized" vs. "global": whether the base list is shared and lightly re-ranked per user, or fully user-specific.
- Write path: client- and server-generated engagement events (impressions, opens, time-on-page, shares), plus editorial removal of an article that must hide it within seconds.
- SLAs: how quickly an event must influence the ranking (e.g., 1–2 minutes), read latency target (e.g., P99 under 100 ms), availability target, and graceful degradation of ingestion.
State your assumptions numerically: daily active users, events per user per day, read requests per user per day, catalog size (total and new articles per day), peak-to-average ratios, regions and locales.
Deliver:
- An explicit definition of "trending" that distinguishes it from "merely popular," including how recency is weighted and how per-event weights are chosen.
- The ingestion architecture and event schema, with an idempotency story and anti-abuse/dedup rules.
- The streaming and batch compute plan, including how sliding windows and decayed counts are maintained, and how a two-stage top-N is computed per dimension.
- Storage tiers (hot/warm/cold), what lives in each, retention, and partitioning/indexing choices.
- Caching, snapshot publishing, and cache invalidation.
- Consistency model, backfill/reprocessing, fault tolerance, sharding, and rough capacity estimates.
Justify each technology choice against alternatives and call out the trade-offs you are accepting.
Hints
Hint 1
Separate the problem into a heavy write path, a heavy read path, and a tiny piece of data that is actually served — the served lists are small precomputed snapshots, so spend your design effort on aggregation, not on request-time ranking.
Hint 2
Use forward decay: accumulate sum(w_i * e^(lambda * t_i)) instead of decayed scores, so each event is one addition; ranking order is preserved because every item shares the same global decay factor at read time.
Hint 3
A single heavily-promoted article can flood one stream partition; partition by article id for local state, then merge partial top-N heaps in a second stage — any item in the global top-N must be in some partition's local top-N.
Hint 4
Make the served snapshot immutable and versioned, then swap a single pointer key atomically, so readers never see a half-built list.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify and set numbers
APIs: GET /trending?scope=…&category=…&cursor=&limit= for lists; POST /events for batched client events; an internal editorial endpoint to block articles; optional GET /feed/trending for per-user re-ranking.
Assumptions to state aloud: 100M DAU × ~50 events/day = 5B events/day ≈ 58K events/s average, ~250K/s peak. 10 trending reads per user per day = 1B/day ≈ 12K QPS average, ~50K QPS peak. Freshness goal 1–2 minutes; read P99 < 100 ms; reads 99.95% available. Catalog ~10M live articles, ~100K published per day. ~30 categories, ~50 locales, plus region scopes.
The framing that drives everything: ingestion is huge, serving is huge, but the artifact being served is tiny. Each trending list is a few thousand precomputed ranked IDs. So the hard work is in the streaming aggregation; the read path is a cache hit plus hydration and reranking.
2. Define "trending"
Popularity is a total; trending is a rate relative to an article's own baseline. Weight events: view 1, open/click 2, dwell > 30 s 3, share 5. Cap per-user contribution per article.
Decayed score: S(t) = Σ wᵢ · e^(−λ(t − tᵢ)), half-life ~2–6 h, tuned per category.
Forward decay is the implementation trick that makes this cheap. Keep P = Σ wᵢ · e^(λ(tᵢ − t₀)). Each event is a single add — no read-decay-write cycle. At read time, S(t) = P · e^(−λ(t − t₀)). Since that factor is identical for every article at a given moment, rankings are unchanged if you compare raw P values as long as t₀ is fixed. Periodically advance t₀ and rescale to avoid float overflow.
Then compute a velocity ratio: trend = S_short / (S_long + prior) (e.g. 1 h vs 24 h half-lives), blended with absolute volume so an article going 1 → 5 views does not reach the top. The prior is what keeps new or rarely-seen articles from looking artificially hot.
3. Ingestion and schema
Clients → ingestion gateway → Kafka. The gateway authenticates, rate-limits, stamps server_ts, and assigns event_id used for idempotency.
Event { event_id, user_id|device, article_id, type, dwell_ms,
client_ts, server_ts, locale, region, device, session_id }
Partition Kafka by article_id. At ~200 B/event, peak ingest ≈ 50 MB/s (~150 MB/s with RF=3). 128 partitions gives headroom. 7-day retention (~1 TB/day raw, ~21 TB replicated) is what makes replay-based backfill possible.
Article metadata (category, locale, publish time, moderation status) lives in a primary store (Postgres/DynamoDB) and is mirrored to a compacted Kafka topic so stream jobs can broadcast-join it.
4. Stream + batch compute
Flink job:
- Dedupe by
event_idwith keyed state and TTL; at most one view per user per article per 30 min; cap per-user totals; down-weight low-diversity IP/ASN sources and known bots. Track unique engagers with HyperLogLog and weight by unique users, not raw counts — the most effective brigading defense. - Broadcast-join metadata for category/locale/moderation.
- Keyed aggregation per
article_id: forward-decayed short and long accumulators plus per-minute buckets. Event time with watermarks and ~5 min allowed lateness; later events go to a side output for batch correction. - Two-stage top-N. Each parallel task keeps a local heap of K≈1000 per dimension (global, region, locale, category, locale×category). Every 30–60 s, partial heaps merge in a small stage. Correctness: any article in the global top-K must be in the local top-K of whichever partition owns it.
- Publish an immutable, versioned snapshot per dimension (write
trending:{dim}:{snapshot_id}), then atomically fliptrending:{dim}:current.
State is ~10M articles × ~100 B ≈ a few GB; RocksDB-backed state with incremental checkpoints every 30 s handles it.
Batch layer (Spark over Iceberg) runs daily for calibrated per-category priors, late-event correction, and personalization training data.
5. Storage tiers
| Tier | Store | Contents | Retention |
|---|---|---|---|
| Hot | Redis, replicated regionally | top-K snapshots per dimension, blocklist | minutes–hours |
| Warm | Cassandra/ClickHouse | per-article minute/hour buckets, snapshot history | 30 days |
| Cold | S3 + Iceberg (Parquet) | raw and cleaned events | 1+ year |
Hot tier sizing: ~2K lists × 1,000 entries × 50 B ≈ 100 MB total — small enough to replicate everywhere and serve from memory. Warm table keyed (article_id, day) clustered by minute for debugging and trend charts. Cold partitioned by date/hour, Z-ordered by article_id for replay and training scans.
6. Serving, caching, invalidation
Request path: read trending:{dim}:current → fetch that snapshot's IDs and scores → drop blocked/moderation-flagged IDs → hydrate metadata from a local cache → optional per-user rerank on the candidate set → return. Page with a cursor encoded as (snapshot_id, last_score, last_id): pagination is over a frozen snapshot, so no duplicates or skips; a new snapshot appears only on refresh. Snapshot-as-immutable-object plus pointer flip is what guarantees readers never see a partial list. Editorial takedowns go into the blocklist with a short TTL and are applied at hydration, so they take effect within seconds even for a stale snapshot.
7. Consistency, faults, operations
Rankings are eventually consistent by design with a stated freshness SLO (e.g., 99% of events reflected within 2 min); readers tolerate a 30–60 s stale list. If Flink falls behind or Redis is cold, serve the last good snapshot plus a degraded-freshness flag rather than an empty feed. For backfill/reprocessing, run a second copy of the job from a Kafka offset into shadow keys, compare, and flip. Shard aggregation by article id range; scale partitions with throughput. Monitor Kafka lag, watermark lag, snapshot age, cache hit rate, and P99 read latency — snapshot age is the metric that actually predicts stale trending.
Trade-offs to name: forward decay over per-read decay (cheap writes, shared read factor); approximate top-N via two-stage merge (nearly exact, massively cheaper than a global sort); precomputed snapshots over on-the-fly ranking (fast reads, bounded staleness); HLL for unique users (small error, huge savings). Common mistakes: no decay (evergreen content squats on the list), no per-user caps, ranking without a baseline ratio, ordering by raw counts and calling it trending, and paginating a live list instead of a frozen snapshot.