0% completed
Event-Driven Architecture
On This Page
What Event-Driven Architecture Means
The Cost of a Thin Event
Event-Carried State Transfer
Local Views
Stale Views and Eventual Consistency
Personal Data in Events
Knowing Who Consumes What
When to Use Event-Driven Architecture
Check Yourself
Summary
Here is one fact written as an event in two different ways. The fact is that a buyer has placed an order in an online store.
{ "type": "order.placed", "eventId": "evt_5521", "orderId": "ord_8f31", "placedAt": "10:00:02" }
{ "type": "order.placed", "eventId": "evt_5521", "orderId": "ord_8f31", "orderVersion": 1, "placedAt": "10:00:02", "buyer": { "id": "u_204", "email": "maya@example.com" }, "items": [{ "sku": "BOOK-SIGNED-01", "qty": 1, "price": 40.00 }], "total": 40.00, "shipTo": { "name": "Maya Ortiz", "street": "12 Lake Road", "city": "Austin", "zip": "78701" } }
The first version has the three fields of the event in the Publish-Subscribe lesson, plus a type field. It is about 100 bytes and says only that order ord_8f31 was placed, and when. The second is about 400 bytes, and it says what was bought, by whom, for how much, and where it must go. In the store, five services listen for this event, and every one of them needs some of those details before it can do its work.
With the first version, each of the five services must call checkout and ask for the order. With the second version, each of them already has what it needs, and nobody calls anyone. This lesson explains event-driven architecture, why the short version (a thin event) costs so much, and the three problems that the full version brings: stale copies, personal data, and hidden dependencies.
What Event-Driven Architecture Means
An event is a record of something that has already happened, like "order ord_8f31 was placed". It is named in the past tense because it describes a fact, and a fact cannot be refused. In event-driven architecture, services communicate mainly by publishing events and reacting to the events of other services, instead of calling each other and waiting. The name says that events drive the work: a service acts because a fact arrived, not because another service told it to act.
An event is different from a command. A command, like "ship order ord_8f31", asks one service to do something, and that service may refuse. An event is addressed to nobody, and checkout does not know which services will react to it.
The Publish-Subscribe lesson built the transport for this. Checkout publishes order.placed once to a broker. A broker is a server that receives events and delivers them, and each subscribing service receives its own copy. In this store, five services subscribe:
- Fulfillment schedules shipping, so it needs the items and the address.
- Email sends the receipt, so it needs the buyer's email, the items, and the total.
- Loyalty awards one point per dollar, so it needs the buyer ID and the total.
- Analytics builds sales reports, so it needs the items and the total.
- Fraud checks each order for signs of a stolen card, so it needs the buyer ID, the total, and the address.
Publish-subscribe decides how an event travels. Event-driven architecture also decides what the event carries. That choice sets how much the services depend on each other.
The Cost of a Thin Event
An event that carries an ID but none of the details is called a thin event, or an event notification. The service that publishes an event is the producer, which is checkout here. A thin event tells subscribers that something happened, and each subscriber must then ask the producer for the details.
The top panel shows the thin event. Each of the five subscribers receives ord_8f31 and sends a request to checkout's order API to read the order. The bottom panel shows the full event, where the same five subscribers receive the details and send nothing back.
These calls back to checkout are callbacks, and each subscriber adds more. On a normal day, the store receives 200 orders per second, so five subscribers send 200 × 5 = 1,000 lookups per second to checkout. Checkout's own buyer traffic is 300 requests per second, so its total load becomes 1,300. During the flash sale, 5,000 orders per second produce 25,000 lookups per second, at the moment checkout is busiest.
The callbacks also bring back the dependency that publishing an event was meant to remove. When checkout's order API is slow or down, all five subscribers stop, and work that was moved out of the buyer's request depends on checkout again.
A thin event has one more problem. A callback returns the order as it is at the time of the call, not as it was when the event happened. Suppose a buyer cancels an order two seconds after placing it, and analytics is ten seconds behind. When analytics reads order.placed and calls back, checkout answers "canceled", and analytics cannot tell what the order looked like when it was placed.
Event-Carried State Transfer
The fix is to put the details inside the event. The state of an order is the data that describes it: the buyer, the items, the total, and the address. When an event carries that state, as the second JSON block does, the pattern is called event-carried state transfer. The name describes the mechanism: the state travels inside the event to every subscriber.
A full event describes the order at the moment it was placed. Even when analytics reads the event ten seconds later, it sees the total from the moment the buyer placed the order. A sales report needs that total.
The cost is size. At 200 orders per second, 400-byte events add up to 80 KB per second, about 6.9 GB per day, compared with about 1.7 GB per day for 100-byte thin events. That extra storage costs far less than 1,000 extra calls per second to checkout.
A full event needs four kinds of fields, and the second JSON block has all four:
- The fields subscribers need, copied as they were at that moment, like the items, the total, and the address.
- An event ID, like
evt_5521. Brokers deliver events at least once, so a subscriber may receive the same event twice. The subscriber records the IDs it has processed and skips a repeat, which is the Idempotency idea applied to events. - A version number, like
orderVersion: 1. Events can arrive out of order, so a subscriber that has already stored version 2 of an order ignores a late version 1. - Only designed fields. Each field is chosen for other teams. The event is not a copy of checkout's database row. Internal columns, like a retry counter, stay out of it.
Local Views
Once events carry state, a subscriber can keep its own table, built only from events and holding only the fields it needs. That table is called a local view. Loyalty keeps a table of buyer IDs and point balances. Each time an order.placed event arrives, loyalty adds the order's total to the buyer's balance, so a $40 order adds 40 points.
A local view lets a service answer its own questions without calling anyone. If checkout is down for ten minutes, the loyalty page reads the loyalty table and keeps working.
A local view is also disposable, which means the team can delete it and build it again. The broker stores order.placed events in a log. A log is a list of events that grows only at the end, and it can be read again from any point. In the Publish-Subscribe lesson, the broker kept events for 7 days. The store now keeps order events for 90 days, so teams can rebuild their views.
A new subscriber, or one whose table was damaged, reads the log from the start and applies every event again. This is called a replay. History older than 90 days needs a longer log or a saved copy of the view.
Stale Views and Eventual Consistency
A local view is a copy, and a copy is always slightly behind the original. Until loyalty applies an event, it disagrees with checkout about the buyer's points.
The diagram follows Maya's $40 order. Checkout publishes the event at 0 ms, and loyalty applies it at 300 ms. During those 300 ms, the loyalty page shows 120 points, the balance before the order. After 300 ms, it shows 160 points.
The copies disagree for a time and then agree, and this is called eventual consistency. A view that has not yet received the latest events is a stale view. The delay itself is called lag, and it is usually under one second.
Lag grows when a subscriber receives events faster than it can process them. Suppose loyalty processes 1,000 events per second, and the flash sale sends 5,000 per second for two minutes. After the sale, 4,000 × 120 = 480,000 events are waiting.
Normal traffic of 200 per second continues, so the number of waiting events (the backlog) falls by 800 per second. The backlog takes 600 seconds to clear. For about ten minutes, the loyalty page shows balances that are behind.
A points balance that is ten minutes behind is acceptable. A decision that must be correct right now is different, like whether the last signed edition is in stock. That question goes to the inventory service as a request-response call.
Personal Data in Events
A full event copies data into many places. Maya's email and address now exist in checkout, in the log for 90 days, and in the local views of every subscriber that kept them. Each copy must be protected, and erased when a buyer asks the store to delete their personal data.
The first rule is to carry only the personal fields that subscribers need. Analytics needs the items and the total, and loyalty needs the buyer ID and the total. Neither needs Maya's name or address, and every unneeded copy is another place to protect and erase.
The second rule handles the copies that must exist. Rewriting old events and finding every copy in every view is hard, so the store uses keys instead.
Checkout encrypts each buyer's personal fields with a key that belongs to that buyer alone, stored in a key service. Subscribers that need the fields ask the key service for the key. They store the fields encrypted in their views and decrypt them only when they use them, like when email sends the receipt. When Maya asks the store to delete her data, the store destroys her key. This technique is called crypto-shredding.
The left panel shows the event before deletion. The order ID and the $40 total are stored as plain text, and the email and address are stored encrypted, readable with the key for u_204. The right panel shows the same stored bytes after the key is destroyed. The email and address are now unreadable in the log and in every view, without changing a single copy.
The order ID, the items, and the total stay readable. That matters, because tax and accounting rules often require the store to keep records of money, even after a buyer asks to be deleted. Crypto-shredding removes the personal data and keeps the financial record.
Knowing Who Consumes What
With request-response, every dependency is visible in the code, because one service calls another by name. With events, five teams depend on the exact fields of order.placed, and none of those dependencies appear in checkout's code. Tracking these hidden dependencies is called governance, and it has three parts.
A catalog of events. The store keeps one list of every event type, with its owner, its fields, and its subscribers. Before checkout changes order.placed, its team reads the list and knows which five teams to tell.
Compatible changes only. Adding a field is safe, because subscribers ignore fields they do not know. Removing or renaming a field is not. Suppose checkout renames total to amount. Loyalty reads total, finds nothing, and awards 0 points for every order until someone notices. A change that removes or renames a field is published as a new event version, next to the old one, until every subscriber reads the new version.
A way to follow one order. When an order goes wrong, the cause may be in any of the five subscribers. Each event therefore carries a correlation ID. The ID is created when the buyer taps Place order. It is copied into every event and log line about that order, so one search shows each step. The Distributed Tracing lesson builds this into a full tool.
A tool can also turn every change to checkout's database tables into an event, as the Change Data Capture lesson describes. Those events describe table rows, not orders, so every subscriber then depends on checkout's table layout. A designed event like order.placed lets checkout change its tables without breaking five teams.
When to Use Event-Driven Architecture
This module asks one question about each connection: does the caller need the answer before it can continue? Event-driven architecture fits the connections where the answer is no. Checkout does not need anything back from the five subscribers, so it publishes a fact and continues. The second decision is what the event carries. The table applies both decisions to the store:
| Connection | Needs the answer to continue? | What to use |
|---|---|---|
| Checkout to payment: charge the card | Yes, the order cannot be confirmed without it | Request-response |
| Checkout to inventory: is the last signed edition in stock? | Yes, and the answer must be current | Request-response |
| Order placed, to fulfillment and email | No | Full event, with the address and email encrypted |
| Order placed, to loyalty and analytics | No | Full event with the buyer ID, items, and total |
| A seller uploads a 5 MB product photo | No | Thin event with a link, since most subscribers never need the file |
A thin event fits the last row because the data is large and few subscribers need it. It also fits when subscribers must always read the latest data. For most business facts, like an order, a payment, or a shipment, a full event is the better default. Event-driven architecture also makes a system harder to follow, so a small system with two services may not need it.
Check Yourself
Q1. The store keeps thin order.placed events, and the five subscribers call checkout for the details. During the flash sale, 5,000 orders arrive per second. How many lookups does checkout receive, and what change removes them?
Each order produces one lookup from each of the five subscribers, so checkout receives 5,000 × 5 = 25,000 lookups per second, on top of its buyer traffic. The change is event-carried state transfer: put the items, the total, the buyer ID, and the address inside the event. Each subscriber then reads what it needs from the event, and checkout receives no lookups at all.
</details>Q2. Right after placing a $40 order, Maya opens the loyalty page and sees 120 points instead of 160. A few seconds later, she sees 160. Is this a bug?
<details> <summary>Show answer</summary>No. The loyalty page reads loyalty's local view, which is updated from events and runs a short time behind checkout. This is eventual consistency: the view was stale for a moment and then received the event. The page can tell buyers that points from a recent order may take a moment to appear.
</details>Q3 (incident). A buyer asks the store to delete her data. The team deletes her row from the customer database. A month later, the analytics team loses its view and rebuilds it by replaying 90 days of order.placed events, and her name and address appear in the new view. What happened, and what should change?
Deleting one database row did not touch the copies inside the events. Her name and address were stored in her order.placed events in the log, and the replay copied them into the new view.
The fix has two parts. First, analytics does not need a name or address, so those fields should not reach it at all. Second, the personal fields that events must carry should be encrypted with a key for each buyer, and a deletion request destroys that key. After that, a replay finds only unreadable text, while the order totals stay available for the financial records.
</details>💡 In the interview: Separate the decision into two questions and say both aloud. "Checkout does not need an answer from fulfillment, email, or loyalty, so it publishes
order.placedinstead of calling them. The event carries the order's details, so no subscriber has to call checkout back, and each one keeps its own view. Those views are eventually consistent, so anything that must be current, like stock for the last item, stays a request-response call. Personal fields in the event are encrypted with a key for each user, so a deletion request destroys the key." Expect a follow-up about changing the event later: add fields freely, and publish a new version instead of renaming or removing one.
Summary
| <span style="white-space:nowrap">Problem</span> | A thin event carries only an ID, so every subscriber calls the producer back for the details. With five subscribers, 200 orders per second become 1,000 lookups, and the subscribers depend on checkout again. |
| <span style="white-space:nowrap">Mechanism</span> | Put the state in the event (event-carried state transfer). Each subscriber keeps a local view, built from events and rebuilt by replaying the log. |
| <span style="white-space:nowrap">Costs</span> | Views are briefly stale (eventual consistency). Personal data is copied into many places, so carry only what subscribers need and encrypt it with a key for each buyer (crypto-shredding). Hidden dependencies need an event catalog and compatible changes only. |
| <span style="white-space:nowrap">When to skip</span> | The caller needs the answer before it can continue, or the answer must be current (use request-response). The data is large and few subscribers need it (use a thin event with a link). The system has only two services. |
| <span style="white-space:nowrap">30-second answer</span> | Checkout does not need an answer from its subscribers, so it publishes order.placed. The event carries the order's details, so nobody calls back, and each service keeps its own eventually consistent view. Anything that must be current stays a request-response call, and personal fields are encrypted with a key for each user. |
Flashcards Review
How do the thin and the full order.placed events differ?
Mahmoud Mousa
· 8 days ago
Hey Arslan,
Could you bring back the summary table or anything like it? I'm making notes as I study and found that summary table to be very good. It is the one that had: problem, mechanism, costs, when to skip, 30 seconds answer.
rkrbommanapally
· 2 months ago
The over explanation of the topic is complex, its not simple. LIke the topic "The pattern", its difficult to understand and corelate, i already worked in kafka but this explanation is so complex i feel
Reading Progress
0%
On This Page
What Event-Driven Architecture Means
The Cost of a Thin Event
Event-Carried State Transfer
Local Views
Stale Views and Eventual Consistency
Personal Data in Events
Knowing Who Consumes What
When to Use Event-Driven Architecture
Check Yourself
Summary