KatInterview

Build a Topic-Based Notification Fan-Out Engine

System DesignModel answer
HardModel answerSystem Designpub-subnotificationsfan-out

Last 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:

  1. Every published item is delivered at most once to each user who is subscribed to its topic.
  2. Once a user unsubscribes, they must receive nothing further from that topic.
  3. 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.