Event-Driven Architecture
In a request-driven system, services call each other: "Order service, please tell Billing to charge, then tell Shipping to ship." In an event-driven system, services announce facts and others react: "An order was placed." Billing, Shipping and Analytics each listen for that event and do their part. The publisher doesn't know, or care, who is listening.
Request-driven (commands) Event-driven (facts)
orders --charge()--> billing orders --"OrderPlaced"--> [event bus]
orders --ship()----> shipping |-> billing
orders --track()---> analytics |-> shipping
(orders knows every downstream service) |-> analytics
|-> (new) loyalty points| Commands / RPC | Events | |
|---|---|---|
| Naming | Imperative: ChargeCard |
Past tense: PaymentSucceeded |
| Coupling | Caller knows the receiver | Publisher doesn't know subscribers |
| Adding a consumer | Change the caller | Just subscribe |
| Failure of a consumer | Caller sees an error | Others carry on; the consumer catches up later |
| Hard part | Cascading failures, latency chains | Eventual consistency, tracing a flow, event versioning |
A tiny event bus
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, **data):
print(f"[bus] {event_type} {data}")
for handler in self.handlers[event_type]:
handler(self, data)
def billing(bus, order):
bus.publish("PaymentSucceeded", order_id=order["order_id"], amount=order["total"])
def shipping(bus, payment):
print(f" shipping: packing order {payment['order_id']}")
def loyalty(bus, order):
print(f" loyalty: +{order['total'] // 10} points for {order['customer']}")
bus = EventBus()
bus.subscribe("OrderPlaced", billing)
bus.subscribe("OrderPlaced", loyalty) # added later, no change to orders
bus.subscribe("PaymentSucceeded", shipping)
bus.publish("OrderPlaced", order_id=7, customer="ana", total=120)[bus] OrderPlaced {'order_id': 7, 'customer': 'ana', 'total': 120}
[bus] PaymentSucceeded {'order_id': 7, 'amount': 120}
shipping: packing order 7
loyalty: +12 points for ana
The order service published one event. Billing reacted and published its own event, which triggered shipping. This chain of reactions is called choreography: no central coordinator, just services reacting to each other.
Event sourcing
Most databases store the current state and overwrite it. Event sourcing stores the sequence of events instead, and derives state by replaying them. The event log is the source of truth; the current state is just a cached fold over it.
events = [
{"type": "AccountOpened", "account": "A-1", "owner": "Ana"},
{"type": "MoneyDeposited", "account": "A-1", "amount": 100},
{"type": "MoneyWithdrawn", "account": "A-1", "amount": 30},
{"type": "MoneyDeposited", "account": "A-1", "amount": 50},
{"type": "MoneyWithdrawn", "account": "A-1", "amount": 200}, # rejected below
]
def apply(state, event):
kind = event["type"]
if kind == "AccountOpened":
return {"owner": event["owner"], "balance": 0, "history": []}
if kind == "MoneyDeposited":
state["balance"] += event["amount"]
elif kind == "MoneyWithdrawn":
if event["amount"] > state["balance"]:
state["history"].append(f"rejected withdrawal of {event['amount']}")
return state
state["balance"] -= event["amount"]
state["history"].append(f"{kind} {event['amount']} -> {state['balance']}")
return state
state = None
for e in events:
state = apply(state, e)
print(state["owner"], "balance:", state["balance"])
for line in state["history"]:
print(" ", line)
# Time travel: the state after the first three events
past = None
for e in events[:3]:
past = apply(past, e)
print("balance after 3 events:", past["balance"])Ana balance: 120
MoneyDeposited 100 -> 100
MoneyWithdrawn 30 -> 70
MoneyDeposited 50 -> 120
rejected withdrawal of 200
balance after 3 events: 70
In a real system the rejected withdrawal would be rejected before an event is written (a command is validated, then the resulting fact is stored); here we keep it simple to show replay.
| Event sourcing gives you | It costs you |
|---|---|
| A complete audit log for free | More storage, and replay time (fixed with snapshots) |
| Time travel and debugging ("what did the state look like yesterday?") | Changing event formats needs versioning/upcasting |
| New read models built later by replaying history | Queries need separate projections (CQRS) |
CQRS: separate read models
Command Query Responsibility Segregation splits the write side (validates commands, appends events) from one or more read models (projections) that are updated from the events and shaped for specific queries. The read side is eventually consistent with the write side.
from collections import defaultdict
events = [
("OrderPlaced", {"order": 1, "customer": "ana", "total": 120, "product": "lamp"}),
("OrderPlaced", {"order": 2, "customer": "ben", "total": 40, "product": "mug"}),
("OrderPlaced", {"order": 3, "customer": "ana", "total": 15, "product": "mug"}),
("OrderCancelled", {"order": 2}),
]
# Two projections built from the same log, each shaped for one screen
spend_by_customer = defaultdict(int)
sales_by_product = defaultdict(int)
orders = {}
for kind, data in events:
if kind == "OrderPlaced":
orders[data["order"]] = data
spend_by_customer[data["customer"]] += data["total"]
sales_by_product[data["product"]] += 1
elif kind == "OrderCancelled":
o = orders.pop(data["order"])
spend_by_customer[o["customer"]] -= o["total"]
sales_by_product[o["product"]] -= 1
print("customer dashboard:", dict(spend_by_customer))
print("product report: ", dict(sales_by_product))customer dashboard: {'ana': 135, 'ben': 0}
product report: {'lamp': 1, 'mug': 1}
The outbox pattern
A service often needs to update its database and publish an event. Doing both separately is unsafe: the process can crash between the two, and then the event is lost (or published for a change that was rolled back). The transactional outbox writes the event into an outbox table in the same database transaction as the state change; a separate relay reads the outbox and publishes to the broker, at least once.
BEGIN
UPDATE orders SET status = 'paid' WHERE id = 7;
INSERT INTO outbox (event_type, payload) VALUES ('OrderPaid', '{"id": 7}');
COMMIT
relay: SELECT * FROM outbox WHERE published = false -> publish -> mark publishedTip: Events are a public contract. Give them a version field, only add optional fields, and never reuse a name for a different meaning; consumers you've never heard of may depend on them.
Test yourself
How should events usually be named?
- As commands:
ChargeCard - As past-tense facts:
PaymentSucceeded - After the consumer:
BillingHandler - With random ids
In event sourcing, what is the source of truth?
- The current-state table
- The append-only log of events
- The cache
- The read model
What problem does the transactional outbox pattern solve?
- Slow queries
- Losing or inventing events when a crash happens between the DB write and the publish
- Message ordering across partitions
- Schema migrations