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 by Subscription.get once a subscription has been closed (via unsubscribe or broker.close()) and all previously queued messages in its mailbox have been consumed.
  • Subscription(broker: PubSub, topic: str, capacity: int):
    • Exposes self.topic: str and self.dropped: int (initialized to 0, tracking how many messages were evicted from this mailbox due to buffer overflow). Raises ValueError if capacity is not an int of at least 1 (explicitly rejecting bool).
    • get(timeout: Optional[float] = None) -> Any: pops and returns the oldest unread message in FIFO order, waiting up to timeout seconds when the buffer is empty (None waits indefinitely; 0 performs an immediate non-blocking check). Raises TimeoutError if the wait expires while the subscription remains open and empty. Once closed, get() still drains every already-buffered message first, and raises SubscriptionClosed once empty.
    • unsubscribe() -> bool: detaches and closes this subscription by delegating to broker.unsubscribe(self).
  • PubSub(capacity: int = 1000):
    • Configures a default mailbox buffer limit capacity (int >= 1; raises ValueError otherwise, including for bool).
    • subscribe(topic: str, capacity: Optional[int] = None) -> Subscription: creates and registers a new active Subscription on topic using capacity (or the broker's default when None), receiving messages published from that moment onward. Raises ValueError for an invalid capacity or RuntimeError if the broker is closed.
    • unsubscribe(sub: Subscription) -> bool: stops future deliveries to sub, closes sub (waking any threads waiting in sub.get()), and returns True. Returns False if sub is no longer active.
    • publish(topic: str, message: Any) -> int: delivers message to every currently subscribed Subscription on topic and returns how many subscriptions received it. Never blocks waiting on consumers: when a subscription's buffer already holds capacity unread items, discard its oldest unread message and increment sub.dropped by 1 before appending message. Concurrent publishers on the same topic must be observed in one consistent global order across all subscribers of that topic. Raises RuntimeError if the broker is closed.
    • close() -> None: marks the broker closed so new publish and subscribe calls raise RuntimeError, closes every active subscription, and wakes all blocked reader threads so they can drain remaining buffered messages and exit cleanly. Calling close() additional times is a safe no-op.

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 both PubSub and subscribe / Subscription) must be an int >= 1 (bool values raise ValueError).
  • Topics are arbitrary str keys; messages may be any Python object (Any), including None.
  • Concurrent calls to publish, subscribe, unsubscribe, close, and Subscription.get across many threads must be free of race conditions and deadlocks.
  • Multiple threads blocked in get() on the same Subscription must all wake when unsubscribe() or close() runs.

Step-by-step walkthrough

  1. 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 a Subscription mailbox object that the subscriber thread reads at its own speed using get().

    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) delivers msg to every Subscription registered on topic at that instant, and never delivers to a subscription after unsubscribe() 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 (and sub.dropped increments) 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 raising SubscriptionClosed.
  2. Prevent race conditions and deadlocks with a strict lock hierarchy

    Two separate pieces of mutable state are shared across threads:

    1. The broker's topic registry ({topic: set_of_subscriptions}), modified by subscribe / unsubscribe / close and read by publish. Without a lock, a thread unsubscribing while another thread iterates the set in publish crashes with RuntimeError: Set changed size during iteration.
    2. Each subscription's message buffer, written by publishers and drained by subscriber threads.

    We give the broker one threading.Lock (self._lock) and give each Subscription its own threading.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)
    
    1. One global lock order: Whenever code acquires both locks, it always acquires PubSub._lock first and Subscription._cond second. Subscription.get() only ever touches its own Subscription._cond (and sub.unsubscribe() delegates straight to broker.unsubscribe(sub) before acquiring sub._cond).
    2. Zero waiting under PubSub._lock: While holding the broker lock, publish only performs constant-time in-memory appends and never waits for a subscriber.
  3. Build the bounded Subscription mailbox

    Each Subscription wraps a collections.deque (a double-ended queue supporting O(1) appends at the right and O(1) removals from the left) protected by self._cond:

    • Publisher side (_offer): If len(self._buffer) >= self._capacity, pop and discard the oldest message from the left (popleft()) and increment self.dropped. Append the new message on the right and call self._cond.notify() to wake one waiting reader.
    • Close side (_close): Set self._closed = True and call self._cond.notify_all(). We must use notify_all() rather than notify() because multiple consumer threads might be blocked in get() 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 _buffer is non-empty or _closed is true), automatically re-checking _ready() in a loop in case of spurious OS wakeups or another reader taking the item first. When awake, we check if self._buffer: before raising SubscriptionClosed so 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()
    
  4. Manage subscriptions safely in PubSub

    subscribe and unsubscribe mutate self._topics, so both execute inside with self._lock::

    • subscribe rejects new registrations if the broker is already closed, creates a fresh Subscription, and adds it to self._topics[topic].
    • unsubscribe removes sub from self._topics[sub.topic], deletes the topic key when its set becomes empty (so temporary topic names do not accumulate forever), and calls sub._close() before releasing self._lock. Closing inside the same critical section guarantees no publisher can slip a message in after unsubscribe, and any thread waiting in sub.get() wakes up right away. If sub was already removed, unsubscribe safely returns False.
    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 True
    
  5. Fan out messages in publish without blocking

    publish looks up the topic's subscriber set under self._lock and calls sub._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._lock held during the for sub in subs: loop? Because _offer only touches a deque in memory and never blocks, k subscribers take k tiny constant-time steps regardless of how slow the consumer threads are. In exchange, serializing the fan-out under self._lock prevents 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]).

  6. Shut down cleanly while draining buffered messages

    close() flips self._closed = True under self._lock, closes every active Subscription, and clears self._topics. Calling close() 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() drains self._buffer before raising SubscriptionClosed, 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)
    
  7. Trace a slow subscriber alongside a fast subscriber

    Suppose lagging = broker.subscribe("orders", capacity=2) never calls get() while roomy = broker.subscribe("orders", capacity=5) has room for everything, and a publisher sends 10, 20, 30 followed by broker.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 publish finishes immediately without waiting for lagging. Afterwards, roomy.get() reads 10, 20, 30 and then raises SubscriptionClosed, while lagging.get() reads the freshest two messages 20, 30 (with lagging.dropped == 1) and then raises SubscriptionClosed.

  8. 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 where k is the number of active subscribers on topic. Looking up the topic set in the dictionary is O(1) average, and offering the message to each of the k mailboxes performs O(1) deque.append (plus O(1) deque.popleft if 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 (for unsubscribe) marks one mailbox closed in O(1).
  • get(timeout): O(1) work per message (plus any sleep time up to timeout), since checking _ready() and popping the front of a deque both run in constant time.
  • close(): O(S) time across S currently 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 for T active topics and S active subscriptions, because each subscription holds at most capacity message references. Bounding capacity prevents a stalled consumer from exhausting process memory.

Edge cases

  • Publishing to a topic with zero subscribers: publish finds an empty set, returns 0, and discards the message (live pub-sub only delivers to current subscribers, unlike a durable log).
  • Subscribing twice from the same thread: Each subscribe call returns a distinct Subscription mailbox, so both receive every message independently.
  • Repeated unsubscribe() or close(): Unsubscribing an already-removed subscription returns False harmlessly, and calling close() again returns immediately without error.
  • Non-blocking poll (get(timeout=0)): Checks _ready() immediately and returns the oldest buffered message or raises TimeoutError without 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 with ValueError in both PubSub and Subscription (checking isinstance(capacity, bool) explicitly since bool subclasses int in Python).
  • Mutable message objects: All subscribers receive a reference to the same Python object; mutating a shared dict in 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, and close() wakes all of them because _close() calls notify_all().

Common mistakes

  • Iterating self._topics[topic] without holding a lock. If another thread subscribes or unsubscribes mid-loop, Python raises RuntimeError: 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 calls broker.subscribe() on the same thread causes an instant deadlock (threads stuck waiting on locks forever) on a non-reentrant Lock.
  • Using if not self._buffer: instead of a while loop (wait_for) around Condition.wait(). Operating systems can trigger a spurious wakeup (a sleeping thread waking without notify()), or a second reader thread can grab the message first; without re-checking the condition in a loop, popleft() crashes with IndexError.
  • Calling notify() instead of notify_all() on close(). notify() wakes at most one waiting thread, leaving any additional reader threads on that mailbox blocked forever.
  • Acquiring locks in inconsistent orders. If publish acquires broker._lock -> sub._cond while sub.unsubscribe() acquired sub._cond -> broker._lock, concurrent publish and unsubscribe calls would deadlock. Delegating sub.unsubscribe() directly to broker.unsubscribe(sub) preserves a single top-down lock order.
  • Polling with time.sleep() inside get(). Sleeping in a fixed loop wastes CPU cycles and adds artificial latency compared to waking immediately on Condition.notify().

Alternative approaches

  • queue.Queue(maxsize=capacity) per subscriber: Python's built-in Queue is already thread-safe; calling put_nowait and catching queue.Full gives 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's Queue.shutdown()).
  • Copy-on-write subscriber tuples: Storing an immutable tuple of subscribers per topic lets publish read the tuple reference and fan out without holding PubSub._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 _offer wait (outside the broker lock!) until space opens in _buffer applies 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 Subscription mailbox internally and spawn a dedicated worker thread (or submit tasks to a bounded thread pool) that loops on sub.get() and invokes callback(msg) outside all broker locks. That way, a slow callback only fills its own mailbox rather than stalling publishers or other subscribers. Always wrap callback(msg) in try ... 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.Lock and threading.Condition only 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 as customer_id).

Follow-up questions

Similar questions

More Hot Agent Startup interview questions

All 2 Hot Agent Startup questions →