Rank Trending Content Across a Multi-Tenant Platform
System DesignModel answerLast updated
Design a low-latency system that returns the top-N pieces of content per workspace, ranked by a weighted engagement score, over rolling time windows.
Rank Trending Content Across a Multi-Tenant Platform
Your platform hosts a collaborative content workspace — think wikis, documents, or blog posts — used by hundreds of thousands of teams. The product team wants to add a "Trending" feed that surfaces the most engaging content within a given workspace over recent time periods.
What you need to design
A backend system that answers the question: which N pieces of content have been most engaging in this workspace over the last 24 hours, 7 days, or 30 days?
Requirements
Functional
- Accept a workspace ID, a time window (24h / 7d / 30d), and a value of N (up to 100) and return the top-N content items for that window.
- "Top" should be based on a configurable engagement metric — views, likes, comments, or a weighted combination.
- Results must respect content visibility rules: a requester should never see items they do not have permission to access.
Non-functional
- Read latency: p99 under 100 ms.
- Write volume: the platform generates hundreds of millions of view events per day, with spiky peaks.
- Freshness: results can be a few minutes stale; real-time accuracy is not required.
- Correctness: handle duplicate events (e.g., a user refreshing a page) and late-arriving events.
What your answer should cover
- How you define and compute the engagement score.
- The event ingestion pipeline and how you handle write volume.
- Storage layer choices and schema design.
- How you precompute or materialize top-N results efficiently.
- The read path, including caching and permission filtering.
- Deduplication, late events, and how you'd recover from data quality issues.
- API design.
Start by stating your assumptions and scale estimates before diving into the design.
Hints
Hint 1
Before designing anything, nail down what 'top' means. Raw view counts are easy to game — think about what a more robust signal looks like, and how storing raw counts separately from a derived score gives you flexibility later.
Hint 2
The workload is extremely write-heavy but reads are repetitive and can tolerate a few minutes of staleness. That asymmetry should drive your architecture: consider precomputing results and caching aggressively rather than querying on every request.
Hint 3
Unique-viewer counts across multiple time buckets can't simply be summed — you'll double-count users who appeared in more than one bucket. Think about what probabilistic data structure solves this efficiently at scale.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Step 1: Clarify scope and estimate scale
A strong answer starts here, not at the whiteboard.
Assumptions worth stating:
- Default score is a weighted combination; raw counts are stored separately so weights can change without reprocessing events.
- Freshness lag of 1–5 minutes is acceptable.
- N tops out at 100; precompute a larger candidate pool (e.g., 500) to account for permission filtering.
- Permissions are enforced at read time, not baked into the ranking.
Back-of-envelope:
| Signal | Estimate |
|---|---|
| Daily active users | 10M |
| View events per day | ~500M (~6k/s avg, ~30k/s peak) |
| Likes and comments | ~1–2% of views |
| Workspaces | ~250k, highly skewed |
| Top-N read QPS | ~2k, p99 < 100 ms |
The workload is write-heavy, reads are cheap and repetitive, and some staleness is fine. That combination points toward streaming aggregation with precomputed, cached results — not querying a database on every request.
Step 2: Defining the engagement score
score = log(1 + unique_viewers) + 3.0 × likes + 5.0 × comments
- Unique viewers over raw views: Resists refresh-spamming. The log dampens runaway viral content.
- Engagement weighted higher: A comment or like takes deliberate effort; a view does not.
- Store raw counts, compute score at query time: When product wants to adjust weights, you rescore from existing aggregates — no event reprocessing needed.
- Optional time decay: A half-life of
window / 2can be layered on top. Worth mentioning, not worth over-engineering.
Step 3: Ingestion and streaming pipeline
Client / Server
└─► Collector (batching, auth)
└─► Kafka (key = workspaceId:postId)
├─► Flink (dedupe, event-time windows → hourly/daily buckets)
│ └─► Aggregate store
└─► S3 / Iceberg (raw event lake for backfills)
Postgres (likes, comments as source of truth)
└─► CDC / Debezium ──► Kafka
Why CDC for likes and comments instead of client events? Likes already have a uniqueness constraint in the OLTP store (user_id, post_id). Reading them via CDC gives you unlikes as negative deltas automatically and avoids reconciling a second event stream against the database.
Flink job responsibilities:
- Key the stream by
(workspaceId, postId). - Use event-time tumbling windows of 1 hour.
- Emit per-bucket:
view_count, a HyperLogLog sketch for unique viewers,likes_delta,comments_delta. - Roll hourly buckets into daily buckets for the 7d/30d windows.
Step 4: Storage and schema
OLTP (Postgres) is the source of truth for content metadata, likes, comments, and permission rules. It is the wrong tool for 30k/s counter increments or multi-week range scans.
Aggregate store: Either a wide-column store (Cassandra / DynamoDB) or a real-time OLAP engine (ClickHouse / Apache Pinot).
| Wide-column | OLAP engine | |
|---|---|---|
| Writes | Fast idempotent upserts | Columnar inserts, slightly more overhead |
| Ad-hoc ranking | Needs a separate materializer | Native GROUP BY ... ORDER BY ... LIMIT N |
| Operations | Simpler | More moving parts |
Pinot/ClickHouse handles both the hot serving path and the long tail of small workspaces in a single system — a reasonable default choice. Cassandra paired with a dedicated materializer is a valid alternative if your team prioritizes operational simplicity.
Hourly bucket table:
post_stats_hourly
PK (workspace_id, bucket_hour)
SK post_id
COLS views BIGINT, uv_hll BLOB, likes INT, comments INT, version INT
Daily buckets follow the same shape.
Precomputed top-N table:
top_posts
PK (workspace_id, window, metric)
COLS items JSON -- top 500 post_ids + counts
computed_at TIMESTAMP
Window math:
- 24h: Merge 24 hourly buckets.
- 7d / 30d: Merge daily buckets plus the partial current day from hourly buckets — at most ~54 reads total.
- Unique viewers across buckets: Merge the HLL sketches. Summing raw counts here would double-count users; HLL union is the correct operation.
Step 5: Materializing top-N efficiently
- Hot workspaces (large or recently active): a background materializer recomputes their lists every 1–5 minutes. It maintains a running window sum incrementally — add the newest bucket, subtract the one that just expired — and keeps a min-heap of size 500 per window.
- Cold / long-tail workspaces: compute on first read via an OLAP query, then cache. Continuously precomputing results for 250k workspaces × 3 windows × multiple metrics wastes resources for workspaces that nobody visits.
Step 6: Read path, caching, and permissions
Request
→ Redis key: top:{wsId}:{window}:{metric} TTL ~2 min
→ miss → Precomputed table or OLAP query
→ Batch permission check (against permissions service, cached per user+space)
→ Filter deleted / archived content
→ Return first N; if too few pass, fetch more candidates and re-filter
A few important details:
- Stale-while-revalidate + single-flight on cache misses — prevents a thundering herd when a popular workspace's cache key expires.
- Cache at the workspace level, filter per user — results are authorization-dependent, so you cannot cache per-user responses at a CDN. The right split is a workspace-level candidate list combined with a per-request permission filter.
- Store K = 500 candidates, not just N = 10, so the permission filter has enough headroom.
Step 7: Deduplication, late events, and backfills
Duplicates:
- Every event carries a client-generated
eventId(UUID). Flink deduplicates on it using keyed state with a TTL of ~24h. - Unique-viewer HLL sketches are naturally replay-safe.
- Use idempotent upserts on buckets (overwrite the full bucket value keyed by
version, not+=) so Flink checkpoint restarts don't corrupt counts.
Late events:
- Flink operates on event time with watermarks and an allowed lateness of ~1 hour. A late event triggers a corrected bucket emission that overwrites the previous value.
- Events arriving beyond the lateness limit land in a side output. A periodic correction job recomputes affected buckets from the raw lake.
- Clamp or reject events with implausible future timestamps.
Backfills / formula changes:
- Weight changes: rescore by reading existing aggregate buckets — no event reprocessing.
- Schema or bug fixes: replay raw events from the S3/Iceberg lake through a modified Flink job, backfill the buckets, and trigger a materializer recompute.
Step 8: API
GET /v1/workspaces/{workspaceId}/posts/trending
?window=24h|7d|30d
&n=10
&metric=score|views|likes|comments
200 OK
{
"asOf": "2024-05-01T10:05:00Z",
"window": "7d",
"items": [
{ "postId": "p1", "title": "...", "score": 41.2,
"views": 1200, "likes": 30, "comments": 4 }
]
}
Common mistakes to avoid
- Raw view counts as the score — trivially gamed and noisy.
- Summing unique-viewer counts across buckets — double-counts users; merge HLL sketches instead.
- Forgetting permissions — this is the most commonly missed correctness requirement.
- Caching per user at a CDN — correct direction (caching), wrong level (user vs. workspace).
- Precomputing everything eagerly — most workspaces are cold; precomputing 250k × N combinations continuously is wasteful.