Build a Topic-Based Notification Fan-Out Engine
System DesignModel answerLast updated
Design an object-oriented service that pushes news to topic subscribers with at-most-once delivery, effective unsubscribes and per-user per-topic ordering, scaling to millions of users.
You are asked to design a notification backend in which users follow topics and receive news items for the topics they follow.
The service exposes four operations:
addSubscription(userId, topicId): start following a topic.unsubscribe(userId, topicId): stop following a topic.publishNews(topicId, newsId, payload): announce a new item on a topic.onNewsReceived(userId, newsId): called when a client confirms that it received an item.
The behavior must satisfy these rules:
- Every published item is delivered at most once to each user who is subscribed to its topic.
- Once a user unsubscribes, they must receive nothing further from that topic.
- For any single (user, topic) pair, items arrive in the order they were published.
What to cover in your answer
- The requirements and guarantees you are assuming, plus rough scale numbers.
- Class and interface design.
- In-memory data structures and a persistent data model.
- Concurrency control.
- Failure handling (crashes, offline users, retries).
- How the design scales to millions of users, including topics with very large audiences.
- Time and space complexity of the core operations.
Hints
Hint 1
Model each topic as an append-only log with increasing sequence numbers, and keep a per-(user, topic) cursor recording the last item sent. Think about which guarantees this gives you for free.
Hint 2
At-most-once means you must record that something was sent before you attempt to send it. Decide when a rollback of that record is safe and when it is not.
Hint 3
Separate the cost of publishing from the cost of fan-out: publishing should be a cheap append, with delivery performed asynchronously. Then ask what happens to a topic with a million subscribers.
Hint 4
Use a per-user serialization point (a lock or actor) that re-checks the subscription before every send, so an unsubscribe cannot be overtaken by items already queued.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements and assumptions
Guarantees to pin down
- At-most-once: a user never receives the same
newsIdtwice. Losing an item in a crash is acceptable; a duplicate is not. - Unsubscribe is effective: after
unsubscribereturns, nothing more from that topic is sent, including items published earlier but still waiting in a queue. - Ordering: in-order per (user, topic); no ordering across topics.
- No backlog: a new subscriber receives only items published after subscribing.
- Idempotent publish: repeating
publishNewswith the samenewsIddoes nothing.
Scale (assumed): 10M users, 100K topics, about 20 subscriptions per user (roughly 200M subscription rows), 2K publishes/s, median fan-out of 100 but hot topics above 1M subscribers, around 1M deliveries/s at peak, with about 30% of users online.
2. Core idea: topic log plus cursors
Each topic is an append-only log with a monotonically increasing sequence number. Each subscription stores a cursor, the last sequence number sent to that user.
- Ordering: a user walks the log strictly in sequence order.
- At-most-once: advance the cursor before pushing (write-ahead). A crash between advance and push loses the item but never resends it.
- Unsubscribe: delete the subscription row. The delivery loop re-checks it before each send.
- Cheap publish:
publishNewsis an O(1) append plus a "topic advanced" event. Fan-out runs asynchronously.
3. Class design
News(topicId, seq, newsId, payload): immutable value object.TopicLog: append (assignsseq, deduplicates bynewsId),head(),readFrom(seq).SubscriptionStore: cursor per (user, topic) and the reverse index topic to users.Transport(interface):push(userId, news) -> bool, returning false when definitively not sent (user offline). Implementations: WebSocket, APNs/FCM, test fake.Deliverer: per-user drain loop.NotificationService: facade for the four public methods.
Operations
addSubscription: under the user lock and the topic lock, setcursor = log.head()if absent and add the user to the topic's subscriber set. Taking the topic lock makes the starting point well defined: anything published after the call returns is delivered.unsubscribe: under the user lock, remove the cursor and the reverse-index entry.publishNews: append to the log (a duplicatenewsIdreturns immediately), then notify the fan-out workers.drain(user, topic): under the user lock, read items after the cursor. For each item, re-check the subscription, setcursor = seq, thenpush. Ifpushreports "definitely not sent", roll the cursor back toseq - 1and stop; the gateway callsdrainagain on reconnect.onNewsReceived: record the ack for metrics and read receipts. It never triggers a resend, because that would break at-most-once.
Rolling back is safe only when the transport can prove nothing was sent. Any ambiguous outcome (timeout, crash mid-send) leaves the cursor advanced.
4. Concurrency control
- Per-topic serialization (a lock, or a single partition owner) assigns sequence numbers without gaps or duplicates.
- Per-user serialization (a lock or actor) ensures at most one drain per user at a time. That preserves ordering, prevents double-send races, and makes the "still subscribed?" check linearizable with unsubscribe.
- Lock order: always user, then topic, to avoid deadlock.
- Subscriber sets are iterated over a snapshot (copy-on-write). Correctness does not depend on the snapshot being fresh, because each send re-checks the subscription.
5. Persistence model
| Table | Key | Columns |
|---|---|---|
topic_log | (topic_id, seq) | news_id, payload, published_at |
news_dedupe | (topic_id, news_id) unique | seq |
subscription | (user_id, topic_id) | last_sent_seq, status, created_at |
topic_subscribers | (topic_id, user_id) | reverse index, eventually consistent |
delivery_ack | (user_id, news_id) | acked_at, TTL |
- Partition the log by
topic_id(Kafka partitions or Cassandra with N-day retention). - Shard
subscriptionbyuser_id, so all of a user's cursors live on one shard. - Advance a cursor with a conditional single-row write (
SET last_sent_seq = s WHERE last_sent_seq = s - 1). This makes concurrent workers safe: the loser of the race does not send. - Because the reverse index is eventually consistent, the per-send check must read the authoritative
subscriptionrow.
6. Failure handling
- Crash after cursor advance, before push: item lost, never duplicated. This is the accepted at-most-once trade-off.
- Crash during publish: the dedupe key makes a client retry safe.
- Offline user: nothing is queued per user. The cursor stays put and the user catches up from the log on reconnect, subject to log retention. If the cursor falls behind retention, skip to the oldest retained item.
- Worker failure: fan-out partitions are reassigned. A new worker resumes from persisted cursors, and the conditional write prevents double sends.
- Slow transport: per-user timeouts and a bounded in-flight window, so one bad connection never stalls a worker.
7. Scaling
- Pull-style fan-out: because items are stored once per topic and users hold cursors, storage is O(items + subscriptions) instead of O(items x subscribers).
- Sharding: partition fan-out workers by
user_idhash. Each worker owns the connections and cursors of its users, so the per-user lock is local and cheap. - Hot topics: the publisher emits one "topic advanced" event, broadcast to all shards. Each shard scans only its local subscribers of that topic. Fan-out is then parallel across shards, and no single node handles 1M sends.
- Online-only push: with 30% of users online, push only to connected users and let the rest catch up on reconnect, cutting work by roughly 3x at peak.
- Batching: coalesce several new items for a user into one transport write, retaining order.
8. Complexity
Let S be the subscribers of a topic and k the number of new items for a user.
| Operation | Time | Space |
|---|---|---|
publishNews (append and event) | O(1) | O(payload) per item |
| Fan-out for one item | O(S), parallelized over shards | O(1) extra |
addSubscription / unsubscribe | O(1) expected | O(1) per subscription |
drain for one user and topic | O(k) | O(1) |
onNewsReceived | O(1) | O(acked ids), TTL-bounded |
Total memory is O(subscriptions + retained log).
9. Common mistakes
- Pushing first and updating the cursor afterward, which gives duplicates after a crash.
- Treating the ack as a trigger for retries, which turns the design into at-least-once.
- Copying each item into a per-user queue, which makes hot topics blow up storage and publish latency.
- Checking subscription state only when enqueuing, so queued items still reach a user who has just unsubscribed.
- Rolling the cursor back on ambiguous failures.
- Taking locks in inconsistent order and deadlocking.
10. Validation and rollout
Test with a fake transport that injects drops, delays and crashes. Assert that no (user, newsId) is delivered twice, that nothing arrives after unsubscribe returns, and that sequence numbers per (user, topic) are strictly increasing. Roll out behind a flag with a small cohort, monitoring delivery lag, the dropped-on-crash rate and the duplicate-detection counter, which must stay at zero.