Route Domain Events through Explicit Subscribers
Core idea
An event describes something that happened, while a command requests an action. A publisher can emit a named event to explicitly registered subscribers without knowing their concrete implementations. A synchronous in-process dispatcher calls subscribers before returning; it does not provide durable delivery, retries or asynchronous isolation. Define ordering and failure behavior.
handlers = {}def subscribe(topic, handler): handlers.setdefault(topic, []).append(handler)def publish(topic, payload): for handler in handlers.get(topic, []): handler(payload)log = []subscribe('packed', log.append)publish('packed', 'A7')publish('sent', 'B2')print(log)Only subscribers for the selected topic receive the payload.
Expected output:
['A7']Observe fail-fast delivery
def fail(event): raise ValueError('handler failed')seen = []try: for handler in [fail, seen.append]: handler('packed')except ValueError: print('failed', seen)The first exception aborts the loop; the second subscriber is not invoked.
Expected output:
failed []Common mistake
Do not assume dispatch is transactional or exactly-once. A subscriber may have performed a side effect before another fails. Avoid invisible global registration and document failure handling.
Practice
Add two subscribers and record their call order. Design a separate collect-errors policy and explain how it differs from fail-fast.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Event-driven design
Check your understanding of event-driven design.
What is printed?
handlers={"a":[1,2]}print(len(handlers.get("b",[])))What is printed?
out=[]for fn in [out.append,out.append]: fn("x")print(out)What does a domain event represent?
What does this dispatcher not guarantee?