Design a Real-Time Content Feed Delivery System
System DesignModel answerLast updated
Design an in-memory topic subscription platform that handles fast ingestion, interest filtering, sliding-window rate limiting, de-duplication, and sorted feed distribution.
You are tasked with designing the core in-memory engine for a real-time topic-based content aggregation service. The platform ingests items continuously and publishes customized feeds to subscribers based on topic interests, quality filters, and delivery speed caps.
Implement a class ContentStreamManager supporting the following API:
API Requirements
-
add_subscription(subscriber_id: int, min_score: float, max_items_per_sec: int, topics: list[str]) -> bool- Creates or updates a subscriber's delivery policy.
- Returns
Trueif inputs are valid (max_items_per_sec >= 1, non-emptytopics, valid numericmin_score). - Returns
Falseon any invalid argument or constraint violation. - Note: Updating an existing subscription must preserve previously delivered item histories and rate-limiting window state.
-
remove_subscription(subscriber_id: int) -> bool- Removes the subscriber's configuration, window state, and delivery history.
- Returns
Trueif found and deleted, orFalseifsubscriber_iddoes not exist.
-
ingest_item(item_id: int, timestamp: float, score: float, topics: list[str]) -> bool- Ingests a new content item into the engine.
- Returns
Falseifitem_idhas already been ingested or iftopicsis empty. - Returns
Trueupon successful registration.
-
dispatch(current_time: float, max_age: float) -> dict[int, list[int]]- Generates and returns a dictionary mapping every registered
subscriber_idto a list of eligibleitem_ids to deliver atcurrent_time.
- Generates and returns a dictionary mapping every registered
Dispatch Rules & Order Constraints
For a given subscriber, an item is eligible for delivery if and only if:
- Score:
item.score >= subscriber.min_score. - Topic Match: At least one topic in
item.topicsexists insubscriber.topics. - Freshness Window:
current_time - max_age <= item.timestamp <= current_time. - De-duplication: The
item_idhas never been delivered to this subscriber in any past or currentdispatchcall. - Rate Limit: The number of items delivered to the subscriber within the last rolling 1-second window
(current_time - 1.0, current_time](including current deliveries) cannot exceedmax_items_per_sec.
Ordering: Eligible items delivered to a subscriber in a single dispatch call must be sorted by:
- Higher
scorefirst (scoredescending). - If scores tie, older timestamp first (
timestampascending). - If scores and timestamps tie, smaller
item_idfirst (item_idascending).
Deliverables
- In-Memory Architecture: Detail the exact data structures chosen for fast lookup, sorting, duplicate detection, and sliding-window rate tracking.
- Algorithm & Pseudo-code: Detail the implementation of
dispatchand management operations. - Complexity Analysis: Provide time and space complexity for every operation in terms of total items $N$, total subscribers $S$, fresh items $F$, and topics per item/subscriber $T$.
- Distributed System & Scale-Out Strategy: Explain how to scale this architecture to handle millions of subscribers, high-throughput item ingestion, stream partitioning, distributed rate limiting, and fault tolerance.
Hints
Hint 1
Because all subscribers demand the exact same total order (score desc, timestamp asc, item_id asc), you can compute a single global sort of the fresh candidate items during dispatch instead of sorting per subscriber.
Hint 2
Using a sliding window algorithm with a deque per subscriber allows O(1) eviction of timestamps older than current_time - 1.0.
Hint 3
To clean up memory over long-running processes, prune delivered item IDs and cached items that fall outside the maximum allowed window max_age.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements & Core Assumptions
- Timestamps: Timestamps are monotonic non-decreasing floats representing epoch seconds. The sliding rate-limit window spans
(current_time - 1.0, current_time]. - Updates vs. Fresh State: Updating a subscription modifies
min_score,max_items_per_sec, andtopics, but retains thedeliveredhistory set and rate-limit deque. - Unified Global Rank Order: A critical property is that all subscribers follow the exact same priority rules for candidate items: $$\text{Sort key} = (-\text{score}, \text{timestamp}, \text{item_id})$$ Because the global relative order of two items never changes across subscribers, we can perform candidate sorting once per dispatch rather than per subscriber.
2. In-Memory Data Structures
To achieve minimal runtime overhead for high-frequency dispatch invocations:
-
Subscriber Directory (
subscribers):dict[int, Subscriber]mappingsubscriber_idto a state object.Subscriberfields:min_score: floatrate_limit: inttopics: set[str]delivered: set[int](tracks delivereditem_ids for de-duplication)window: deque[float](stores delivery timestamps within the last 1.0s)
-
Item Storage (
items&time_index):dict[int, Item]mappingitem_idto anItemdataclass(item_id, timestamp, score, topics: set[str]).time_index: list[tuple[float, int]]maintaining(timestamp, item_id)sorted by timestamp to allow binary search over freshness boundaries[current_time - max_age, current_time].
3. Implementation
import bisect
from collections import deque
from dataclasses import dataclass, field
from typing import Dict, List, Set, Tuple
@dataclass
class Item:
item_id: int
timestamp: float
score: float
topics: Set[str]
@dataclass
class Subscriber:
min_score: float
rate_limit: int
topics: Set[str]
delivered: Set[int] = field(default_factory=set)
window: deque = field(default_factory=deque)
class ContentStreamManager:
def __init__(self):
self.subscribers: Dict[int, Subscriber] = {}
self.items: Dict[int, Item] = {}
self.time_index: List[Tuple[float, int]] = [] # Sorted by (timestamp, item_id)
def add_subscription(self, subscriber_id: int, min_score: float, max_items_per_sec: int, topics: List[str]) -> bool:
if subscriber_id is None or min_score is None:
return False
if not isinstance(max_items_per_sec, int) or max_items_per_sec < 1:
return False
if not topics:
return False
topic_set = set(topics)
if subscriber_id in self.subscribers:
sub = self.subscribers[subscriber_id]
sub.min_score = min_score
sub.rate_limit = max_items_per_sec
sub.topics = topic_set
else:
self.subscribers[subscriber_id] = Subscriber(
min_score=min_score,
rate_limit=max_items_per_sec,
topics=topic_set
)
return True
def remove_subscription(self, subscriber_id: int) -> bool:
return self.subscribers.pop(subscriber_id, None) is not None
def ingest_item(self, item_id: int, timestamp: float, score: float, topics: List[str]) -> bool:
if item_id in self.items or not topics:
return False
item = Item(item_id=item_id, timestamp=timestamp, score=score, topics=set(topics))
self.items[item_id] = item
# Maintain time index ordering
entry = (timestamp, item_id)
bisect.insort(self.time_index, entry)
return True
def dispatch(self, current_time: float, max_age: float) -> Dict[int, List[int]]:
# 1. Identify fresh items using binary search on time index
min_time = current_time - max_age
left_idx = bisect.bisect_left(self.time_index, (min_time, float('-inf')))
right_idx = bisect.bisect_right(self.time_index, (current_time, float('inf')))
fresh_entries = self.time_index[left_idx:right_idx]
fresh_items = [self.items[nid] for _, nid in fresh_entries]
# 2. Globally sort fresh candidate items ONCE
# Priority: score DESC (-score), timestamp ASC, item_id ASC
fresh_items.sort(key=lambda x: (-x.score, x.timestamp, x.item_id))
results: Dict[int, List[int]] = {}
# 3. Process candidate stream for each subscriber
for sub_id, sub in self.subscribers.items():
# Prune rate-limit window entries older than 1 second
window_cutoff = current_time - 1.0
while sub.window and sub.window[0] <= window_cutoff:
sub.window.popleft()
capacity = sub.rate_limit - len(sub.window)
delivered_this_round = []
if capacity > 0:
for item in fresh_items:
# Early termination: candidate score below subscriber's min_score threshold
if item.score < sub.min_score:
break
# Skip if already delivered or no matching topics
if item.item_id in sub.delivered or sub.topics.isdisjoint(item.topics):
continue
# Deliver item
delivered_this_round.append(item.item_id)
sub.delivered.add(item.item_id)
sub.window.append(current_time)
capacity -= 1
if capacity == 0:
break
results[sub_id] = delivered_this_round
return results
4. Complexity Analysis
Let:
- $N$ = total stored items in memory
- $S$ = total active subscribers
- $F$ = number of fresh items within
[current_time - max_age, current_time] - $T$ = average number of topics per item/subscriber
- $D$ = total delivered items in a single dispatch round
| Operation | Time Complexity | Space Complexity | Notes |
|---|---|---|---|
add_subscription | $\mathcal{O}(T)$ | $\mathcal{O}(T)$ | Set construction for topics. |
remove_subscription | $\mathcal{O}(1)$ | $\mathcal{O}(1)$ | Hash map removal. |
ingest_item | $\mathcal{O}(\log N + N)$ | $\mathcal{O}(T)$ | $\mathcal{O}(\log N)$ locate + $\mathcal{O}(N)$ list shift in Python insort. Can be optimized to $\mathcal{O}(\log N)$ using a Balanced BST / SkipList. |
dispatch | $\mathcal{O}(\log N + F \log F + S \cdot F_{\text{matched}})$ | $\mathcal{O}(F + S \cdot \text{batch_size})$ | Candidate sorting takes $\mathcal{O}(F \log F)$. Inner subscriber loop terminates early via budget and score thresholds ($F_{\text{matched}} \ll F$). |
5. Edge Cases & Garbage Collection
-
Memory Bounds & Garbage Collection:
- Over time,
self.items,self.time_index, and subscriberdeliveredsets grow indefinitely. - Fix: Retain a global
MAX_SYSTEM_AGE. During eachdispatchor via a background thread, purge items fromitemsandtime_indexolder thancurrent_time - MAX_SYSTEM_AGE. Similarly, evictitem_ids from subscriberdeliveredsets if their corresponding item timestamps are older thanMAX_SYSTEM_AGE(since they can never qualify undermax_agefilters again).
- Over time,
-
Out-of-Order Ingestion:
- Ingesting items with out-of-order timestamps is handled correctly by
bisect.insortintotime_index.
- Ingesting items with out-of-order timestamps is handled correctly by
6. Distributed System Architecture & Scaling
To scale to millions of subscribers and hundreds of thousands of ingested items/sec, the system must transition from a monolithic in-memory model to a distributed event-driven microservice architecture.
┌──────────────────────┐
│ Ingestion API / Kafka│
└──────────┬───────────┘
│ Partitioned by Topic
▼
┌────────────────────────────┐
│ Inverted Topic Index Node │
└─────────────┬──────────────┘
│
┌────────────────┴────────────────┐
▼ ▼
┌──────────────────────┐ ┌──────────────────────┐
│ Feed Dispatch Node 1 │ │ Feed Dispatch Node 2 │
│ (Subs 1 - 500k) │ │ (Subs 500k - 1M) │
└──────────┬───────────┘ └──────────┬───────────┘
│ │
▼ ▼
┌────────────────────────────────────────────────────────┐
│ Distributed State Store (Redis Cluster / Cassandra) │
│ - Subscriber Rate Window (Sliding Window Redis Script)│
│ - Subscriber Delivery History (Bloom Filter / TTL Set)│
└────────────────────────────────────────────────────────┘
A. Partitioning Strategy
- Subscriber Partitioning (Scatter-Gather / Sharding): Shard subscriber states across multiple Dispatch Nodes using
hash(subscriber_id) % N. Each dispatch node holds only a subset of active subscribers and processes candidate news items against its assigned partition. - Topic Inverted Indexing: Maintain a distributed inverted index (
topic -> list[item_id]) in a Redis cluster or distributed cache. This prevents scanning all $F$ fresh items per subscriber by quickly fetching candidate items matchingsubscriber.topics.
B. Scalable Rate-Limiting & De-duplication
- De-duplication via Bloom Filters + Redis Sets: Store delivered IDs in a TTL-backed Redis Set per subscriber. To save memory, place a Bloom filter in front of the set to immediately discard ~99% of duplicate checks locally before querying Redis.
- Sliding-Window Rate Limiting: Implement sliding window counters using Redis Sorted Sets (
ZADDtimestamp,ZREMRANGEBYSCOREto evict older than $t - 1.0\text{s}$,ZCARDto check remaining limit).
C. High Throughput & Fault Tolerance
- Batching & Consumer Groups: Ingest incoming items via Kafka topic partitions. Feed dispatch workers consume items in batches, execute vectorized threshold checks, and push output batches to delivery queues (e.g., WebSockets, push notification services).
- Stateless Dispatchers & Persistent Stores: Keep feed dispatch workers stateless by backing subscriber configs and histories in a persistent distributed database (e.g., ScyllaDB/Cassandra). If a dispatch worker crashes, a standby instance picks up the assigned subscriber shard from the database.