Event Bus / Publisher-Subscriber
Event Bus / Publisher-Subscriber
The mechanism behind EDA: a registry that maps event types to subscriber functions, dispatches events to all interested subscribers, and decouples publisher from consumer.
Minimal in-process bus
from typing import Callable
from collections import defaultdict
class EventBus:
def __init__(self):
self._subs: dict[type, list[Callable]] = defaultdict(list)
def subscribe(self, event_type: type, handler: Callable) -> None:
self._subs[event_type].append(handler)
def publish(self, event) -> None:
for handler in self._subs[type(event)]:
handler(event)
That's it. Everything beyond is policy: delivery guarantees, error handling, async dispatch.
The contract
- Publisher knows: event type and payload.
- Subscriber knows: event type it cares about and what to do.
- Bus knows: who subscribes to what.
Neither publisher nor subscriber knows about the other.
Sync vs async dispatch
# Synchronous: subscribers run before publish() returns
def publish(self, event):
for handler in self._subs[type(event)]:
handler(event)
# Asynchronous (queue-backed): publish enqueues
async def publish(self, event):
await self._queue.put(event)
See the Sync vs Async note for the trade-offs.
Wiring subscribers
Three styles:
# Function subscriber
def log_order_placed(event: OrderPlaced) -> None: ...
bus.subscribe(OrderPlaced, log_order_placed)
# Bound method subscriber
class InventoryTracker:
def handle(self, event: OrderPlaced) -> None: ...
tracker = InventoryTracker()
bus.subscribe(OrderPlaced, tracker.handle)
# Callable object (__call__) subscriber
class EmailNotifier:
def __init__(self, smtp): self._smtp = smtp
def __call__(self, event: OrderPlaced) -> None: ...
bus.subscribe(OrderPlaced, EmailNotifier(smtp))
For stateless logic -> function. For stateful logic with a clear "react" method -> bound method. For configurable callable -> __call__. Prefer the named method (.handle) in OOP code — clearer stack traces, easier to subscribe multiple methods per class.
Error handling
If one subscriber throws, what happens to the others?
def publish(self, event):
for handler in self._subs[type(event)]:
try:
handler(event)
except Exception as e:
self._on_error(event, handler, e) # log, retry, etc.
Three policies:
| Policy | When |
|---|---|
| Fail-fast (first error aborts) | Tight invariants; need all-or-nothing |
| Best-effort (log, continue) | Independent reactions; one failure shouldn't break others |
| Per-subscriber retry | Async bus with broker semantics |
Default to best-effort with logging for in-process buses.
Anti-patterns
- Type-string subscriptions.
bus.subscribe("OrderPlaced", handler)instead ofbus.subscribe(OrderPlaced, handler). Loses type safety, breaks silently on rename. - Subscriber that publishes. Cycle risk. Possible but easy to introduce infinite loops.
- Publisher querying subscribers. "How many subscribers do I have?" — coupling smell.
- Bus as god object. Every component takes the bus and reaches into it for arbitrary calls. Pass the bus only to publishers; subscribers register at composition.
- One global bus singleton. Hard to test, hard to scope. Inject the bus.
Broker-backed buses
For cross-context events, replace the in-process dict with a broker:
class KafkaEventBus:
async def publish(self, event):
await self._producer.send(topic_of(event), serialize(event))
async def subscribe(self, topic, handler):
await self._consumer.subscribe(topic)
async for msg in self._consumer:
handler(deserialize(msg))
Same interface, different transport. Subscribers don't know they moved.
Testing
Inject a fake bus that records published events:
class RecordingBus:
def __init__(self):
self.published = []
def publish(self, event):
self.published.append(event)
bus = RecordingBus()
order = Order(...)
order.place()
for event in order.pull_events():
bus.publish(event)
assert bus.published == [OrderPlaced(order_id=order.id, ...)]
No mocks, no monkey-patching, plain dependency injection.