Sub topic 2
Producers and Consumers: Decoupling by Publishing Facts
This chapter assumes you know basic programming, HTTP request/response APIs, and what a distributed system is. It builds on the previous chapter's distinction between events and commands.
The two roles
A producer is a component that detects that something happened and publishes an event describing it. A consumer is a component that receives events and reacts to them. One component can be both. An order service might consume payment.completed and then produce order.confirmed.
The key design rule is that a producer publishes a fact about its own domain. It does not tell anyone what to do. order.placed is a fact. "Reserve stock" is a command aimed at a specific receiver.
Why this decouples a system
In a request/response design, the order service calls the inventory service, then the email service. It must know their addresses, wait for their replies, and change its own code whenever a new reaction is needed.
With events, the producer publishes once. It does not know which consumers exist, how many there are, or whether they are running. Adding a new reaction means adding a consumer, with no change to the producer.
from collections import defaultdict
class EventBus:
def __init__(self):
self._handlers = defaultdict(list)
def subscribe(self, event_type, handler):
self._handlers[event_type].append(handler)
def publish(self, event_type, payload):
for handler in self._handlers[event_type]:
handler(payload)
bus = EventBus()
bus.subscribe("order_placed", lambda e: print("reserve stock for", e["order_id"]))
bus.subscribe("order_placed", lambda e: print("send receipt for", e["order_id"]))
bus.publish("order_placed", {"order_id": "o-1"})The publish method never names a handler. One event reaches two independent handlers. A real broker does the same job across processes and machines.
What decoupling does and does not remove
Decoupling removes three kinds of dependency:
- Knowledge: the producer does not know who consumes.
- Time: consumers can be slow or offline, and process the event later.
- Failure: a crashed consumer does not make the producer's publish fail.
It does not remove the shared contract. Both sides depend on the event's name and fields. If the producer renames totalCents, consumers break. Later chapters cover schema versioning.
Common errors
- Disguised commands. An event named
send.email.requestedis a command with a different label. The producer still expects a specific outcome, so the coupling remains. - Expecting a reply. A producer that waits for a consumer's result has rebuilt a synchronous call. If you need an answer, use request/response, or have the consumer publish its own event in return.
- Assuming handlers run in order or exactly once. Consumers run independently, and the broker may redeliver. Handlers must not depend on each other's side effects.
- Hidden flow. With no caller chain to read, the overall process is harder to see. Document which events exist and who consumes them.
Exercise
An invoice.generate message is published by the billing service, and exactly one document service must produce the PDF. Is this an event? Name the better way to describe it and what changes in the design.
Show answer
It is a command, not an event. It names an action and expects one specific receiver to perform it. An event would be order.completed, a fact that billing consumes and then decides to generate an invoice. Billing then publishes invoice.generated when done. This keeps the order service free of knowledge about invoices.