KatInterview

Building a Non-Blocking In-Process Publish/Subscribe Broker

System DesignModel answer
MediumModel answerSystem Designconcurrencythreadingpub-sub

Last updated

Design a thread-safe pub/sub service whose publishers never wait on slow consumers, using per-subscription mailboxes, a snapshot-then-fan-out registry, and clean shutdown.

Design and implement an in-process publish/subscribe service with Python's standard threading module.

Requirements:

  • Several publisher threads may publish concurrently, and several subscriber threads may subscribe/unsubscribe concurrently.
  • A subscriber can attach to a topic and later detach from it.
  • When a message is published to a topic, every subscriber attached to that topic at that moment should receive it.
  • No data races and no deadlocks.
  • Prefer primitives such as Lock, RLock, Condition, Event and thread-safe queues.
  • Explain your delivery guarantees, how shutdown works, and how you prevent a single slow consumer from stalling publishers or other subscribers.

Expect to justify your design out loud: the locking discipline, where the linearization point of a publish sits, what happens to the message when a consumer falls behind, and what changes if you need strict ordering.

Hints

Hint 1

Give every subscription its own small buffer so publishers only enqueue and never execute consumer code.

Hint 2

Hold the registry lock just long enough to copy the subscriber set for a topic, then fan out after releasing it — never nest the registry lock and a mailbox lock.

Hint 3

Decide up front what happens when a mailbox is full: drop the oldest, drop the newest, or block with a timeout — and note which choice keeps publishers non-blocking.

Hint 4

On close or unsubscribe, mark the mailbox closed and notify_all so any blocked consumer wakes, drains what is left, and then stops.