Library
11 min read

Event sourcing, CDC and the log

A support ticket arrives: "My wallet balance is ₹400 less than it should be." The engineer opens the database. The wallets row says balance = 1150. That is all it says. It does not know how it got there, what it was yesterday, or whether a refund was applied twice. The one thing support needs, the history, was overwritten one UPDATE at a time.

An accountant would never keep books this way. A ledger only ever has entries added to it, and the balance is what you get by adding them up. This chapter is about building software the same way, and about getting that history out of databases that were not built like that.

Your answer

A wallets table stores one balance per user and updates it in place. Name three questions support, finance or a fraud team might ask that this table can never answer. What would you store instead?

The log underneath everything#

You have already met the same structure four times on this site. A database writes every change to its write ahead log before touching its tables. Raft keeps replicas in step by agreeing on a log. Replicas copy the primary by replaying its log. A Kafka topic is a log you can read.

In each case the log is the truth and the tables are a convenience built from it. Jay Kreps, one of Kafka's creators, made this argument in a 2013 essay, "The Log", and it changes how you see data: a table is just the latest value of every key, which is a cache of the log.