Thread-Safe In-Memory Event Bus

Medium · Software Engineering Fundamentals · Software Engineer · Onsite

Problem Statement

Implement a thread-safe, in-memory publish-subscribe EventDispatcher that allows any number of producer and consumer threads to register callbacks, remove callbacks, and publish events concurrently.

Support the following interface:

  • EventDispatcher(on_error: Optional[ErrorHandler] = None) -> None Creates an empty dispatcher. When on_error is provided, it has signature on_error(event_type, listener, exc) and is invoked whenever a listener raises an Exception during fire.
  • subscribe(event_type: Hashable, listener: Listener) -> bool Registers listener (a single-argument callable listener(payload)) under event_type. Listeners are deduplicated per event_type using equality (==, not is, so bound methods such as instance.handle match across attribute lookups). Returns True if listener was newly added, or False if an equal listener was already subscribed to event_type.
  • unsubscribe(event_type: Hashable, listener: Listener) -> bool Removes listener (matched via ==) from event_type while keeping remaining listeners in their original registration order. Returns True if listener was found and removed, or False otherwise.
  • fire(event_type: Hashable, payload: Any) -> int Captures an atomic snapshot of all listeners subscribed to event_type at the moment fire begins, invokes listener(payload) synchronously on the caller's thread in subscription order, and returns the count of listeners invoked (0 when none are subscribed).

Your implementation must satisfy these concurrency and fault-tolerance guarantees:

  1. Snapshot isolation: Any subscribe or unsubscribe executed after a fire call takes its snapshot — whether from another thread or re-entrantly from inside a running listener — takes effect only on subsequent fire calls and never alters or skips callbacks in the active snapshot.
  2. Deadlock freedom and non-blocking updates: Slow listeners must not block concurrent subscribe, unsubscribe, or fire calls on other threads, and listeners that re-entrantly call subscribe, unsubscribe, or fire on the same dispatcher must never deadlock.
  3. Exception isolation: If a listener raises an Exception, every remaining listener in the snapshot must still execute. When on_error is set, forward (event_type, listener, exc) to on_error for each failure and return the snapshot size normally; when on_error is None, re-raise the first Exception after all listeners in the snapshot have finished.

Examples

Example 1

log = []
bus = EventDispatcher()
alpha = lambda payload: log.append(("alpha", payload["build"]))
beta = lambda payload: log.append(("beta", payload["build"]))
metric = lambda payload: log.append(("metric", payload))

bus.subscribe("deploy", alpha)     # True
bus.subscribe("deploy", beta)      # True
bus.subscribe("deploy", alpha)     # False
bus.subscribe("metric", metric)    # True

count_1 = bus.fire("deploy", {"build": 42})
removed_1 = bus.unsubscribe("deploy", alpha)
removed_2 = bus.unsubscribe("deploy", alpha)
count_2 = bus.fire("deploy", {"build": 43})

Output:

count_1 == 2
removed_1 is True, removed_2 is False
count_2 == 1
log == [("alpha", 42), ("beta", 42), ("beta", 43)]

Walk-through: Subscribing alpha a second time to "deploy" returns False and leaves registration order (alpha, beta) intact. Firing "deploy" with {"build": 42} invokes alpha then beta (returning 2) without touching "metric". After removing alpha, a repeat unsubscribe returns False, and the next "deploy" event invokes only beta (returning 1).

Example 2

seen = []
bus = EventDispatcher()
later = lambda key: seen.append(("later", key))
steady = lambda key: seen.append(("steady", key))

def one_shot(key):
    seen.append(("one_shot", key))
    bus.unsubscribe("cache.evict", one_shot)
    bus.subscribe("cache.evict", later)

bus.subscribe("cache.evict", one_shot)
bus.subscribe("cache.evict", steady)

first_count = bus.fire("cache.evict", "k1")
second_count = bus.fire("cache.evict", "k2")

Output:

first_count == 2
second_count == 2
seen == [("one_shot", "k1"), ("steady", "k1"), ("steady", "k2"), ("later", "k2")]

Walk-through: The first fire snapshots (one_shot, steady). Even though one_shot removes itself and adds later mid-dispatch, steady is not skipped and later waits until the next dispatch. On the second fire, the updated snapshot (steady, later) runs in order.

Example 3

calls = []
caught = []

def broken(vol):
    raise RuntimeError("disk full")

bus = EventDispatcher(
    on_error=lambda ev, fn, exc: caught.append((ev, fn is broken, str(exc)))
)
bus.subscribe("backup", lambda vol: calls.append(("pre", vol)))
bus.subscribe("backup", broken)
bus.subscribe("backup", lambda vol: calls.append(("post", vol)))

total = bus.fire("backup", "vol-7")

Output:

total == 3
calls == [("pre", "vol-7"), ("post", "vol-7")]
caught == [("backup", True, "disk full")]

Walk-through: broken raises RuntimeError, yet the third listener still runs. Because on_error is configured, it receives the failure details and fire returns 3 normally (without on_error, both healthy listeners would still run before RuntimeError is re-raised).

Constraints

  • event_type can be any hashable Python object (str, int, tuple, Enum, etc.).
  • Listeners may be plain functions, lambdas, callable instances, or bound methods (obj.method), and must be compared with ==.
  • subscribe, unsubscribe, and fire may be invoked concurrently by arbitrary threads as well as re-entrantly from inside listener callbacks.
  • Removing the last listener for an event_type should clean up internal state so transient event keys do not accumulate unboundedly.

Step-by-step walkthrough

  1. Restate the contract and concurrency guarantees

    An in-process event dispatcher decouples producers that announce events from subscribers that react to them: - subscribe(event_type, listener) -> bool: registers listener under event_type at most once (comparing with ==), returning True if newly added or False if already present. - unsubscribe(event_type, listener) -> bool: removes listener from event_type, returning True if removed or False otherwise. - fire(event_type, payload) -> int: calls listener(payload) synchronously on the caller's thread for every listener subscribed when fire begins, returning the count invoked.

    Pin down five explicit multithreading invariants before writing code: 1. Atomic point-in-time snapshot: fire captures the subscriber tuple atomically at entry and invokes each callback in that snapshot once, in registration order. 2. Linearizable subscription edits: Concurrent subscribe and unsubscribe operations serialize under a lock — each edit lands cleanly before a fire snapshot or cleanly after it, with zero lost updates. 3. Non-blocking unsubscribe vs. in-flight fire: If Thread A has already captured its snapshot when Thread B calls unsubscribe(listener), Thread A may still call listener one last time; in return, unsubscribe never blocks behind slow callbacks or deadlocks on re-entrant self-removal. 4. Execution ordering: Within one fire, callbacks run in registration order; concurrent fire calls on separate threads proceed in parallel without blocking one another. 5. Exception isolation: A failing listener never skips later listeners in the snapshot; exceptions route to on_error(event_type, listener, exc) if provided, or the first exception is re-raised once the loop completes.

  2. Why the two obvious designs break

    Attempt 1: A plain dictionary of mutable Python lists with no lock. Even under CPython's Global Interpreter Lock (GIL), two bugs surface immediately: - Check-then-act race condition: if listener not in lst: lst.append(listener) spans multiple bytecodes. Two threads can both pass not in before either appends, registering duplicate listeners. - Mutating a list mid-iteration: Even on a single thread (as in Example 2), when one_shot removes itself from a live list during fire, remaining elements shift left and Python's loop index skips steady:

    listeners = []
    seen = []
    
    
    def one_shot(key):
        seen.append(("one_shot", key))
        listeners.remove(one_shot)  # shifts 'steady' from index 1 into index 0!
    
    
    def steady(key):
        seen.append(("steady", key))
    
    
    listeners.extend([one_shot, steady])
    for fn in listeners:
        fn("k1")
    
    print(seen)  # [('one_shot', 'k1')] -> 'steady' was silently skipped!
    

    Attempt 2: Holding one threading.Lock across the entire fire loop. Wrapping fire in with self._lock: prevents list corruption, yet invoking user callbacks while holding an internal lock creates three concurrency hazards: - Re-entrant self-deadlock: When one_shot calls bus.unsubscribe("cache.evict", one_shot) inside fire, its thread tries to acquire self._lock a second time and freezes forever. - Lock-order inversion deadlock (even if you replace Lock with a re-entrant RLock!):

    Thread 1 (inside fire)                  Thread 2 (application code)
    --------------------------------------  --------------------------------------
    1. Acquires bus._lock                   1. Acquires app_lock
    2. Calls listener() -> waits app_lock   2. Calls bus.subscribe() -> waits bus._lock
             \________________________ DEADLOCK ________________________/
    
    • Head-of-line blocking: One slow callback (such as flushing metrics over a slow socket) stalls every fire, subscribe, and unsubscribe across the entire process.

    Hence the core rule of concurrent callback design: never hold an internal lock while calling external code.

  3. Key idea: copy-on-write immutable snapshots

    Store each event key's subscribers in an immutable tuple and apply copy-on-write (readers share immutable tuples freely while writers replace the dictionary entry with a newly allocated tuple):

    Before subscribe("deploy", gamma):
      _listeners["deploy"] ───► (alpha, beta)   ◄── Thread F's snapshot iterates safely!
    
    During subscribe("deploy", gamma) under _lock:
      _listeners["deploy"] ───► (alpha, beta, gamma)  (fresh tuple swapped in atomically)
    
    • fire (read path): Acquires _lock just long enough to read snapshot = self._listeners.get(event_type, ()), releases _lock immediately, and iterates snapshot with zero lock contention.
    • subscribe / unsubscribe (write path): Acquires _lock, constructs a replacement tuple with the added or filtered listeners, updates self._listeners, and releases _lock.

    Read-heavy vs. write-heavy trade-offs: - Most event buses fire events far more often than listeners join or leave. Copy-on-write makes fire's locked section O(1) (zero copying), while subscribe and unsubscribe spend O(k) time copying k listeners for that event key. - If subscriptions churn thousands of times per second while events rarely fire, store an insertion-ordered dict (Dict[Listener, None]) per event key so subscribe/unsubscribe become O(1) under _lock and fire pays O(k) to snapshot tuple(listeners_dict). - Under heavy multi-core contention across many distinct event keys, lock striping (an array of M locks indexed by hash(event_type) % M) eliminates cross-topic contention.

  4. Code subscribe and unsubscribe

    Both write methods execute strictly in memory under self._lock and never run user code. Two Python subtleties matter here: 1. listener in current tests equality (==) rather than identity (is). Every time caller code evaluates a bound method like panel.on_resize, Python allocates a fresh wrapper object (panel.on_resize is panel.on_resize is False), whereas == compares both the underlying function and self instance (panel.on_resize == panel.on_resize is True). 2. Deleting self._listeners[event_type] once the last subscriber leaves prevents short-lived event keys from accumulating empty entries in memory.

        def __init__(self, on_error: Optional[ErrorHandler] = None) -> None:
            # _lock: mutex guarding reads and tuple replacements in _listeners
            self._lock = threading.Lock()
            # _listeners: maps event_type -> immutable tuple of callbacks, e.g. {"click": (fn1, fn2)}
            self._listeners: Dict[Hashable, Tuple[Listener, ...]] = {}
            # _on_error: optional handler called as on_error(event_type, listener, exc)
            self._on_error = on_error
    
        def subscribe(self, event_type: Hashable, listener: Listener) -> bool:
            """Register listener for event_type; False if it was already registered."""
            with self._lock:
                current = self._listeners.get(event_type, ())
                # 'in' checks equality (==, not 'is'), so bound methods like obj.method match.
                if listener in current:
                    return False
                # Copy-on-write: allocate a new tuple instead of mutating in place,
                # leaving any tuple currently being iterated by fire() untouched.
                self._listeners[event_type] = current + (listener,)
                return True
    
        def unsubscribe(self, event_type: Hashable, listener: Listener) -> bool:
            """Remove listener from event_type; True if it was registered."""
            with self._lock:
                current = self._listeners.get(event_type, ())
                if listener not in current:
                    return False
                # Build a replacement tuple preserving the subscription order of remaining listeners.
                remaining = []
                for registered in current:
                    if registered != listener:
                        remaining.append(registered)
                # Delete empty keys so unused event types do not accumulate in memory.
                if remaining:
                    self._listeners[event_type] = tuple(remaining)
                else:
                    del self._listeners[event_type]
                return True
    
  5. Code fire: snapshot under lock, invoke outside lock

    fire separates the O(1) locked snapshot lookup from the unlocked callback loop. Wrapping each listener(payload) call in try ... except Exception matches Example 3's fault-isolation contract: - When self._on_error is configured, each caught exception is passed to self._on_error(event_type, listener, exc) and fire returns len(snapshot). - When self._on_error is None, fire records the first exception in first_error, finishes invoking all remaining listeners in snapshot, and then re-raises first_error.

        def fire(self, event_type: Hashable, payload: Any) -> int:
            """Call every listener registered when fire starts; return how many were called."""
            # Phase 1: Grab an immutable snapshot reference under the lock in O(1) time.
            with self._lock:
                snapshot = self._listeners.get(event_type, ())
    
            # Phase 2: Invoke callbacks OUTSIDE the lock so slow listeners never block
            # other threads and re-entrant calls (subscribe/unsubscribe/fire) never deadlock.
            first_error = None
            for listener in snapshot:
                try:
                    listener(payload)
                except Exception as exc:
                    # Isolate failures so one broken listener never skips later listeners.
                    if self._on_error is not None:
                        self._on_error(event_type, listener, exc)
                    elif first_error is None:
                        first_error = exc
    
            if first_error is not None:
                raise first_error
            return len(snapshot)
    
  6. Trace Example 2 and concurrent updates

    Trace Example 2 (one_shot and steady subscribed to "cache.evict") step by step:

    Step  Call / action                                  _listeners["cache.evict"]    Active snapshot
    ----  ---------------------------------------------  ---------------------------  -------------------
    1     fire("cache.evict", "k1") grabs snapshot       (one_shot, steady)           (one_shot, steady)
    2     one_shot("k1") runs outside _lock:
            - appends ("one_shot", "k1")
            - unsubscribe("cache.evict", one_shot)       (steady,)                    (one_shot, steady)
            - subscribe("cache.evict", later)            (steady, later)              (one_shot, steady)
    3     loop advances to index 1 -> steady("k1") runs  (steady, later)              (one_shot, steady)
    4     first fire returns 2 (later did not run yet)
    5     fire("cache.evict", "k2") grabs new snapshot   (steady, later)              (steady, later)
    6     steady("k2") then later("k2") run -> returns 2
    

    Notice that the exact same mechanism works when a second thread updates "cache.evict" concurrently while fire is partway through snapshot: the writer swaps the dictionary entry immediately without waiting, and the active fire finishes reading its immutable tuple.

  7. Complete solution

    from typing import Any, Callable, Dict, Hashable, Optional, Tuple
    import threading
    
    Listener = Callable[[Any], None]
    ErrorHandler = Callable[[Hashable, Listener, Exception], None]
    
    
    class EventDispatcher:
        """In-memory publish/subscribe, safe to use from many threads at once.
    
        Copy-on-write: each event type maps to an immutable tuple of listeners.
        Writers replace the tuple under the lock; fire grabs the current tuple and
        calls the listeners after releasing the lock.
        """
    
        def __init__(self, on_error: Optional[ErrorHandler] = None) -> None:
            # _lock: mutex guarding reads and tuple replacements in _listeners
            self._lock = threading.Lock()
            # _listeners: maps event_type -> immutable tuple of callbacks, e.g. {"click": (fn1, fn2)}
            self._listeners: Dict[Hashable, Tuple[Listener, ...]] = {}
            # _on_error: optional handler called as on_error(event_type, listener, exc)
            self._on_error = on_error
    
        def subscribe(self, event_type: Hashable, listener: Listener) -> bool:
            """Register listener for event_type; False if it was already registered."""
            with self._lock:
                current = self._listeners.get(event_type, ())
                # 'in' checks equality (==, not 'is'), so bound methods like obj.method match.
                if listener in current:
                    return False
                # Copy-on-write: allocate a new tuple instead of mutating in place,
                # leaving any tuple currently being iterated by fire() untouched.
                self._listeners[event_type] = current + (listener,)
                return True
    
        def unsubscribe(self, event_type: Hashable, listener: Listener) -> bool:
            """Remove listener from event_type; True if it was registered."""
            with self._lock:
                current = self._listeners.get(event_type, ())
                if listener not in current:
                    return False
                # Build a replacement tuple preserving the subscription order of remaining listeners.
                remaining = []
                for registered in current:
                    if registered != listener:
                        remaining.append(registered)
                # Delete empty keys so unused event types do not accumulate in memory.
                if remaining:
                    self._listeners[event_type] = tuple(remaining)
                else:
                    del self._listeners[event_type]
                return True
    
        def fire(self, event_type: Hashable, payload: Any) -> int:
            """Call every listener registered when fire starts; return how many were called."""
            # Phase 1: Grab an immutable snapshot reference under the lock in O(1) time.
            with self._lock:
                snapshot = self._listeners.get(event_type, ())
    
            # Phase 2: Invoke callbacks OUTSIDE the lock so slow listeners never block
            # other threads and re-entrant calls (subscribe/unsubscribe/fire) never deadlock.
            first_error = None
            for listener in snapshot:
                try:
                    listener(payload)
                except Exception as exc:
                    # Isolate failures so one broken listener never skips later listeners.
                    if self._on_error is not None:
                        self._on_error(event_type, listener, exc)
                    elif first_error is None:
                        first_error = exc
    
            if first_error is not None:
                raise first_error
            return len(snapshot)
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine an emergency notification desk holding a printed call list. If the dispatcher bolts the office door shut until every phone call on the sheet finishes, nobody can add or remove their number while a slow call is in progress — and if someone on the phone tries to walk in and cross their own name off the sheet, everyone freezes in a deadlock (threads waiting on one another forever). Instead, we apply copy-on-write (a concurrency pattern where readers iterate immutable snapshots freely while writers swap in a freshly copied tuple): each event_type maps to an immutable Python tuple of callbacks. Inside fire, we acquire a mutex (threading.Lock, a lock permitting only one thread in a critical section at once) just long enough to copy the tuple pointer, release the lock immediately, and invoke every callback outside the lock.

Without synchronization, concurrent subscribe calls hit a race condition (a bug triggered by unlucky thread interleaving) where two threads both pass listener not in list and insert duplicates, while removing a listener from a live list mid-iteration shifts elements left and skips the next callback. Conversely, holding a mutex across callback execution deadlocks on re-entrancy (a listener calling unsubscribe, subscribe, or fire on the same bus) as well as two-thread lock-order inversion (Thread 1 holds the bus lock and waits for an app lock while Thread 2 holds the app lock and calls subscribe). Copy-on-write eliminates both failure modes simultaneously.

Walk through Example 2 (one_shot and steady registered on "cache.evict"): 1. _listeners["cache.evict"] initially stores the immutable tuple (one_shot, steady). 2. fire("cache.evict", "k1") acquires _lock, grabs snapshot = (one_shot, steady) in O(1) time, releases _lock, and invokes one_shot("k1"). 3. Inside one_shot("k1"), calling unsubscribe("cache.evict", one_shot) and subscribe("cache.evict", later) acquires _lock without deadlocking and replaces _listeners["cache.evict"] with (steady, later). 4. fire continues reading its untouched snapshot = (one_shot, steady), invokes steady("k1"), and returns 2; the next fire("cache.evict", "k2") reads (steady, later) and invokes those two in order.

Complexity

Let k be the number of listeners currently subscribed to event_type and S be the total number of active subscriptions across all event keys: - subscribe: O(k) time. Under _lock, we scan the k-element tuple once to check equality (listener in current) and allocate a (k + 1)-element replacement tuple. - unsubscribe: O(k) time. Under _lock, we scan the k-element tuple to confirm presence and build a (k - 1)-element tuple (deleting the key when k == 1). - fire: O(1) locked time, plus O(k) callback calls outside the lock. Reading the tuple reference from _listeners is a single hash lookup under _lock, keeping lock contention near zero regardless of callback duration. - Space: O(S) memory. Storing all current subscriber tuples uses O(S) memory; any superseded tuple is freed as soon as in-flight fire calls finish iterating their O(k) reference.

Edge cases

  • Unregistered or emptied event_type: Firing an unknown key returns 0, and removing the final listener deletes _listeners[event_type] so ephemeral keys never leak memory.
  • Duplicate subscribe vs. multi-topic subscribe: Registering the same callback twice on "deploy" returns False and stores it once, whereas registering it on two distinct keys tracks each independently.
  • Bound instance methods (panel.on_resize): Python creates a fresh bound-method wrapper on every attribute lookup, so is would fail; matching via == (in / !=) deduplicates and removes bound methods accurately.
  • Re-entrant callbacks: Listeners that unsubscribe themselves, register follow-up listeners, or trigger nested fire calls execute outside _lock without deadlocking, and subscription edits apply cleanly starting on the next fire.
  • Exceptions raised inside callbacks: Later listeners in the snapshot still run; on_error receives every failure when configured, and otherwise the first exception is re-raised after all callbacks complete.

Common mistakes

  • Holding self._lock while invoking listeners. Switching from Lock to RLock only avoids single-thread self-deadlock — two-thread lock-order inversion still deadlocks, and slow callbacks still block all threads.
  • Iterating over a shared mutable list without copying. Self-unsubscription or concurrent unsubscribe shifts list indices mid-loop and silently skips the next listener.
  • Relying on Python's GIL instead of an explicit lock. if listener not in lst: lst.append(listener) spans multiple bytecodes, allowing a thread switch between the membership check and the append.
  • Comparing callbacks with is instead of ==. Passing panel.on_resize to unsubscribe constructs a new wrapper object that is equal (==) to the registered one, never identical (is).
  • Allowing one raising callback to abort the for loop. Omitting per-listener try ... except starves every subscriber registered after a failing callback.

Alternative approaches

  • Insertion-ordered dict + copy-on-fire: Store Dict[Listener, None] per event_type so subscribe and unsubscribe run in O(1) average time under _lock, while fire copies tuple(d) in O(k) time under _lock. Best when subscription churn dominates firing (requires hashable callbacks).
  • Lock striping across topic buckets: Partition _listeners across M independent shards (hash(event_type) % M), each guarded by its own Lock, removing cross-topic lock contention on many-core servers.
  • Weak-reference subscriptions (weakref.WeakMethod / weakref.ref): Storing weak references (pointers that allow garbage collection when no strong owner remains) prevents forgotten listeners on short-lived UI widgets from leaking memory.

Follow-up questions

  • How would you guarantee that an unsubscribed callback never executes once unsubscribe returns? Maintain a per-subscription state object under _lock containing an active flag and an in_flight call counter paired with a threading.Condition (a synchronization primitive that lets threads sleep until notified). Around each callback in snapshot, fire briefly locks to check active, increments in_flight (recording the active thread ID), runs the callback unlocked, and then decrements in_flight and notifies waiters. unsubscribe sets active = False and waits until in_flight drops to zero — while explicitly skipping any in-flight call running on its own thread so a callback unsubscribing itself never deadlocks waiting on itself.
  • How would you adapt the data structures if subscription churn vastly exceeds event publishing? Replace each immutable tuple with an insertion-ordered dict (Dict[Listener, None]) sharded across M striped locks. Deduplicating, adding, and deleting hashable callbacks drop from O(k) tuple allocations to O(1) hash-table operations under the shard lock, moving the O(k) tuple(d.keys()) copy onto the much rarer fire calls.
  • What changes if fire dispatches callbacks asynchronously on a worker pool rather than on the caller thread? Capture snapshot under _lock inside fire exactly as before so publish-time snapshot semantics remain intact, then push (event_type, snapshot, payload) onto bounded worker queues. Route each event to worker shard hash(event_type) % num_workers if per-topic event order must be preserved, require an on_error logger/handler because the publisher has already returned, enforce an explicit full-queue backpressure policy (block publisher vs. drop with metrics), and provide a close(drain=True) shutdown method using sentinel tokens so queued events finish cleanly.

Follow-up questions

Similar questions

More Purestorage interview questions

All 4 Purestorage questions →