Building a Non-Blocking In-Process Publish/Subscribe Broker
System DesignModel answerLast 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,Eventand 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core design decisions
Three choices drive the whole design.
- One mailbox per subscription. Each subscription owns a bounded
dequeprotected by its ownCondition. A publisher never invokes subscriber code; it only deposits a message. The subscriber's own thread drains the mailbox at whatever pace it can manage. - Snapshot under the registry lock, deliver outside it. One
Lockguards thetopic -> {sub_id: Subscription}map.publishholds it only long enough to copy the subscriber list for the topic, releases it, then iterates the copy. This avoids "dict changed size during iteration" and keeps the critical section tiny. - Delivery is never blocking. If a mailbox is full, the overflow policy decides:
drop_oldestordrop_newest. Either way the publisher returns immediately, so a wedged consumer cannot stall publishers or peers. The count of dropped messages is tracked per subscription so the loss is visible.
Why it is safe
- Registry state (
_topics, the closed flag) is only touched while holdingPubSub._lock. Reads and writes are consistent. - Mailbox state (
_buf, closed flag, drop counter) is only touched while holding that subscription'sCondition. The consumer waits withwait_for(predicate), so spurious wakeups and lost notifications are handled by re-checking the predicate after every wake. - No deadlock. The process never holds two locks at once: the registry lock is always released before any mailbox lock is acquired (in
publish,unsubscribe, andclose), and mailbox methods never reach back into the registry. With no nested acquisition there is no lock-ordering cycle. User callbacks are never run under a lock.
Linearization point
A publish effectively "happens" at the instant of the snapshot. A subscriber present before the snapshot receives the message; one registered after it does not. A mailbox closed between snapshot and deposit rejects the offer because _offer re-checks the closed flag under the mailbox lock. That matches "all currently subscribed subscribers receive it" precisely, and it is the point you should call out when asked when delivery is decided.
Delivery semantics and backpressure
- At-most-once, in-process. A message can be dropped on overflow (counted in
dropped) and is lost if the process dies. At-least-once would need acks, persistence and redelivery — a real broker's job. - Ordering. Messages from one publisher thread reach each subscriber in FIFO order. Concurrent publishers have no global order: subscriber A may see
m1, m2while B seesm2, m1. For a total order per topic, hold a per-topic lock across snapshot and fan-out — cheap because offers don't block — or route each topic through a single dispatcher thread. - Overflow policy trade-off.
drop_oldestsuits latest-state feeds;drop_newestpreserves history the consumer already has; blocking with a timeout reintroduces coupling to slow consumers, so mention it but don't make it the default. - Shared payloads. The same object goes to every subscriber, so treat messages as immutable.
Shutdown and unsubscribe
close() is idempotent. Afterwards, publish and subscribe raise Closed. Every mailbox is marked closed and notify_all() wakes blocked consumers, which drain whatever remains and then see the closed signal. unsubscribe does the same for one subscription. A blocking get() therefore never hangs forever.
Complexity
| Operation | Time | Notes |
|---|---|---|
subscribe / unsubscribe | O(1) | |
publish | O(k) | k = subscribers on the topic; registry lock held only for the O(k) copy |
get | O(1) | excluding wait time |
close | O(S) | S = total subscriptions |
Space: O(S × maxsize) for buffers plus O(S) for the registry.
Edge cases
- Publishing to a topic with no subscribers returns 0; not an error.
- Unsubscribing twice, or after close, returns
Falsewithout raising. - A consumer blocked in
get()wakes on unsubscribe/close and getsClosedonce drained. get(timeout=...)raisesTimeoutErrorso consumers can poll a stopEvent.- A publish racing close/unsubscribe is either delivered or cleanly rejected, never half-applied.
- Invalid
maxsizeor overflow string raisesValueErrorat subscribe time. - Empty topics are pruned from the registry so the map doesn't leak.
Sketch
import threading
from collections import deque
class Closed(Exception): pass
class Subscription:
def __init__(self, maxsize, overflow="drop_oldest"):
if maxsize < 1: raise ValueError("maxsize >= 1")
if overflow not in ("drop_oldest", "drop_newest"): raise ValueError(overflow)
self._buf, self._max = deque(), maxsize
self._overflow = overflow
self._cond = threading.Condition(threading.Lock())
self._closed, self.dropped = False, 0
def _offer(self, msg):
with self._cond:
if self._closed: return False
if len(self._buf) >= self._max:
self.dropped += 1
if self._overflow == "drop_newest": return False
self._buf.popleft()
self._buf.append(msg); self._cond.notify(); return True
def get(self, timeout=None):
with self._cond:
if not self._cond.wait_for(lambda: self._buf or self._closed, timeout):
raise TimeoutError
if self._buf: return self._buf.popleft()
raise Closed
def _close(self):
with self._cond:
self._closed = True; self._cond.notify_all()
PubSub keeps _lock, _topics, and _closed; publish copies the target set under _lock, then calls _offer on each copy outside it. close() swaps the topic map under _lock and closes each mailbox outside it.