Event-driven architecture and event sourcing
Events can tell other services what changed, carry the data with them, or become your database. Know which one you are building, and what each costs.
Updated since you finished it. We changed this lesson after you marked it done. Your progress is kept.
What broke
In 2019, engineer Chris Kiehl wrote up a year of running an event-sourced system in production. He had made the design call, and his team built it from scratch in Java. 3
The pitch had been simple. Every change is an event in a log. Any service can subscribe and react. You get an audit log and time travel for free.
The real system was different. In his view, letting services read each other's raw events was both "extremely coupled" and "excruciatingly opaque". It became hard to tell which services produced or consumed which events. 3
About a month in, a change in focus made some stored events "no longer relevant, at all". The team had to either translate old events on read or rewrite the log. Either way, he writes, they could no longer reproduce exactly how the system looked before the change. 3
He also warns about the next stage. Once the data grows, reads must move to projections. Those lag behind writes, so new items can return 404 and deleted items can stay visible for a while. 3 His advice at the end: ask what core problem event sourcing solves for you. If you cannot answer clearly, a history table or a plain queue may be enough. 3
The idea in simple words
"Event-driven" means at least three different things. Martin Fowler separates them. 1 Kiehl's own closing question points at this mix-up: "Is what you actually want just a plain old queue?" 3
- Event notification. A service sends an event to say "something changed". It does not expect a reply. The receiver calls back if it needs details. 1
- Event-carried state transfer. The event carries the changed data. Receivers keep their own copy, so they never need to call the sender. 1
- Event sourcing. Every change to your own data is stored as an event. The event store is the main source of truth. Current state is whatever you get by replaying the events. 1
The first two are about how services talk. The third is about how one service stores its data. You can use the first two without the third.
The key idea. Events between services are messages. Event sourcing makes events your database. The first is common and useful. The second is a big, hard-to-undo decision for the parts of a system that need full history.
How it works
Events between services
Event notification gives low coupling. The sender does not know who listens. 1 Microsoft adds that you can add new consumers without changing the producer. 5
The cost is that the flow is hidden. Fowler warns that "it can be hard to see such a flow as it's not explicit in any program text". 1 Debugging is harder too, because there is no shared call stack. Put a correlation ID in every event so you can link the steps into one trace. 5
Event-carried state transfer gives more resilience. Receivers keep working when the sender is down, and they need no remote call. The cost is many copies of the data. 1 Those copies are eventually consistent. For a while after an event, different services see different states. 5
The sagas, outbox and CDC lesson shows how to publish these events safely.
Event sourcing: the stream is the truth
In event sourcing, each aggregate (an account, an order) has its own stream. A stream is the ordered list of every event for that one object. 4 You never update or delete an event. To undo a change, you append a new event that reverses it. 4 This is the same rule as a double-entry ledger, applied to any kind of data.
To load an aggregate, you start from an empty state and apply every event in order. 4 Fowler calls the full version a "complete rebuild". You can also stop at a past time to see the state as it was then. 2
Step through one account stream. Use Next and Back, or the ← and → keys.
- The account is a stream of events, numbered 1, 2, 3. To get the balance, you start from zero and apply each event in order. That gives ₹300 at version 3.
- Two requests to withdraw ₹250 arrive at the same time. Writer A and Writer B both load the stream. Both see ₹300 at version 3, so both rules pass.
- Writer A appends a Withdrawn event and says: I expect the stream to be at version 3. It is, so the event is saved as version 4.
- Writer B also says it expects version 3. The stream is now at 4, so the store rejects the append. B reloads, sees ₹50, and refuses the withdrawal.
- Long streams get slow to replay. Save a snapshot of the state at version 4. Next time, load the snapshot and replay only the events after it.
Appending with an expected version
Two requests can load the same stream at the same moment and both pass your rules. Event stores stop this with optimistic concurrency control. They reject an append if the stream changed since it was read. The loser reloads, checks again, and retries. 4
Purpose-built stores support this directly. In KurrentDB you pass the revision you read as the expected stream state. If the stream is not in that state, the append throws an error. 6 In Postgres you can get the same result with a primary key on (stream_id, version). 4
// CREATE TABLE events (stream_id text, version int, type text, data jsonb,
// PRIMARY KEY (stream_id, version));
type Event =
| { type: "Opened" }
| { type: "Deposited"; paise: number }
| { type: "Withdrawn"; paise: number };
type Account = { open: boolean; balance: number; version: number };
function apply(s: Account, e: Event): Account {
switch (e.type) {
case "Opened": return { ...s, open: true };
case "Deposited": return { ...s, balance: s.balance + e.paise };
case "Withdrawn": return { ...s, balance: s.balance - e.paise };
}
}
async function load(db: Db, id: string): Promise<Account> {
const rows = await db.query(
"SELECT version, data FROM events WHERE stream_id = $1 ORDER BY version", [id]);
let s: Account = { open: false, balance: 0, version: 0 };
for (const r of rows) s = { ...apply(s, r.data), version: r.version };
return s;
}
async function append(db: Db, id: string, expected: number, events: Event[]) {
try {
await db.transaction(async (tx) => {
for (const [i, e] of events.entries())
await tx.query("INSERT INTO events VALUES ($1, $2, $3, $4)",
[id, expected + 1 + i, e.type, e]);
});
} catch (err: any) {
if (err.code === "23505") throw new ConflictError(id, expected); // someone wrote first
throw err;
}
}
async function withdraw(db: Db, id: string, paise: number) {
const acc = await load(db, id);
if (!acc.open) throw new Error("account not open");
if (acc.balance < paise) throw new Error("insufficient funds");
await append(db, id, acc.version, [{ type: "Withdrawn", paise }]);
}If another writer already saved the next version, the insert breaks the primary key. Postgres reports that as error code 23505, unique_violation. 8 The caller catches ConflictError, loads again, and retries. Always pass the version you loaded. This check only proves that the next version is free.
Snapshots
Long streams are slow to replay. A snapshot is a saved copy of the state at one version, taken every N events. To load, you read the latest snapshot and replay only the events after it. 4 Snapshots are only a speed-up. The stream stays the truth, and you can rebuild any snapshot from it. 4
Replay and the outside world
Replaying must not repeat side effects. If a replay calls the payment provider or sends emails again, real people are affected. Fowler suggests a gateway in front of each outside system that knows when it is in replay mode and skips the call. 2
Versioning old events
Events live forever, but your code changes. Microsoft lists four strategies, which you can use alone or together. 4
- Tolerant deserialization. Ignore unknown fields and default missing ones. This handles fields you add.
- Event versioning. A version number in each event, so the reader picks the right logic.
- Upcasting. Functions convert old event shapes to the current one when they are read. Stored events stay unchanged.
- In-place migration. Rewrite stored events to the new shape. Use this only as a last resort, because it breaks the audit trail.
The general rules for changing data formats are in schema evolution and encoding. Kiehl's story shows the limit. Upcasting keeps your code working, but a change in what an event means can still blur the past. 3
Deleting personal data
Laws like the "right to be forgotten" clash with a store that never deletes. Microsoft's first advice is to keep personal data outside the event store and refer to it by ID. 4 If you cannot, use crypto-shredding. You encrypt each person's data with their own key. To forget them, you delete the key. 4 7 It adds encryption work on every read and write, and needs careful key management. 4 Verraes notes that it only helps if consumers such as projections also keep the data encrypted. It does not cover values that consumers computed from the data. 7
Verraes also asks whether this counts as deletion under GDPR. An update to his post quotes a reader whose lawyer said it does not. That reader prefers keeping personal data in a separate store you can delete from. 7
Read models
Replaying a stream on every query is slow, so you build read models (projections) that are updated from the events. They lag behind writes. 4 The next lesson, CQRS and read models, covers them.
Trade-offs
| Option | Full history? | Main cost | Use it when |
|---|---|---|---|
| CRUD + history table | Partial. You log what you choose. | Low. | Most services, including admin screens and settings. |
| Event notification | No | Hidden flows, and callbacks to the sender. 1 | Other services need to react, but can fetch details. |
| Event-carried state transfer | No | Many copies of data, eventually consistent. 1 5 | Receivers must keep working when the sender is down. |
| Event sourcing | Yes Every change, in order. | Versioning, snapshots, replay safety, projections, and new skills for the team. 4 | Ledgers, orders and other areas where history and audit are core business needs. |
Microsoft's summary: for most systems, and most parts of a system, plain data storage is enough. Its poor fits include simple CRUD, short-lived prototypes, systems that need real-time consistent views, mostly static data, and teams new to event-driven design. 4 Apply event sourcing to the few parts that need it, not to the whole system. 4
At work: how a senior uses this
- When someone says "event-driven", ask: "Notification, state transfer, or event sourcing?" Then argue about one thing at a time.
- Before you event-source anything, write down the core problem it solves. If the answer is "audit", ask whether a history table is enough. 3
- Name events for business intent, like
SeatsReserved, not "remaining seats changed to 42". 4 - Do not let other services read your raw stored events. Publish separate integration events as your public contract. Microsoft notes that stored events are often too low-level for this. 4
- Always append with an expected version. Test what happens when two writers race.
- Plan event versioning and personal data on day one. Both are painful to add later.
- Put a correlation ID in every event, and check that your tracing follows it.
With AI
What to ask the agent
"Here is our event-sourced Account aggregate. Write a test where two writers load version 3 and both append. Assert that exactly one succeeds and the other gets a conflict error."
"List every event type in this codebase. For each one, say whether it is a notification, carries state, or is a stored domain event. Mark any stored event that another service reads directly."
"We renamed amount to amount_paise in the Deposited event. Write an upcaster for old events, and a test that replays a stream with both versions."
What to check yourself
- The append really checks the expected version. An agent may write a plain insert with no unique key, which quietly allows lost updates.
- Replays and projection rebuilds do not call outside systems or send messages.
- No migration edits stored events in place. Old shapes are handled by upcasters.
- Personal data is either outside the store or encrypted with a per-person key.
- Event handlers are idempotent, since delivery is usually at-least-once. 4
Check yourself
Your progress is saved only in this browser. Export it to keep it safe.
You have finished 5 lessons. Your progress lives only in this browser. Export a copy so you don’t lose it.
Go deeper
Show 8 sources and related lessons
- Martin Fowler, “What do you mean by “Event-Driven”?”, martinfowler.com (7 February 2017) (opens in a new tab)
The four patterns people mean by "event-driven", with the benefits and costs of each. - Martin Fowler, “Event Sourcing”, martinfowler.com (12 December 2005) (opens in a new tab)
The original write-up. Complete rebuild, temporal query, snapshots, and how to stop replays from calling outside systems. - Chris Kiehl, “Don't Let the Internet Dupe You, Event Sourcing is Hard”, Blogomatano (3 February 2019) (opens in a new tab)
A first-hand account of a year running an event-sourced system in production, and what hurt. The author is named on the site's About page. - Microsoft Learn, Azure Architecture Center: “Event Sourcing Pattern” (opens in a new tab)
Snapshots, optimistic concurrency, versioning strategies including upcasting, personal data, and when not to use the pattern. - Microsoft Learn, Azure Architecture Center: “Event-Driven Architecture Style” (opens in a new tab)
Benefits and challenges of event-driven systems, including eventual consistency and tracing across consumers. - Kurrent documentation (Node.js client): “Appending events” (opens in a new tab)
How a purpose-built event store checks the expected stream revision on each append. - Mathias Verraes, “Eventsourcing Patterns: Crypto-Shredding” (13 May 2019) (opens in a new tab)
One key per customer, delete the key to make the data unreadable, and the caveats. - PostgreSQL documentation: “Appendix A. PostgreSQL Error Codes” (opens in a new tab)
Error code 23505 is unique_violation, which the code example uses to detect a conflict.
Case studies: LMAX: LMAX: 6 million orders a second on one thread
Related: Queues vs logs and delivery guarantees · Sagas, outbox and CDC · Domain-driven design · Schema evolution and encoding · Money and double-entry ledgers · CQRS and read models
Before this: queues vs logs. Related: sagas, outbox and CDC, domain-driven design for aggregates and domain events, schema evolution and encoding, and money and double-entry ledgers. Next: CQRS and read models.