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) -> NoneCreates an empty dispatcher. Whenon_erroris provided, it has signatureon_error(event_type, listener, exc)and is invoked whenever a listener raises anExceptionduringfire.subscribe(event_type: Hashable, listener: Listener) -> boolRegisterslistener(a single-argument callablelistener(payload)) underevent_type. Listeners are deduplicated perevent_typeusing equality (==, notis, so bound methods such asinstance.handlematch across attribute lookups). ReturnsTrueiflistenerwas newly added, orFalseif an equal listener was already subscribed toevent_type.unsubscribe(event_type: Hashable, listener: Listener) -> boolRemoveslistener(matched via==) fromevent_typewhile keeping remaining listeners in their original registration order. ReturnsTrueiflistenerwas found and removed, orFalseotherwise.fire(event_type: Hashable, payload: Any) -> intCaptures an atomic snapshot of all listeners subscribed toevent_typeat the momentfirebegins, invokeslistener(payload)synchronously on the caller's thread in subscription order, and returns the count of listeners invoked (0when none are subscribed).
Your implementation must satisfy these concurrency and fault-tolerance guarantees:
- Snapshot isolation: Any
subscribeorunsubscribeexecuted after afirecall takes its snapshot — whether from another thread or re-entrantly from inside a running listener — takes effect only on subsequentfirecalls and never alters or skips callbacks in the active snapshot. - Deadlock freedom and non-blocking updates: Slow listeners must not block concurrent
subscribe,unsubscribe, orfirecalls on other threads, and listeners that re-entrantly callsubscribe,unsubscribe, orfireon the same dispatcher must never deadlock. - Exception isolation: If a listener raises an
Exception, every remaining listener in the snapshot must still execute. Whenon_erroris set, forward(event_type, listener, exc)toon_errorfor each failure and return the snapshot size normally; whenon_errorisNone, re-raise the firstExceptionafter 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_typecan 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, andfiremay be invoked concurrently by arbitrary threads as well as re-entrantly from inside listener callbacks.- Removing the last listener for an
event_typeshould clean up internal state so transient event keys do not accumulate unboundedly.
Step-by-step walkthrough
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: registerslistenerunderevent_typeat most once (comparing with==), returningTrueif newly added orFalseif already present. -unsubscribe(event_type, listener) -> bool: removeslistenerfromevent_type, returningTrueif removed orFalseotherwise. -fire(event_type, payload) -> int: callslistener(payload)synchronously on the caller's thread for every listener subscribed whenfirebegins, returning the count invoked.Pin down five explicit multithreading invariants before writing code: 1. Atomic point-in-time snapshot:
firecaptures the subscriber tuple atomically at entry and invokes each callback in that snapshot once, in registration order. 2. Linearizable subscription edits: Concurrentsubscribeandunsubscribeoperations serialize under a lock — each edit lands cleanly before afiresnapshot or cleanly after it, with zero lost updates. 3. Non-blockingunsubscribevs. in-flightfire: If Thread A has already captured its snapshot when Thread B callsunsubscribe(listener), Thread A may still calllistenerone last time; in return,unsubscribenever blocks behind slow callbacks or deadlocks on re-entrant self-removal. 4. Execution ordering: Within onefire, callbacks run in registration order; concurrentfirecalls 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 toon_error(event_type, listener, exc)if provided, or the first exception is re-raised once the loop completes.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 passnot inbefore either appends, registering duplicate listeners. - Mutating a list mid-iteration: Even on a single thread (as in Example 2), whenone_shotremoves itself from a livelistduringfire, remaining elements shift left and Python's loop index skipssteady: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.Lockacross the entirefireloop. Wrappingfireinwith self._lock:prevents list corruption, yet invoking user callbacks while holding an internal lock creates three concurrency hazards: - Re-entrant self-deadlock: Whenone_shotcallsbus.unsubscribe("cache.evict", one_shot)insidefire, its thread tries to acquireself._locka second time and freezes forever. - Lock-order inversion deadlock (even if you replaceLockwith a re-entrantRLock!):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, andunsubscribeacross the entire process.
Hence the core rule of concurrent callback design: never hold an internal lock while calling external code.
- Head-of-line blocking: One slow callback (such as flushing metrics over a slow socket) stalls every
Key idea: copy-on-write immutable snapshots
Store each event key's subscribers in an immutable
tupleand 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_lockjust long enough to readsnapshot = self._listeners.get(event_type, ()), releases_lockimmediately, and iteratessnapshotwith zero lock contention.subscribe/unsubscribe(write path): Acquires_lock, constructs a replacement tuple with the added or filtered listeners, updatesself._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 sectionO(1)(zero copying), whilesubscribeandunsubscribespendO(k)time copyingklisteners for that event key. - If subscriptions churn thousands of times per second while events rarely fire, store an insertion-ordereddict(Dict[Listener, None]) per event key sosubscribe/unsubscribebecomeO(1)under_lockandfirepaysO(k)to snapshottuple(listeners_dict). - Under heavy multi-core contention across many distinct event keys, lock striping (an array ofMlocks indexed byhash(event_type) % M) eliminates cross-topic contention.Code subscribe and unsubscribe
Both write methods execute strictly in memory under
self._lockand never run user code. Two Python subtleties matter here: 1.listener in currenttests equality (==) rather than identity (is). Every time caller code evaluates a bound method likepanel.on_resize, Python allocates a fresh wrapper object (panel.on_resize is panel.on_resizeisFalse), whereas==compares both the underlying function andselfinstance (panel.on_resize == panel.on_resizeisTrue). 2. Deletingself._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 TrueCode fire: snapshot under lock, invoke outside lock
fireseparates theO(1)locked snapshot lookup from the unlocked callback loop. Wrapping eachlistener(payload)call intry ... except Exceptionmatches Example 3's fault-isolation contract: - Whenself._on_erroris configured, each caught exception is passed toself._on_error(event_type, listener, exc)andfirereturnslen(snapshot). - Whenself._on_errorisNone,firerecords the first exception infirst_error, finishes invoking all remaining listeners insnapshot, and then re-raisesfirst_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)Trace Example 2 and concurrent updates
Trace Example 2 (
one_shotandsteadysubscribed 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 2Notice that the exact same mechanism works when a second thread updates
"cache.evict"concurrently whilefireis partway throughsnapshot: the writer swaps the dictionary entry immediately without waiting, and the activefirefinishes reading its immutable tuple.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 returns0, and removing the final listener deletes_listeners[event_type]so ephemeral keys never leak memory. - Duplicate
subscribevs. multi-topicsubscribe: Registering the same callback twice on"deploy"returnsFalseand 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, soiswould fail; matching via==(in/!=) deduplicates and removes bound methods accurately. - Re-entrant callbacks: Listeners that unsubscribe themselves, register follow-up listeners, or trigger nested
firecalls execute outside_lockwithout deadlocking, and subscription edits apply cleanly starting on the nextfire. - Exceptions raised inside callbacks: Later listeners in the snapshot still run;
on_errorreceives every failure when configured, and otherwise the first exception is re-raised after all callbacks complete.
Common mistakes
- Holding
self._lockwhile invoking listeners. Switching fromLocktoRLockonly avoids single-thread self-deadlock — two-thread lock-order inversion still deadlocks, and slow callbacks still block all threads. - Iterating over a shared mutable
listwithout copying. Self-unsubscription or concurrentunsubscribeshifts 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
isinstead of==. Passingpanel.on_resizetounsubscribeconstructs a new wrapper object that is equal (==) to the registered one, never identical (is). - Allowing one raising callback to abort the
forloop. Omitting per-listenertry ... exceptstarves every subscriber registered after a failing callback.
Alternative approaches
- Insertion-ordered
dict+ copy-on-fire: StoreDict[Listener, None]perevent_typesosubscribeandunsubscriberun inO(1)average time under_lock, whilefirecopiestuple(d)inO(k)time under_lock. Best when subscription churn dominates firing (requires hashable callbacks). - Lock striping across topic buckets: Partition
_listenersacrossMindependent shards (hash(event_type) % M), each guarded by its ownLock, 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
unsubscribereturns? Maintain a per-subscription state object under_lockcontaining anactiveflag and anin_flightcall counter paired with athreading.Condition(a synchronization primitive that lets threads sleep until notified). Around each callback insnapshot,firebriefly locks to checkactive, incrementsin_flight(recording the active thread ID), runs the callback unlocked, and then decrementsin_flightand notifies waiters.unsubscribesetsactive = Falseand waits untilin_flightdrops 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 acrossMstriped locks. Deduplicating, adding, and deleting hashable callbacks drop fromO(k)tuple allocations toO(1)hash-table operations under the shard lock, moving theO(k)tuple(d.keys())copy onto the much rarerfirecalls. - What changes if
firedispatches callbacks asynchronously on a worker pool rather than on the caller thread? Capturesnapshotunder_lockinsidefireexactly as before so publish-time snapshot semantics remain intact, then push(event_type, snapshot, payload)onto bounded worker queues. Route each event to worker shardhash(event_type) % num_workersif per-topic event order must be preserved, require anon_errorlogger/handler because the publisher has already returned, enforce an explicit full-queue backpressure policy (block publisher vs. drop with metrics), and provide aclose(drain=True)shutdown method using sentinel tokens so queued events finish cleanly.
Follow-up questions
- How would you guarantee that an unsubscribed callback never executes once `unsubscribe` returns?
- How would you adapt the data structures if subscription churn vastly exceeds event publishing?
- What changes if `fire` dispatches callbacks asynchronously on a worker pool rather than on the caller thread?
Similar questions
- Thread-Safe One-Shot Latch
- Square Submatrices Filled with Ones
- Counting Squares from 2D Integer Coordinates
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination