Concurrent In-Memory Publish-Subscribe Broker
Medium · Software Engineering Fundamentals · Software Engineer · Onsite
Problem Statement
Build an in-memory, multi-threaded message broker in pure Python (threading and standard library collections only) where producer threads broadcast messages to named topics and consumer threads pull from per-subscription mailboxes without slow consumers stalling producers.
Implement the following exception and classes:
SubscriptionClosed(Exception): raised bySubscription.getonce a subscription has been closed (viaunsubscribeorbroker.close()) and all previously queued messages in its mailbox have been consumed.Subscription(broker: PubSub, topic: str, capacity: int):- Exposes
self.topic: strandself.dropped: int(initialized to0, tracking how many messages were evicted from this mailbox due to buffer overflow). RaisesValueErrorifcapacityis not anintof at least1(explicitly rejectingbool). get(timeout: Optional[float] = None) -> Any: pops and returns the oldest unread message in FIFO order, waiting up totimeoutseconds when the buffer is empty (Nonewaits indefinitely;0performs an immediate non-blocking check). RaisesTimeoutErrorif the wait expires while the subscription remains open and empty. Once closed,get()still drains every already-buffered message first, and raisesSubscriptionClosedonce empty.unsubscribe() -> bool: detaches and closes this subscription by delegating tobroker.unsubscribe(self).
- Exposes
PubSub(capacity: int = 1000):- Configures a default mailbox buffer limit
capacity(int >= 1; raisesValueErrorotherwise, including forbool). subscribe(topic: str, capacity: Optional[int] = None) -> Subscription: creates and registers a new activeSubscriptionontopicusingcapacity(or the broker's default whenNone), receiving messages published from that moment onward. RaisesValueErrorfor an invalid capacity orRuntimeErrorif the broker is closed.unsubscribe(sub: Subscription) -> bool: stops future deliveries tosub, closessub(waking any threads waiting insub.get()), and returnsTrue. ReturnsFalseifsubis no longer active.publish(topic: str, message: Any) -> int: deliversmessageto every currently subscribedSubscriptionontopicand returns how many subscriptions received it. Never blocks waiting on consumers: when a subscription's buffer already holdscapacityunread items, discard its oldest unread message and incrementsub.droppedby1before appendingmessage. Concurrent publishers on the same topic must be observed in one consistent global order across all subscribers of that topic. RaisesRuntimeErrorif the broker is closed.close() -> None: marks the broker closed so newpublishandsubscribecalls raiseRuntimeError, closes every active subscription, and wakes all blocked reader threads so they can drain remaining buffered messages and exit cleanly. Callingclose()additional times is a safe no-op.
- Configures a default mailbox buffer limit
Examples
Example 1
broker = PubSub(capacity=4)
alerts_a = broker.subscribe("alerts")
alerts_b = broker.subscribe("alerts")
metrics = broker.subscribe("metrics")
first_count = broker.publish("alerts", "disk-90%")
detached = alerts_b.unsubscribe()
second_count = broker.publish("alerts", "disk-ok")
Output:
first_count == 2
detached is True
second_count == 1
alerts_a.get(timeout=0.1) == "disk-90%"
alerts_a.get(timeout=0.1) == "disk-ok"
alerts_b.get(timeout=0.1) == "disk-90%"
# Next alerts_b.get(timeout=0.1) raises SubscriptionClosed
# metrics.get(timeout=0) raises TimeoutError
Explanation: Both "alerts" subscriptions receive "disk-90%", whereas "metrics" is isolated on a separate topic. After alerts_b unsubscribes, "disk-ok" goes only to alerts_a. alerts_b can still read "disk-90%" that arrived prior to unsubscribing, and then raises SubscriptionClosed.
Example 2
broker = PubSub(capacity=2)
lagging = broker.subscribe("orders")
roomy = broker.subscribe("orders", capacity=5)
for seq in (10, 20, 30):
broker.publish("orders", seq)
broker.close()
Output:
lagging.dropped == 1
[lagging.get(), lagging.get()] == [20, 30]
# Next lagging.get() raises SubscriptionClosed
roomy.dropped == 0
[roomy.get(), roomy.get(), roomy.get()] == [10, 20, 30]
Explanation: lagging has capacity 2, so publishing 30 evicts the oldest unread item (10) and increments lagging.dropped to 1 without blocking the publisher. broker.close() seals the broker while still letting both subscriptions drain their buffered items before raising SubscriptionClosed.
Constraints
capacity(on bothPubSubandsubscribe/Subscription) must be anint >= 1(boolvalues raiseValueError).- Topics are arbitrary
strkeys; messages may be any Python object (Any), includingNone. - Concurrent calls to
publish,subscribe,unsubscribe,close, andSubscription.getacross many threads must be free of race conditions and deadlocks. - Multiple threads blocked in
get()on the sameSubscriptionmust all wake whenunsubscribe()orclose()runs.
Step-by-step walkthrough
Define the pull-based API and delivery guarantees
The prompt asks us to design a thread-safe publish-subscribe broker where slow subscribers cannot block publishers. Before writing any locking code, we choose a pull model: instead of the publisher thread calling subscriber functions directly (where one slow function would freeze the publisher),
subscribe()returns aSubscriptionmailbox object that the subscriber thread reads at its own speed usingget().Publisher threads PubSub broker Subscriber threads ----------------- --------------------- ------------------ publish("alerts", "disk-90%") ---> topic "alerts" |--> Subscription A ["disk-90%"] -> alerts_a.get(timeout=0.1) +--> Subscription B ["disk-90%"] -> alerts_b.get(timeout=0.1)Pinning down four explicit behavioral rules tells us exactly what our locks must protect:
- Membership: A
publish(topic, msg)deliversmsgto everySubscriptionregistered ontopicat that instant, and never delivers to a subscription afterunsubscribe()returns. - Ordering: Messages from a single publisher arrive in first-in, first-out (FIFO) order, and all subscribers on the same topic observe concurrent publishes in one shared order.
- At-most-once bounded delivery: Messages live in memory inside a fixed-capacity buffer per subscription (
capacity >= 1). If a subscriber falls behind and its buffer fills up, the oldest unread message is dropped (andsub.droppedincrements) so publishers never stall and memory never grows without bound. - Graceful shutdown:
close()blocks new publishes and subscriptions immediately, wakes every sleeping reader thread, and lets readers finish draining any messages already buffered before raisingSubscriptionClosed.
- Membership: A
Prevent race conditions and deadlocks with a strict lock hierarchy
Two separate pieces of mutable state are shared across threads:
- The broker's topic registry (
{topic: set_of_subscriptions}), modified bysubscribe/unsubscribe/closeand read bypublish. Without a lock, a thread unsubscribing while another thread iterates the set inpublishcrashes withRuntimeError: Set changed size during iteration. - Each subscription's message buffer, written by publishers and drained by subscriber threads.
We give the broker one
threading.Lock(self._lock) and give eachSubscriptionits ownthreading.Condition(self._cond, which combines a lock with a thread wait/wake queue).A deadlock happens when Thread 1 holds Lock X while waiting for Lock Y, and Thread 2 holds Lock Y while waiting for Lock X. Two rules make a wait cycle impossible:
Allowed lock acquisition order: PubSub._lock ------> Subscription._cond (publish, unsubscribe, close) Subscription._cond only (Subscription.get) Forbidden: Subscription._cond --X--> PubSub._lock (NEVER happens anywhere)- One global lock order: Whenever code acquires both locks, it always acquires
PubSub._lockfirst andSubscription._condsecond.Subscription.get()only ever touches its ownSubscription._cond(andsub.unsubscribe()delegates straight tobroker.unsubscribe(sub)before acquiringsub._cond). - Zero waiting under
PubSub._lock: While holding the broker lock,publishonly performs constant-time in-memory appends and never waits for a subscriber.
- The broker's topic registry (
Build the bounded Subscription mailbox
Each
Subscriptionwraps acollections.deque(a double-ended queue supportingO(1)appends at the right andO(1)removals from the left) protected byself._cond:- Publisher side (
_offer): Iflen(self._buffer) >= self._capacity, pop and discard the oldest message from the left (popleft()) and incrementself.dropped. Append the new message on the right and callself._cond.notify()to wake one waiting reader. - Close side (
_close): Setself._closed = Trueand callself._cond.notify_all(). We must usenotify_all()rather thannotify()because multiple consumer threads might be blocked inget()on the same mailbox, and every one of them needs to wake up. - Reader side (
get):self._cond.wait_for(self._ready, timeout)sleeps until_ready()is true (either_bufferis non-empty or_closedis true), automatically re-checking_ready()in a loop in case of spurious OS wakeups or another reader taking the item first. When awake, we checkif self._buffer:before raisingSubscriptionClosedso pre-existing messages drain cleanly.
from typing import Any, Dict, Optional, Set import threading from collections import deque class SubscriptionClosed(Exception): """Raised by Subscription.get once the subscription is closed and its buffer is empty.""" def _validate_capacity(capacity: int) -> None: # Reject bool explicitly because bool is a subclass of int in Python (True == 1). if isinstance(capacity, bool) or not isinstance(capacity, int) or capacity < 1: raise ValueError("capacity must be an integer of at least 1") class Subscription: """One subscriber's mailbox for one topic. Publishers fill it; the subscriber thread drains it.""" def __init__(self, broker: "PubSub", topic: str, capacity: int) -> None: _validate_capacity(capacity) self.topic = topic self.dropped = 0 # count of oldest messages evicted when buffer was full self._broker = broker self._capacity = capacity # _buffer: bounded FIFO queue of unread messages, e.g. deque([oldest_msg, ..., newest_msg]) self._buffer: deque = deque() self._closed = False # _cond: per-mailbox lock + wait/notify queue guarding _buffer, _closed, and dropped self._cond = threading.Condition() def get(self, timeout: Optional[float] = None) -> Any: with self._cond: became_ready = self._cond.wait_for(self._ready, timeout) if not became_ready: raise TimeoutError(f"no message on {self.topic!r} within {timeout}s") if self._buffer: return self._buffer.popleft() raise SubscriptionClosed(self.topic) def unsubscribe(self) -> bool: return self._broker.unsubscribe(self) def _ready(self) -> bool: return len(self._buffer) > 0 or self._closed def _offer(self, message: Any) -> None: with self._cond: if self._closed: return if len(self._buffer) >= self._capacity: self._buffer.popleft() self.dropped += 1 self._buffer.append(message) self._cond.notify() def _close(self) -> None: with self._cond: self._closed = True self._cond.notify_all()- Publisher side (
Manage subscriptions safely in PubSub
subscribeandunsubscribemutateself._topics, so both execute insidewith self._lock::subscriberejects new registrations if the broker is already closed, creates a freshSubscription, and adds it toself._topics[topic].unsubscriberemovessubfromself._topics[sub.topic], deletes the topic key when its set becomes empty (so temporary topic names do not accumulate forever), and callssub._close()before releasingself._lock. Closing inside the same critical section guarantees no publisher can slip a message in after unsubscribe, and any thread waiting insub.get()wakes up right away. Ifsubwas already removed,unsubscribesafely returnsFalse.
class PubSub: def __init__(self, capacity: int = 1000) -> None: _validate_capacity(capacity) self._capacity = capacity self._topics: Dict[str, Set[Subscription]] = {} self._closed = False self._lock = threading.Lock() def subscribe(self, topic: str, capacity: Optional[int] = None) -> Subscription: mailbox_capacity = self._capacity if capacity is None else capacity _validate_capacity(mailbox_capacity) with self._lock: if self._closed: raise RuntimeError("pub-sub is closed") sub = Subscription(self, topic, mailbox_capacity) self._topics.setdefault(topic, set()).add(sub) return sub def unsubscribe(self, sub: Subscription) -> bool: with self._lock: subs = self._topics.get(sub.topic) if subs is None or sub not in subs: return False subs.remove(sub) if not subs: del self._topics[sub.topic] sub._close() return TrueFan out messages in publish without blocking
publishlooks up the topic's subscriber set underself._lockand callssub._offer(message)on each subscriber:def publish(self, topic: str, message: Any) -> int: with self._lock: if self._closed: raise RuntimeError("pub-sub is closed") subs = self._topics.get(topic, set()) for sub in subs: sub._offer(message) return len(subs)Why keep
self._lockheld during thefor sub in subs:loop? Because_offeronly touches adequein memory and never blocks,ksubscribers takektiny constant-time steps regardless of how slow the consumer threads are. In exchange, serializing the fan-out underself._lockprevents two concurrent publishers on the same topic from interleaving in opposite orders across two subscribers (Subscriber 1 seeing[M1, M2]while Subscriber 2 sees[M2, M1]).Shut down cleanly while draining buffered messages
close()flipsself._closed = Trueunderself._lock, closes every activeSubscription, and clearsself._topics. Callingclose()a second time simply returns early.def close(self) -> None: with self._lock: if self._closed: return self._closed = True for subs in self._topics.values(): for sub in subs: sub._close() self._topics.clear()Because
Subscription.get()drainsself._bufferbefore raisingSubscriptionClosed, a background subscriber worker loop stays clean and loses no pre-close work:def run_consumer(sub: Subscription, process_fn) -> None: while True: try: msg = sub.get() except SubscriptionClosed: return process_fn(msg)Trace a slow subscriber alongside a fast subscriber
Suppose
lagging = broker.subscribe("orders", capacity=2)never callsget()whileroomy = broker.subscribe("orders", capacity=5)has room for everything, and a publisher sends10, 20, 30followed bybroker.close():Action lagging._buffer lagging.dropped roomy._buffer publish return -------------------- ---------------- ---------------- ---------------- -------------- publish("orders",10) [10] 0 [10] 2 publish("orders",20) [10, 20] 0 [10, 20] 2 publish("orders",30) [20, 30] 1 (evicted 10) [10, 20, 30] 2 broker.close() [20, 30] (closed) 1 [10, 20, 30] (cl) -Every
publishfinishes immediately without waiting forlagging. Afterwards,roomy.get()reads10, 20, 30and then raisesSubscriptionClosed, whilelagging.get()reads the freshest two messages20, 30(withlagging.dropped == 1) and then raisesSubscriptionClosed.Complete solution
from typing import Any, Dict, Optional, Set import threading from collections import deque class SubscriptionClosed(Exception): """Raised by Subscription.get once the subscription is closed and its buffer is empty.""" def _validate_capacity(capacity: int) -> None: # Reject bool explicitly because bool is a subclass of int in Python (True == 1). if isinstance(capacity, bool) or not isinstance(capacity, int) or capacity < 1: raise ValueError("capacity must be an integer of at least 1") class Subscription: """One subscriber's mailbox for one topic. Publishers fill it; the subscriber thread drains it.""" def __init__(self, broker: "PubSub", topic: str, capacity: int) -> None: _validate_capacity(capacity) self.topic = topic self.dropped = 0 # count of oldest messages evicted when buffer was full self._broker = broker self._capacity = capacity # _buffer: bounded FIFO queue of unread messages, e.g. deque([oldest_msg, ..., newest_msg]) self._buffer: deque = deque() self._closed = False # _cond: per-mailbox lock + wait/notify queue guarding _buffer, _closed, and dropped self._cond = threading.Condition() def get(self, timeout: Optional[float] = None) -> Any: """Return the oldest buffered message, waiting up to timeout seconds (None waits forever). Raise TimeoutError if nothing arrives in time, and SubscriptionClosed once the subscription is closed and every buffered message has been read. """ with self._cond: # wait_for re-checks _ready() in a loop so spurious wakeups or competing # readers on the same mailbox never cause popleft() on an empty deque. became_ready = self._cond.wait_for(self._ready, timeout) if not became_ready: raise TimeoutError(f"no message on {self.topic!r} within {timeout}s") # Drain any already-buffered messages BEFORE reporting closure so graceful # shutdown never discards messages that arrived prior to close/unsubscribe. if self._buffer: return self._buffer.popleft() raise SubscriptionClosed(self.topic) def unsubscribe(self) -> bool: """Same as broker.unsubscribe(self).""" return self._broker.unsubscribe(self) def _ready(self) -> bool: # A waiting reader should wake up when either data is available or no more will ever arrive. return len(self._buffer) > 0 or self._closed def _offer(self, message: Any) -> None: """Enqueue a message without ever blocking; evict the oldest item if at capacity.""" with self._cond: if self._closed: return # Drop-oldest policy keeps publishers O(1) and non-blocking even if this reader stalls. if len(self._buffer) >= self._capacity: self._buffer.popleft() self.dropped += 1 self._buffer.append(message) # Wake one waiting reader thread (if any) to consume the newly appended message. self._cond.notify() def _close(self) -> None: """Mark the mailbox closed and wake all threads blocked in get().""" with self._cond: self._closed = True # Must use notify_all (not notify) in case multiple threads share this Subscription. self._cond.notify_all() class PubSub: """In-process publish-subscribe broker that many threads can use at once. Lock hierarchy: self._lock (broker lock) is ALWAYS acquired before sub._cond (mailbox lock), and no lock is ever held while waiting for a subscriber, so lock-order cycles (deadlocks) cannot occur. """ def __init__(self, capacity: int = 1000) -> None: _validate_capacity(capacity) self._capacity = capacity # _topics: maps topic name -> set of active Subscription objects, e.g. {"news": {sub1, sub2}} self._topics: Dict[str, Set[Subscription]] = {} self._closed = False # _lock: guards _topics and _closed across subscribe, unsubscribe, publish, and close self._lock = threading.Lock() def subscribe(self, topic: str, capacity: Optional[int] = None) -> Subscription: """Start receiving every message published to topic from now on.""" mailbox_capacity = self._capacity if capacity is None else capacity _validate_capacity(mailbox_capacity) with self._lock: if self._closed: raise RuntimeError("pub-sub is closed") sub = Subscription(self, topic, mailbox_capacity) self._topics.setdefault(topic, set()).add(sub) return sub def unsubscribe(self, sub: Subscription) -> bool: """Stop delivery to sub and close it. Return False if it was not subscribed any more.""" with self._lock: subs = self._topics.get(sub.topic) if subs is None or sub not in subs: return False subs.remove(sub) # Delete empty topic sets so ephemeral topic names do not leak memory over time. if not subs: del self._topics[sub.topic] # Close inside _lock so no concurrent publish can offer a message after close. sub._close() return True def publish(self, topic: str, message: Any) -> int: """Deliver message to every current subscriber of topic; return how many there were.""" with self._lock: if self._closed: raise RuntimeError("pub-sub is closed") # Fan out under _lock: each _offer is O(1) non-blocking memory work, and holding # _lock ensures all subscribers observe concurrent publishes in the exact same order. subs = self._topics.get(topic, set()) for sub in subs: sub._offer(message) return len(subs) def close(self) -> None: """Reject new publishes and subscriptions and close every subscription.""" with self._lock: # Second and subsequent close() calls are safe no-ops. if self._closed: return self._closed = True for subs in self._topics.values(): for sub in subs: sub._close() self._topics.clear()✅ Submit now — all tests should pass.
Intuition & how it works
Think of a thread-safe publish-subscribe broker as an apartment building's mailroom. Instead of the mail carrier walking up to every apartment door, knocking, and waiting until the resident wakes up (which lets one sleeping resident stall deliveries for the whole building), every subscribed resident gets their own fixed-size mailbox (Subscription). When a publisher sends a message to a topic, the broker quickly drops a reference into each subscriber's mailbox; if one resident never checks their mail and their box fills up, the oldest unread message is evicted to make room for the newest one.
A naive implementation that shares plain dictionaries and lists across threads suffers from race conditions (bugs where concurrent threads interleave reads and writes in unpredictable orders, causing crashes like RuntimeError: Set changed size during iteration or lost messages). Conversely, calling subscriber callbacks or blocking on full queues while holding a global lock stalls every publisher whenever a single consumer hangs. Isolating each subscriber with a bounded deque (a double-ended queue with constant-time appends and removals at both ends) and a condition variable (threading.Condition, a lock paired with a sleep/wake queue so idle readers consume zero CPU while waiting) keeps publishers non-blocking and readers responsive.
Walk through Example 2 on PubSub(capacity=2):
1. lagging = broker.subscribe("orders") creates an empty mailbox deque([]) under topic "orders".
2. broker.publish("orders", 10) and broker.publish("orders", 20) fill lagging's buffer to [10, 20].
3. broker.publish("orders", 30) sees the buffer at capacity 2, pops 10 from the left (lagging.dropped becomes 1), and appends 30, leaving [20, 30].
4. broker.close() marks lagging closed and wakes any waiting threads; calling lagging.get() twice still drains 20 and 30, and the third lagging.get() sees an empty closed buffer and raises SubscriptionClosed.
Complexity
publish(topic, message):O(k)time wherekis the number of active subscribers ontopic. Looking up the topic set in the dictionary isO(1)average, and offering the message to each of thekmailboxes performsO(1)deque.append(plusO(1)deque.popleftif full) without ever waiting on a subscriber thread.subscribe/unsubscribe:O(1)average time. Each acquires the broker lock, performs one dictionary lookup and one set insertion or deletion, and (forunsubscribe) marks one mailbox closed inO(1).get(timeout):O(1)work per message (plus any sleep time up totimeout), since checking_ready()and popping the front of adequeboth run in constant time.close():O(S)time acrossScurrently active subscriptions, because it visits each open mailbox once to mark it closed and wake its readers.- Space:
O(T + S * capacity)in the worst case forTactive topics andSactive subscriptions, because each subscription holds at mostcapacitymessage references. Boundingcapacityprevents a stalled consumer from exhausting process memory.
Edge cases
- Publishing to a topic with zero subscribers:
publishfinds an empty set, returns0, and discards the message (live pub-sub only delivers to current subscribers, unlike a durable log). - Subscribing twice from the same thread: Each
subscribecall returns a distinctSubscriptionmailbox, so both receive every message independently. - Repeated
unsubscribe()orclose(): Unsubscribing an already-removed subscription returnsFalseharmlessly, and callingclose()again returns immediately without error. - Non-blocking poll (
get(timeout=0)): Checks_ready()immediately and returns the oldest buffered message or raisesTimeoutErrorwithout sleeping. capacity = 1("latest value only"): Every publish overwrites the single slot with the newest message, which is handy for live status or price tickers.- Invalid capacity (
<= 0,False,True, floats): Rejected upfront withValueErrorin bothPubSubandSubscription(checkingisinstance(capacity, bool)explicitly sinceboolsubclassesintin Python). - Mutable message objects: All subscribers receive a reference to the same Python object; mutating a shared
dictin one subscriber alters what other subscribers read, so callers should publish immutable values or copies. - Multiple reader threads sharing one
Subscription: Messages are load-balanced across the readers, andclose()wakes all of them because_close()callsnotify_all().
Common mistakes
- Iterating
self._topics[topic]without holding a lock. If another thread subscribes or unsubscribes mid-loop, Python raisesRuntimeError: Set changed size during iteration. - Blocking or running user callbacks while holding
PubSub._lock. Waiting on a full queue slows every publisher to the speed of the slowest consumer, and invoking a callback that callsbroker.subscribe()on the same thread causes an instant deadlock (threads stuck waiting on locks forever) on a non-reentrantLock. - Using
if not self._buffer:instead of awhileloop (wait_for) aroundCondition.wait(). Operating systems can trigger a spurious wakeup (a sleeping thread waking withoutnotify()), or a second reader thread can grab the message first; without re-checking the condition in a loop,popleft()crashes withIndexError. - Calling
notify()instead ofnotify_all()onclose().notify()wakes at most one waiting thread, leaving any additional reader threads on that mailbox blocked forever. - Acquiring locks in inconsistent orders. If
publishacquiresbroker._lock -> sub._condwhilesub.unsubscribe()acquiredsub._cond -> broker._lock, concurrentpublishandunsubscribecalls would deadlock. Delegatingsub.unsubscribe()directly tobroker.unsubscribe(sub)preserves a single top-down lock order. - Polling with
time.sleep()insideget(). Sleeping in a fixed loop wastes CPU cycles and adds artificial latency compared to waking immediately onCondition.notify().
Alternative approaches
queue.Queue(maxsize=capacity)per subscriber: Python's built-inQueueis already thread-safe; callingput_nowaitand catchingqueue.Fullgives a drop-newest policy in fewer lines, though drop-oldest and post-close draining require extra coordination (such as sentinel objects or Python 3.13'sQueue.shutdown()).- Copy-on-write subscriber tuples: Storing an immutable tuple of subscribers per topic lets
publishread the tuple reference and fan out without holdingPubSub._lock, boosting multi-core throughput at the cost of losing strict cross-subscriber ordering between concurrent publishes. - Per-topic locks: Using a small lock for the topic dictionary plus one lock per topic eliminates contention between unrelated topics when hundreds of topics are active simultaneously.
- Bounded backpressure instead of dropping: Having
_offerwait (outside the broker lock!) until space opens in_bufferapplies backpressure (slowing producers down to match slow consumers so zero messages are lost), which trades publisher latency isolation for lossless delivery.
Follow-up questions
- How would you evolve this broker from bounded at-most-once delivery to guaranteed at-least-once delivery? Assign every published message a unique ID, keep delivered messages in an "in-flight" map per subscription until the consumer calls
ack(message_id), and redeliver any message whose acknowledgment times out. Because a network or thread stall can cause the same message to arrive twice, subscribers must be idempotent (processing the same message ID a second time produces no duplicate side effects). To survive process crashes as well, persist messages to an append-only log (a disk file where new records are only ever written at the end) before acknowledging the publish, and store each subscriber's committed read offset. - How could you add push-based callback subscriptions without allowing a slow callback to stall publishers? Keep the exact same bounded
Subscriptionmailbox internally and spawn a dedicated worker thread (or submit tasks to a bounded thread pool) that loops onsub.get()and invokescallback(msg)outside all broker locks. That way, a slow callback only fills its own mailbox rather than stalling publishers or other subscribers. Always wrapcallback(msg)intry ... except Exception:inside the worker loop so one uncaught exception in user code does not permanently kill that subscription's delivery thread. - What architectural changes are required when publishers and consumers run across separate processes or hosts?
threading.Lockandthreading.Conditiononly synchronize threads sharing memory inside one process, so the broker must become a networked service speaking over TCP or gRPC. Lightweight brokers like Redis Pub/Sub mirror our fire-and-forget design (low latency, at-most-once delivery to currently connected clients), whereas partitioned log brokers like Apache Kafka persist messages to disk and replicate them across nodes for durability, guaranteeing message order within each partition (an ordered shard of a topic keyed by a routing attribute such ascustomer_id).
Follow-up questions
- How would you evolve this broker from bounded at-most-once delivery to guaranteed at-least-once delivery?
- How could you add push-based callback subscriptions without allowing a slow callback to stall publishers?
- What architectural changes are required when publishers and consumers run across separate processes or hosts?
Similar questions
- Airline Reservation Backend and High-Throughput Live Polling
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging
- Library Hold-Queue and Loan Reminder Notification Manager