Sub topic 2
Producers and consumers: decoupling by publishing facts
This chapter assumes you can write basic code in any language and know how HTTP request/response APIs work. It also assumes you know what a database transaction is. The previous chapter separated events from commands. Here we look at the two roles that make event-driven systems work: the producer that publishes events and the consumer that reacts to them.
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 does work in response. A single service is often both. An order service consumes payment.completed and produces order.confirmed.
The key rule is that a producer states a fact and does not tell anyone what to do about it. It publishes order.placed. It does not publish "reserve stock" or "send a receipt". Those reactions belong to consumers, and the producer does not need to know they exist.
Compare two designs for placing an order.
Request/response (orchestration by the caller):
- The order service calls the inventory service to reserve stock.
- It calls the email service to send a receipt.
- It calls the analytics service to record the sale.
- It returns a response to the user.
Event-driven:
- The order service saves the order and publishes
order.placed. - It returns a response to the user.
- Inventory, email and analytics each react on their own.
In the first design the order service must know every downstream system, wait for each one, and change whenever a new reaction is needed. In the second, adding a fraud-check service means adding a new consumer. The order service is not touched.
What decoupling means
"Decoupled" is a loose word, so it helps to name what is actually separated. Producers and consumers become independent in four ways.
| Kind of coupling | Request/response | Event-driven |
|---|---|---|
| Knowledge of the other party | Caller knows the callee's address and API | Producer knows only the event type |
| Timing | Callee must be up now | Consumer can be down and catch up later |
| Number of receivers | Caller handles each one | Zero, one or many consumers, no producer change |
| Failure | Callee failure becomes caller failure | Consumer failure does not fail the producer |
Decoupling is not total. Producer and consumer still share one thing: the event contract, meaning the event's name, fields and meaning. Changing a field name can break every consumer. Later chapters on schemas and versioning deal with this. Treat the event as a public API.
A minimal example
The following in-process bus shows the shape of the relationship. The producer calls publish and has no reference to any consumer.
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"})Running it prints one line per subscriber. Adding a third subscribe call changes nothing on the publishing side.
This toy bus hides three things that a real system must handle:
- It is synchronous.
publishreturns only after every handler finishes, so a slow handler slows the producer, and an exception in one handler stops the loop and prevents later handlers from running. - It lives in one process. If the process dies, pending work is lost.
- It has no delivery guarantees, no retries and no history.
A broker, covered in the next chapter, exists to supply these. For now, note that real decoupling requires the producer's publish call to hand the event to something durable and then return.
Designing a good event
An event is a record of something that already happened. Several habits follow from that.
- Name it in the past tense.
order.placed,payment.failed,address.changed. A name likereserve.stockis a command in disguise. - Describe the fact, not the intended reaction. The producer should not shape the event around what one consumer wants to do.
- Include an identity. A unique
idlets consumers detect duplicates. A timestamp and a type let them route and order. - Make it immutable. An event is never edited after publication. If the fact was wrong, publish a new event that corrects it.
An envelope that follows these habits:
{
"id": "6f1c2d9e-3b7a-4c55-9d0e-1a2b3c4d5e6f",
"type": "order.placed",
"version": 1,
"occurredAt": "2026-11-26T11:00:00Z",
"data": {
"orderId": "o-1",
"customerId": "c-9",
"totalCents": 4599
}
}The id supports deduplication, type and version support routing and schema evolution, and occurredAt records when the fact happened. The data block holds the business details.
What the producer is responsible for
Producers are not free of obligations just because they do not know their consumers.
- Publish only true facts. If you publish
order.placedand then the order save rolls back, consumers will act on an order that does not exist. - Publish reliably. If the order is saved but the process crashes before publishing, the order exists and nobody learns about it. The two actions, a database write and a publish, are not atomic by default. The transactional outbox chapter solves this.
- Keep the contract stable. Add fields compatibly and version breaking changes.
- Do not depend on a reaction. If the producer needs a result from a consumer before it can continue, the interaction is really a request, and an event is the wrong tool.
What the consumer is responsible for
Consumers carry most of the hard work in this style.
- Expect duplicates. Most brokers deliver at least once, so the same event can arrive twice. The consumer must be idempotent, meaning that handling an event twice has the same effect as handling it once.
- Expect delay and disorder. An event may arrive seconds or minutes after it was published, and sometimes out of order relative to others.
- Handle failure explicitly. Decide what happens when processing fails: retry, skip, or move the event to a dead-letter queue.
- Own its data. A consumer that needs information from an event stores what it needs in its own database. It should not call back to the producer for every event, since that recreates the coupling.
- Ignore what it does not understand. A consumer should tolerate unknown extra fields so producers can add data safely.
The following consumer shows the first responsibility. It remembers the IDs of handled events, so a redelivery does not apply the deposit twice.
balances = {"acct-1": 100}
processed_ids = set()
def handle_deposit(event):
if event["event_id"] in processed_ids:
return # duplicate delivery: do nothing
balances[event["account"]] += event["amount"]
processed_ids.add(event["event_id"])
event = {"event_id": "e-42", "account": "acct-1", "amount": 25}
handle_deposit(event)
handle_deposit(event) # redelivered by the broker
print(balances["acct-1"]) # 125, not 150A real system would store the event ID and the balance change in one database transaction. Otherwise a crash between the two steps leaves the state inconsistent.
Common mistakes
- Disguised commands. Publishing
send.email.requestedto a topic that only one service reads is a command wearing an event's name. It is not always wrong, but then you should model it as a command on a queue and be honest about the coupling. - Chatty events that force callbacks. If every consumer must call the producer to get the details, the producer is back on the critical path. Consider carrying the needed data in the event, a choice covered in the chapter on event notification versus state transfer.
- Hidden dependencies. A producer that "knows" that a certain consumer will update a record, and relies on that for correctness, has coupling that no code or diagram shows. Such hidden coupling makes systems hard to change.
- Assuming read-your-writes. After publishing, the consumer's effect is not yet visible. A user who places an order and immediately views "stock remaining" may see old data. This is eventual consistency, covered later.
- Unbounded fan-out without ownership. When anyone can subscribe to anything, nobody knows who depends on an event. Record the owner and the consumers of each event type.
Summary
- A producer publishes facts and does not know who reacts. A consumer reacts and does not know who produced.
- The gain is independence in knowledge, timing, number of receivers and failure.
- The cost is a shared event contract, plus consumer duties: idempotency, tolerance of delay and disorder, and explicit failure handling.
- Producers must publish only true facts and publish them reliably.
Exercise
A checkout service needs to know whether payment succeeded before it shows the user a confirmation page. A teammate suggests it publish payment.requested and wait for a payment.completed event. Is this a good use of producers and consumers, and what would you change or keep?
Show answer
It is a weak fit as described. The checkout service depends on the reaction to continue, so the interaction is really a request with a required answer, and waiting on an event reintroduces timing coupling with extra complexity. A direct request/response call to the payment service fits better for the confirmation step. Events still fit afterward: once payment succeeds, the payment service can publish payment.completed as a fact for other consumers such as receipts, accounting and fraud analysis, without the checkout service knowing about them. Alternatively, the checkout page can show "processing" and update when the event arrives, which accepts eventual consistency.
Exercise
Why does the in-process EventBus above not give real decoupling, and name two problems a broker would address?
Show answer
The producer's publish call runs every handler inline, so a slow handler delays the producer and an exception in one handler can stop the others. The bus also lives in one process, so events are lost on a crash. A broker addresses this by storing events durably, delivering to consumers asynchronously, and providing retries, delivery guarantees and history, so consumers can be down and catch up later.