Event-Driven Communication
Services publish domain events when important business facts happen.
What you will be able to do
- Explain the difference between a command ("send this email") and an event ("an order was placed")
- Describe publish/subscribe: publishers, a broker, and subscribers the publisher does not know
- Show why events keep a service working when the services after it are down
- Decide what goes inside an event, and how to change an event without breaking subscribers
- Make a consumer safe against duplicate and out-of-order events
- Explain the dual-write problem, and when events are the wrong tool
The idea, in plain English
Lesson 5 showed services calling each other and waiting for the answer. That is fine when you need the answer right now. But when an order is placed, the order service does not need to wait for the confirmation email, the stock update and the analytics record - it only needs them to happen.
With event-driven communication, the order service announces a fact - OrderPlaced - and moves on. A message broker delivers the fact to every service that subscribed to it. Each subscriber decides for itself what to do. The order service does not know who is listening, and does not wait for any of them.
That makes services loosely coupled: new subscribers can be added without touching the publisher, and a subscriber that is down catches up later. The price is new kinds of problems - duplicates, ordering, eventual consistency and harder debugging. This lesson covers both sides.
Worked example: An order service that announces OrderPlaced once - and the email, inventory, analytics and loyalty services that each react on their own.
An everyday example: the school notice
A school moves an exam to Monday. The office can spread the news in two ways:
- By phone: the office calls the teachers, then the canteen, then the bus driver, and tells each what to do. If the bus driver does not answer, the office is stuck on the phone.
- By notice: the office posts one message in the staff group - "The exam has moved to Monday" - and gets back to work.
- Each reader decides what to do with it. Teachers change their plans; the canteen orders less food on Friday; the bus driver changes the route.
- Someone who was away reads the group when they come back. Nothing was lost.
- A new reader - the parents’ committee - joins the group. The office changes nothing.
- The notice states a FACT that already happened. It does not give orders.
The officeThe publisher - the service where the fact happened."The exam has moved to Monday"An event: a fact, in the past tense.The staff groupThe message broker, holding the event for each reader.Teachers, canteen, bus driverSubscribers - each decides its own reaction.Reading it after being awayA subscriber that was down catches up later.The parents’ committee joinsA new subscriber, with no change to the publisher.Phoning each personDirect calls - the caller waits, and depends on everyone answering.Commands and events
The difference is in who decides:
- A COMMAND asks one specific service to do something: "SendEmail to Ravi". The sender decides what happens, and usually waits to hear if it worked.
- An EVENT announces that something happened: "OrderPlaced". The sender does not decide what happens next - each subscriber does.
- Name events in the past tense, in the business’s words: OrderPlaced, PaymentFailed, ParcelShipped.
- An event is a fact, so it cannot be refused. A subscriber can only decide how to react to it.
- Commands go to one receiver. Events go to any number of subscribers - including none.
CommandDo this. One receiver. The sender decides, and often waits.EventThis happened. Any number of subscribers. Each decides.NamingCommands are imperative; events are past tense.Publish and subscribe
- The publisher sends the event to a TOPIC on the broker - a named channel such as "orders".
- Each subscriber registers interest in the topic, and the broker delivers a copy of every event to each of them.
- The publisher never lists its subscribers. It cannot - they can join at any time.
- The model below is a tiny in-memory event bus. Three services react to OrderPlaced.
- Then a loyalty service subscribes, and the next order gets loyalty points - with no change to order-service.
- Real brokers add what this model leaves out: they keep events on disk, deliver to subscribers on other machines, and retry until each one confirms.
from collections import defaultdict
subscribers = defaultdict(list)
def subscribe(event_type, handler):
subscribers[event_type].append(handler)
def publish(event_type, data):
print(f"published {event_type} {data}")
for handler in subscribers[event_type]:
handler(data)
# Three services subscribe to the same fact
subscribe("OrderPlaced", lambda e: print(f" email-service sends a confirmation for order {e['order_id']}"))
subscribe("OrderPlaced", lambda e: print(f" inventory-service reserves {', '.join(e['items'])}"))
subscribe("OrderPlaced", lambda e: print(f" analytics-service records Rs {e['total']}"))
def place_order(order_id, items, total):
# ... save the order in order-service's own database ...
publish("OrderPlaced", {"order_id": order_id, "items": items, "total": total})
place_order(812, ["pen", "book"], 270)
# A new team adds loyalty points - order-service does not change at all
subscribe("OrderPlaced", lambda e: print(f" loyalty-service adds {e['total'] // 10} points"))
place_order(813, ["bag"], 900)
# published OrderPlaced {'order_id': 812, 'items': ['pen', 'book'], 'total': 270}
# email-service sends a confirmation for order 812
# inventory-service reserves pen, book
# analytics-service records Rs 270
# published OrderPlaced {'order_id': 813, 'items': ['bag'], 'total': 900}
# email-service sends a confirmation for order 813
# inventory-service reserves bag
# analytics-service records Rs 900
# loyalty-service adds 90 pointsorder-service publishes:
-> OrderPlaced { order_id, items, customer_id, total }
-> OrderCancelled { order_id, reason }
-> OrderShipped { order_id, tracking_id }
Subscribers react:
email-service listens to OrderPlaced, OrderShipped
inventory-service listens to OrderPlaced, OrderCancelled
analytics-service listens to all order eventsWhy it keeps the publisher working
- With direct calls, order-service calls email-service and waits. If email-service is down, the order fails - for a confirmation email.
- With events, order-service records the fact and is done. The broker holds the event until email-service can take it.
- When email-service comes back, the waiting event is delivered, and the email goes out - late, but not lost.
- The model removes an event from the queue only AFTER the subscriber succeeds. Real brokers do the same: the subscriber acknowledges each event, and anything not acknowledged is delivered again.
- So a failure in one subscriber no longer spreads back to the publisher.
email_up = False
def send_email(order_id):
if not email_up:
raise ConnectionError("email-service unavailable")
return f"email sent for {order_id}"
# 1. Direct calls: order-service calls email-service and waits.
def place_order_direct(order_id):
send_email(order_id) # if this fails, the order fails
return f"order {order_id} placed"
# 2. Events: record the fact; the broker holds it for each subscriber.
email_queue = []
def place_order_events(order_id):
email_queue.append({"type": "OrderPlaced", "order_id": order_id})
return f"order {order_id} placed"
def deliver_email_events():
while email_queue:
event = email_queue[0]
try:
print(" ", send_email(event["order_id"]))
email_queue.pop(0) # remove only after success
except ConnectionError as e:
print(f" still waiting: {e}")
return
for design in (place_order_direct, place_order_events):
try:
print(f"{design.__name__:<20} OK:", design(812))
except ConnectionError as e:
print(f"{design.__name__:<20} FAILED:", e)
print("events waiting for email-service:", len(email_queue))
deliver_email_events()
email_up = True
print("email-service is back")
deliver_email_events()
print("events waiting for email-service:", len(email_queue))
# place_order_direct FAILED: email-service unavailable
# place_order_events OK: order 812 placed
# events waiting for email-service: 1
# still waiting: email-service unavailable
# email-service is back
# email sent for 812
# events waiting for email-service: 0What goes inside an event
- An envelope: a unique event_id, the event type, when it happened, and a version number for the event’s format.
- The data: the facts subscribers need, under stable field names.
- THIN event (notification): only ids - "order 812 was placed". Subscribers call back for details. Small, but every subscriber now calls the publisher.
- FAT event (event-carried state): everything subscribers need - items, total, customer. No call-backs, so subscribers keep working even if the publisher is down (Self-Contained Service, Lesson 4).
- Most teams lean fat, but include only facts about THIS event - not the whole customer record.
{
"event_id": "e-7f3a9c",
"type": "OrderPlaced",
"version": 2,
"occurred_at": "2026-10-31T19:30:00Z",
"data": {
"order_id": 812,
"customer_id": 7,
"items": [{ "sku": "P1", "qty": 3 }, { "sku": "P3", "qty": 2 }],
"total": 270
}
}Events are an API: change them carefully
- Once other teams subscribe, an event’s format is a contract - like a public API, but you may not even know who uses it.
- SAFE changes: add a new optional field. Old subscribers ignore it.
- BREAKING changes: rename or remove a field, or change what it means or its type. Old subscribers break.
- For a breaking change, publish a new version alongside the old one - "version": 3 - and retire the old one only when every subscriber has moved.
- Many teams keep event formats in a schema registry, so a breaking change is caught before it ships.
Watch out: Renaming total to amount "to be consistent" breaks every subscriber that reads total - often in another team, often silently. Add the new field, keep the old one, and remove it later.
The hard parts: duplicates and ordering
- DUPLICATES: brokers deliver at least once. After a crash or a timeout, the same event can arrive twice. A consumer that adds loyalty points would add them twice.
- Fix: make consumers IDEMPOTENT - safe to run twice. Remember the event_ids already handled and skip repeats (or design the update so repeating it changes nothing).
- ORDERING: events can arrive out of order - "shipped" after "delivered". Applied blindly, the order goes back to "shipped".
- Fix: give each event a version (or sequence number) per order, and ignore anything older than what you already have.
- Brokers such as Kafka keep events in order per key, so sending all events for one order with the same key (the order_id) helps - but consumers should still check.
points = {"ravi": 0}
processed = set() # event ids this consumer has handled
def on_order_placed_naive(event):
points[event["customer"]] += event["total"] // 10
def on_order_placed_idempotent(event):
if event["event_id"] in processed:
return "skipped duplicate"
processed.add(event["event_id"])
points[event["customer"]] += event["total"] // 10
return "applied"
event = {"event_id": "e-812", "customer": "ravi", "total": 900}
for _ in range(2): # the broker delivers it twice
on_order_placed_naive(event)
print("naive consumer: ", points["ravi"], "points")
points["ravi"] = 0
for _ in range(2):
print(" ", on_order_placed_idempotent(event))
print("idempotent consumer:", points["ravi"], "points")
# naive consumer: 180 points
# applied
# skipped duplicate
# idempotent consumer: 90 pointsevents_in_arrival_order = [
{"order_id": 812, "version": 1, "status": "placed"},
{"order_id": 812, "version": 3, "status": "delivered"},
{"order_id": 812, "version": 2, "status": "shipped"}, # arrives late
]
naive = {}
for e in events_in_arrival_order:
naive[e["order_id"]] = e["status"]
print("last event wins: ", naive[812])
latest = {}
for e in events_in_arrival_order:
current = latest.get(e["order_id"])
if current is None or e["version"] > current["version"]:
latest[e["order_id"]] = e
else:
print(f" ignored stale version {e['version']} ({e['status']})")
print("highest version wins:", latest[812]["status"])
# last event wins: shipped
# ignored stale version 2 (shipped)
# highest version wins: deliveredPublishing reliably: the dual-write problem
- Placing an order is two writes: save the order in the database, then publish OrderPlaced to the broker.
- They are separate systems, so they cannot be one transaction. If the service crashes between them, the order exists but the event is lost - no email, no stock reservation.
- Publishing first and saving second is no better: the event goes out for an order that was never saved.
- The usual fix is the Transactional Outbox (Lesson 19): save the event in the SAME database transaction as the order, and let a separate process publish it.
database, broker = [], []
def place_order(order_id, crash_after_save=False):
database.append(order_id) # write 1: the order
if crash_after_save:
raise RuntimeError("process crashed")
broker.append({"type": "OrderPlaced", "order_id": order_id}) # write 2: the event
place_order(812)
try:
place_order(813, crash_after_save=True)
except RuntimeError as e:
print("order 813:", e)
print("orders saved: ", database)
print("events published: ", [e["order_id"] for e in broker])
print("lost events: ", [o for o in database if o not in [e["order_id"] for e in broker]])
# order 813: process crashed
# orders saved: [812, 813]
# events published: [812]
# lost events: [813]When events are the wrong tool
- When the caller NEEDS the answer to continue: "is this card valid?", "what is the price?". Use a direct call (Lesson 5).
- When the user must see the result immediately and cannot accept "processing".
- When there is really only one receiver and you want to know it succeeded - that is a command, sent through a queue (Asynchronous Messaging, Lesson 6).
- When the flow is long and must succeed or be undone as a whole - plan it as a saga (Lessons 22-23).
- And remember the debugging cost: a chain of events has no single call stack. Carry a correlation id in every event (Lesson 34) and trace it (Lesson 31).
Apache KafkaA durable, ordered log; subscribers can replay history. High volume.RabbitMQFlexible routing of messages to queues; strong at work queues and commands.AWS SNS + SQSSNS fans a message out to many SQS queues, one per subscriber.AWS EventBridgeAn event bus with routing rules on event content.Google Pub/SubManaged topics and subscriptions.Event-driven communication at a glance
EventA fact that happened, in the past tense.
OrderPlaced
CommandA request to one service to do something.
SendEmail
Publisher / subscriberThe publisher does not know its subscribers.
publish("OrderPlaced", ...)TopicA named channel on the broker.
orders
At-least-once deliveryAn event may arrive more than once.
make consumers idempotent
Version per entityIgnore events older than what you have.
if e.version > current
Event versionAdd fields freely; publish a new version for breaking changes.
"version": 2
Dual writeSaving and publishing separately can lose events.
Transactional Outbox
What usually goes wrong
An event called "SendWelcomeEmail" tells one service what to do - the publisher still decides and still depends on it. Publish the fact instead; let the email service decide.
✗ publish("SendWelcomeEmail", {...})✓ publish("CustomerSignedUp", {...})Brokers can deliver an event twice. A consumer that adds points, charges money or sends a message must not do it twice.
✗ points[c] += total // 10✓ if event_id in processed: return
processed.add(event_id)
points[c] += total // 10Subscribers in other teams depend on the format. Add new fields, keep the old ones, and version breaking changes.
A crash in between loses the event. Use the Transactional Outbox.
If the next step depends on the result - a price, a payment approval - a direct call is simpler and honest about the dependency.
Without an id carried through every event, nobody can follow one order across six services when something goes wrong.
Practice
Write these yourself before opening anything. Getting them wrong first is most of how this sticks.
Command or event? SendInvoice, PaymentReceived, ReserveStock, ParcelDelivered, CancelOrder, CustomerAddressChanged.
Show hintHide hint
Is it telling someone what to do, or saying what happened?
Show solutionHide solution
Commands: SendInvoice, ReserveStock, CancelOrder
Events: PaymentReceived, ParcelDelivered, CustomerAddressChangedA course platform publishes CourseCompleted. List three services that might subscribe, and what each does - then say what changes in the publisher when a fourth is added.
Show solutionHide solution
certificate-service creates and emails a certificate
recommendation-service suggests the next course
analytics-service updates completion rates
A fourth subscriber (say, a leaderboard) needs no change in the
publisher - it just subscribes to CourseCompleted.The team wants to rename "total" to "amount" in OrderPlaced. How do you do it without breaking subscribers?
Show solutionHide solution
1. Add "amount" alongside "total" (same value). Adding a field is safe.
2. Tell subscribers; let each switch to "amount" at its own pace.
3. When none read "total" any more, remove it - as a new event version
if any subscriber might still depend on it.Key points
- An event is a fact in the past tense; a command asks one service to act.
- The publisher announces the fact and moves on; subscribers decide their own reactions.
- The publisher does not know its subscribers, so new ones need no change to it.
- A broker holds events for a subscriber that is down, so failures do not spread back to the publisher.
- Events are a contract: add fields freely, version breaking changes.
- Delivery is at least once - make consumers idempotent.
- Events can arrive out of order - use a version per entity and ignore stale ones.
- Saving and publishing separately can lose events - use the Transactional Outbox.
- When you need the answer now, use a direct call instead.
Quick check before you move on
Interview questions
What is event-driven architecture?
Services communicate by publishing events - facts that happened - to a broker, and other services subscribe and react. Publishers do not know their subscribers, which keeps services loosely coupled and lets new consumers be added without changing producers.
How do you handle duplicate events?
Assume at-least-once delivery and make consumers idempotent: record processed event ids (often in the same transaction as the side effect) and skip repeats, or design updates so applying them twice has no extra effect.
How do you evolve an event schema?
Treat it as a public contract. Additive changes - new optional fields - are safe. For breaking changes, publish a new version alongside the old one and retire the old version once all consumers have migrated; a schema registry can enforce compatibility.
What problems does event-driven communication introduce?
Eventual consistency, duplicate and out-of-order delivery, the dual-write problem when publishing, harder debugging without a single call stack, and contract management across teams. They are handled with idempotent consumers, versioning, the transactional outbox, correlation ids and tracing.
Quiz
- 1.
Why does an event-driven order service keep working when email-service is down?
- 2.
What is the difference between a thin and a fat event?
- 3.
Events for one order arrive as placed, delivered, shipped. How should a consumer handle that?
- 4.
When should you use a direct call instead of an event?
Comments
Sign in to leave a comment. Your name and photo come from Google; nothing else is shared.
Loading comments...