CQRS and event sourcing: storing what happened and reading it many ways

Event sourcing stores every change as an event and computes state by replaying them. CQRS keeps separate models for writing and reading, so projections can turn those events into tables shaped for queries. This page builds both with Spring's JdbcTemplate and H2, then runs the problems teams meet in production: concurrent appends, gaps in event positions, stale reads, long streams and changing event schemas.

Contents

Two separate ideas: CQRS and event sourcing

CQRS and event sourcing are often mentioned together, but they solve different problems and each can be used alone.

  • CQRS (Command Query Responsibility Segregation): the code that changes data and the code that reads it use different models. Commands such as "withdraw 40" go to a write model that enforces the business rules. Queries go to read models shaped for the screens and reports that use them, often in separate tables or a separate database. The name comes from Greg Young, building on Bertrand Meyer's command-query separation.
  • Event sourcing: the system of record is the list of events that happened, not the current state. An account is stored as "opened, deposited 100, withdrew 30", and its balance is computed by replaying those events. Events are only ever appended, never updated or deleted.

They fit together because an event store is a poor place to run queries: finding all accounts with a negative balance would mean replaying every account. With CQRS, projections read the event stream and keep query tables up to date, and the event store only has to load one aggregate's events by id.

Four ways to combine the two
DesignWrite side storesReads come fromBest for
Plain CRUDCurrent state in tablesThe same tablesMost applications
CQRS aloneCurrent state in tablesSeparate read tables, a search index or a cacheReads and writes with very different shapes or load
Event sourcing aloneEventsReplaying the aggregateA few aggregates where the full history is the product
CQRS with event sourcingEventsProjections built from the eventsAudit-heavy domains: ledgers, orders, bookings

Both add real cost: more moving parts, read models that lag behind writes, and events that must stay readable for years. The programs on this page show the mechanisms with Spring's JdbcTemplate and H2. A production system would use PostgreSQL or a dedicated event store, and would often publish events to Kafka for projections in other services.

An event store on one table

An event store needs three operations: append events to a stream, load a stream in order, and read all events in the order they were stored. One table with two keys provides them. The account stream here gets three events, then two writers try to append at the same time:

Java
import java.util.List;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

public class EventStoreBasics {

    record StoredEvent(String streamId, int version, String type, int amount) {
    }

    /** An append-only event store on one table. */
    static class EventStore {
        private final JdbcTemplate jdbc;

        EventStore(JdbcTemplate jdbc) {
            this.jdbc = jdbc;
            jdbc.execute("""
                    CREATE TABLE events (
                        position BIGINT AUTO_INCREMENT PRIMARY KEY,
                        stream_id VARCHAR(40) NOT NULL,
                        version INT NOT NULL,
                        type VARCHAR(40) NOT NULL,
                        amount INT NOT NULL,
                        UNIQUE (stream_id, version))""");
        }

        /** Appends after expectedVersion; fails if another writer got there first. */
        void append(String streamId, int expectedVersion, String type, int amount) {
            jdbc.update("INSERT INTO events (stream_id, version, type, amount)"
                    + " VALUES (?, ?, ?, ?)", streamId, expectedVersion + 1, type, amount);
        }

        List<StoredEvent> load(String streamId) {
            return jdbc.query("SELECT * FROM events WHERE stream_id = ? ORDER BY version",
                    (rs, n) -> new StoredEvent(rs.getString("stream_id"), rs.getInt("version"),
                            rs.getString("type"), rs.getInt("amount")), streamId);
        }
    }

    static int balance(List<StoredEvent> events) {
        int balance = 0;
        for (StoredEvent e : events) {
            balance += e.type().equals("MoneyDeposited") ? e.amount() : -e.amount();
        }
        return balance;
    }

    public static void main(String[] args) {
        JdbcTemplate jdbc = new JdbcTemplate(
                new DriverManagerDataSource("jdbc:h2:mem:store;DB_CLOSE_DELAY=-1"));
        EventStore store = new EventStore(jdbc);
        store.append("account-1", 0, "MoneyDeposited", 100);
        store.append("account-1", 1, "MoneyWithdrawn", 30);
        store.append("account-2", 0, "MoneyDeposited", 500);
        store.append("account-1", 2, "MoneyDeposited", 45);

        List<StoredEvent> history = store.load("account-1");
        history.forEach(e -> System.out.println("  v" + e.version() + " " + e.type()
                + " " + e.amount()));
        System.out.println("account-1 balance, replayed: " + balance(history));
        for (int v = 1; v <= history.size(); v++) {
            System.out.println("  balance after version " + v + ": "
                    + balance(history.subList(0, v)));
        }

        System.out.println("Two writers both loaded account-1 at version 3:");
        store.append("account-1", 3, "MoneyWithdrawn", 100);
        System.out.println("  writer A appended version 4");
        try {
            store.append("account-1", 3, "MoneyWithdrawn", 100);
        } catch (DuplicateKeyException e) {
            System.out.println("  writer B rejected: version 4 already exists");
        }
        System.out.println("account-1 balance: " + balance(store.load("account-1")));
        System.out.println("all events in order of position:");
        jdbc.query("SELECT position, stream_id, version, type FROM events ORDER BY position",
                rs -> {
                    System.out.println("  " + rs.getLong(1) + " " + rs.getString(2) + " v"
                            + rs.getInt(3) + " " + rs.getString(4));
                });
    }
}
Output
v1 MoneyDeposited 100
  v2 MoneyWithdrawn 30
  v3 MoneyDeposited 45
account-1 balance, replayed: 115
  balance after version 1: 100
  balance after version 2: 70
  balance after version 3: 115
Two writers both loaded account-1 at version 3:
  writer A appended version 4
  writer B rejected: version 4 already exists
account-1 balance: 15
all events in order of position:
  1 account-1 v1 MoneyDeposited
  2 account-1 v2 MoneyWithdrawn
  3 account-2 v1 MoneyDeposited
  4 account-1 v3 MoneyDeposited
  5 account-1 v4 MoneyWithdrawn
  • Replaying account-1's three events gave the balance 115: 100 in, 30 out, 45 in. No balance column exists anywhere.
  • Replaying a prefix of the stream gives the state at any earlier point: 100 after version 1, 70 after version 2. A CRUD table that keeps only the current balance cannot answer "what was the balance last Tuesday".
  • Writers A and B both loaded account-1 at version 3 and both appended version 4. The UNIQUE (stream_id, version) constraint let A's insert through and rejected B's, so B must reload and decide again. This is optimistic concurrency, and it is what stops two withdrawals from both passing a balance check.
  • The position column numbers events across all streams, 1 to 5, in insertion order. Projections use it to read "everything after position N".

The version check is the one feature an event store cannot do without. Kafka, for example, has no way to say "append only if this key is still at offset N", which is why Kafka is usually used to distribute events rather than as the event store itself.

Commands, events and aggregates

The write side receives commands, which may be rejected, and produces events, which are facts and cannot be. An aggregate turns one into the other: it rebuilds its state from past events, checks the command against that state, and returns new events. This account has an overdraft limit of 50 and can be frozen:

Java
import java.util.ArrayList;
import java.util.List;

public class AccountAggregate {

    sealed interface Event permits Opened, Deposited, Withdrawn, Frozen {
    }

    record Opened(String owner, int overdraftLimit) implements Event {
    }

    record Deposited(int amount) implements Event {
    }

    record Withdrawn(int amount) implements Event {
    }

    record Frozen(String reason) implements Event {
    }

    sealed interface Command permits Deposit, Withdraw, Freeze {
    }

    record Deposit(int amount) implements Command {
    }

    record Withdraw(int amount) implements Command {
    }

    record Freeze(String reason) implements Command {
    }

    /** State rebuilt from events. It holds only what decisions need. */
    record Account(int balance, int overdraftLimit, boolean frozen, int version) {
        static final Account EMPTY = new Account(0, 0, false, 0);

        Account apply(Event event) {
            return switch (event) {
                case Opened o -> new Account(0, o.overdraftLimit(), false, version + 1);
                case Deposited d -> new Account(balance + d.amount(), overdraftLimit, frozen,
                        version + 1);
                case Withdrawn w -> new Account(balance - w.amount(), overdraftLimit, frozen,
                        version + 1);
                case Frozen f -> new Account(balance, overdraftLimit, true, version + 1);
            };
        }

        /** Checks a command against the current state and returns the new events. */
        List<Event> decide(Command command) {
            if (frozen) {
                throw new IllegalStateException("account is frozen");
            }
            return switch (command) {
                case Deposit d -> List.of(new Deposited(d.amount()));
                case Withdraw w -> {
                    if (balance - w.amount() < -overdraftLimit) {
                        throw new IllegalStateException("withdrawal of " + w.amount()
                                + " exceeds the overdraft limit");
                    }
                    yield List.of(new Withdrawn(w.amount()));
                }
                case Freeze f -> List.of(new Frozen(f.reason()));
            };
        }
    }

    static Account replay(List<Event> events) {
        Account account = Account.EMPTY;
        for (Event e : events) {
            account = account.apply(e);
        }
        return account;
    }

    public static void main(String[] args) {
        List<Event> stream = new ArrayList<>(List.of(new Opened("ada", 50)));
        List<Command> commands = List.of(new Deposit(100), new Withdraw(120), new Withdraw(40),
                new Freeze("suspected fraud"), new Deposit(10));
        for (Command command : commands) {
            Account current = replay(stream);
            try {
                List<Event> produced = current.decide(command);
                stream.addAll(produced);
                System.out.printf("%-31s -> %s%n", command, produced);
            } catch (IllegalStateException e) {
                System.out.printf("%-31s -> rejected: %s%n", command, e.getMessage());
            }
        }
        System.out.println("stream: " + stream);
        System.out.println("state : " + replay(stream));
    }
}
Output
Deposit[amount=100]             -> [Deposited[amount=100]]
Withdraw[amount=120]            -> [Withdrawn[amount=120]]
Withdraw[amount=40]             -> rejected: withdrawal of 40 exceeds the overdraft limit
Freeze[reason=suspected fraud]  -> [Frozen[reason=suspected fraud]]
Deposit[amount=10]              -> rejected: account is frozen
stream: [Opened[owner=ada, overdraftLimit=50], Deposited[amount=100], Withdrawn[amount=120], Frozen[reason=suspected fraud]]
state : Account[balance=-20, overdraftLimit=50, frozen=true, version=4]
  • Deposit(100) and Withdraw(120) were accepted, leaving a balance of -20, inside the overdraft limit.
  • Withdraw(40) would have taken the balance to -60, past the limit of 50, so decide threw and no event was stored. The rejected command leaves no trace in the stream; log it separately if you need it.
  • After Frozen, every command was rejected, including a deposit.
  • The final stream holds four events and the state is rebuilt from them: balance -20, frozen, version 4. The owner from Opened is in the event but not in the state, because no decision needs it.

apply must never fail and never check rules: it replays facts that already happened, possibly years ago under different rules. decide checks the rules. Keeping the two apart is what lets old events replay cleanly after the rules change. The sealed interfaces and the pattern switch make the compiler reject an event type that apply forgets to handle.

Projections: read models built from events

A projection reads events in position order and updates a query table. It stores a checkpoint, the last position it processed, in the same transaction as its updates, so a crash never processes an event twice or skips one. The program runs a balance projection three times as events arrive, then adds a second read model later:

Java
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.support.TransactionTemplate;

public class Projections {

    static JdbcTemplate jdbc;
    static TransactionTemplate transaction;

    static void append(String account, String type, int amount) {
        Integer version = jdbc.queryForObject(
                "SELECT COALESCE(MAX(version), 0) FROM events WHERE stream_id = ?",
                Integer.class, account);
        jdbc.update("INSERT INTO events (stream_id, version, type, amount) VALUES (?, ?, ?, ?)",
                account, version + 1, type, amount);
    }

    interface Handler {
        void apply(Map<String, Object> event);
    }

    /** Applies new events to a read model and moves its checkpoint, in one transaction. */
    static int project(String projection, Handler handler) {
        Integer count = transaction.execute(status -> {
            long checkpoint = jdbc.queryForObject("SELECT position FROM checkpoints"
                    + " WHERE projection = ?", Long.class, projection);
            List<Map<String, Object>> events = jdbc.queryForList(
                    "SELECT * FROM events WHERE position > ? ORDER BY position", checkpoint);
            for (Map<String, Object> event : events) {
                handler.apply(event);
                jdbc.update("UPDATE checkpoints SET position = ? WHERE projection = ?",
                        event.get("POSITION"), projection);
            }
            return events.size();
        });
        return count == null ? 0 : count;
    }

    static void balances(Map<String, Object> e) {
        int signed = e.get("TYPE").equals("MoneyDeposited")
                ? (Integer) e.get("AMOUNT") : -(Integer) e.get("AMOUNT");
        jdbc.update("MERGE INTO account_balances b USING (VALUES (?, ?)) s(id, delta)"
                + " ON b.id = s.id"
                + " WHEN MATCHED THEN UPDATE SET balance = b.balance + s.delta,"
                + " transactions = b.transactions + 1"
                + " WHEN NOT MATCHED THEN INSERT VALUES (s.id, s.delta, 1)",
                e.get("STREAM_ID"), signed);
    }

    static void largeWithdrawals(Map<String, Object> e) {
        if (e.get("TYPE").equals("MoneyWithdrawn") && (Integer) e.get("AMOUNT") >= 200) {
            jdbc.update("INSERT INTO large_withdrawals VALUES (?, ?)",
                    e.get("STREAM_ID"), e.get("AMOUNT"));
        }
    }

    public static void main(String[] args) {
        DataSource ds = new DriverManagerDataSource("jdbc:h2:mem:proj;DB_CLOSE_DELAY=-1");
        jdbc = new JdbcTemplate(ds);
        transaction = new TransactionTemplate(new DataSourceTransactionManager(ds));
        jdbc.execute("CREATE TABLE events (position BIGINT AUTO_INCREMENT PRIMARY KEY,"
                + " stream_id VARCHAR(40), version INT, type VARCHAR(40), amount INT,"
                + " UNIQUE (stream_id, version))");
        jdbc.execute("CREATE TABLE checkpoints (projection VARCHAR(40) PRIMARY KEY,"
                + " position BIGINT)");
        jdbc.execute("CREATE TABLE account_balances (id VARCHAR(40) PRIMARY KEY,"
                + " balance INT, transactions INT)");
        jdbc.update("INSERT INTO checkpoints VALUES ('balances', 0)");

        append("acc-1", "MoneyDeposited", 1000);
        append("acc-2", "MoneyDeposited", 300);
        append("acc-1", "MoneyWithdrawn", 250);
        System.out.println("balances projector, run 1: " + project("balances",
                Projections::balances) + " events");
        append("acc-2", "MoneyWithdrawn", 50);
        append("acc-1", "MoneyWithdrawn", 400);
        System.out.println("balances projector, run 2: " + project("balances",
                Projections::balances) + " events");
        System.out.println("balances projector, run 3: " + project("balances",
                Projections::balances) + " events");
        System.out.println("account_balances: "
                + jdbc.queryForList("SELECT * FROM account_balances ORDER BY id"));

        System.out.println("A new read model, built from the existing history:");
        jdbc.execute("CREATE TABLE large_withdrawals (id VARCHAR(40), amount INT)");
        jdbc.update("INSERT INTO checkpoints VALUES ('large', 0)");
        System.out.println("large projector, first run: " + project("large",
                Projections::largeWithdrawals) + " events");
        System.out.println("large_withdrawals: "
                + jdbc.queryForList("SELECT * FROM large_withdrawals"));
        System.out.println("checkpoints: "
                + jdbc.queryForList("SELECT * FROM checkpoints ORDER BY projection"));
    }
}
Output
balances projector, run 1: 3 events
balances projector, run 2: 2 events
balances projector, run 3: 0 events
account_balances: [{ID=acc-1, BALANCE=350, TRANSACTIONS=3}, {ID=acc-2, BALANCE=250, TRANSACTIONS=2}]
A new read model, built from the existing history:
large projector, first run: 5 events
large_withdrawals: [{ID=acc-1, AMOUNT=250}, {ID=acc-1, AMOUNT=400}]
checkpoints: [{PROJECTION=balances, POSITION=5}, {PROJECTION=large, POSITION=5}]
  • Run 1 processed the 3 events that existed, run 2 only the 2 added since, and run 3 found nothing new. The checkpoint, now 5, is what made each run continue where the last one stopped.
  • account_balances shows acc-1 at 350 after 3 transactions and acc-2 at 250 after 2. A query reads this table directly, without touching the events.
  • The large_withdrawals read model did not exist when the events were written. Starting its checkpoint at 0 built it from the whole history: both withdrawals of 200 or more, 250 and 400, are in it.

That last point is the strongest argument for event sourcing: a new question about the past can be answered by writing a new projection, because nothing was thrown away. A broken projection is fixed the same way: drop its table, reset its checkpoint and replay. In larger systems, projections run in other services, fed by a relay that publishes the events to Kafka, as on the outbox page.

A trap: positions committed out of order

Reading "all events after my checkpoint" assumes that positions become visible in order. They do not. The database hands out the position when the row is inserted, but other readers see it only when its transaction commits. A slow transaction can commit position 2 after a fast one has committed position 3:

Java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

public class PositionGap {

    static final String URL = "jdbc:h2:mem:gap;DB_CLOSE_DELAY=-1";

    static void insert(Connection c, String stream) throws SQLException {
        try (var st = c.prepareStatement("INSERT INTO events (stream_id) VALUES (?)")) {
            st.setString(1, stream);
            st.executeUpdate();
        }
    }

    public static void main(String[] args) throws SQLException {
        JdbcTemplate jdbc = new JdbcTemplate(new DriverManagerDataSource(URL));
        jdbc.execute("CREATE TABLE events (position BIGINT AUTO_INCREMENT PRIMARY KEY,"
                + " stream_id VARCHAR(40))");
        jdbc.update("INSERT INTO events (stream_id) VALUES ('acc-1')");

        try (Connection slow = DriverManager.getConnection(URL);
                Connection fast = DriverManager.getConnection(URL)) {
            slow.setAutoCommit(false);
            fast.setAutoCommit(false);
            insert(slow, "acc-2");
            insert(fast, "acc-3");
            fast.commit();
            System.out.println("slow transaction holds position 2 (not committed),"
                    + " fast one committed position 3");

            long checkpoint = 0;
            List<Long> seen = jdbc.queryForList(
                    "SELECT position FROM events WHERE position > ? ORDER BY position",
                    Long.class, checkpoint);
            checkpoint = seen.get(seen.size() - 1);
            System.out.println("projector reads " + seen + ", checkpoint = " + checkpoint);

            slow.commit();
            System.out.println("slow transaction commits position 2");
            List<Long> next = jdbc.queryForList(
                    "SELECT position FROM events WHERE position > ? ORDER BY position",
                    Long.class, checkpoint);
            System.out.println("projector reads " + next + ": position 2 is never projected");
            System.out.println("events table: " + jdbc.queryForList(
                    "SELECT position FROM events ORDER BY position", Long.class));
        }
    }
}
Output
slow transaction holds position 2 (not committed), fast one committed position 3
projector reads [1, 3], checkpoint = 3
slow transaction commits position 2
projector reads []: position 2 is never projected
events table: [1, 2, 3]
  • While the slow transaction held position 2 uncommitted, the projector saw [1, 3] and moved its checkpoint to 3.
  • When position 2 committed, the next read asked for positions above 3 and got nothing. The event is in the table, but this projection will never see it.

The bug appears only under concurrent writes, so tests on one thread never find it. The common fixes:

  • Serialize appends: take a lock, such as a row lock on a single sequence row, so that positions are assigned and committed one transaction at a time. That is simple, but it limits write throughput.
  • Treat gaps as "not yet": when the projector sees a gap, it stops before it and waits a few seconds before skipping it, because the gap may be a rolled-back transaction that will never fill.
  • Use the database's own ordering: PostgreSQL exposes transaction ids and snapshots that let a reader stop below the oldest transaction still running, and change data capture reads the log in commit order.

Reading your own writes

Projections run after the command has committed, so for a moment the read model is behind. A user who renames a product and is sent straight to the product page may see the old name. The projector here runs every 500 ms:

Java
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.transaction.support.TransactionTemplate;

public class ReadLag {

    static JdbcTemplate jdbc;
    static TransactionTemplate transaction;

    /** Write side: appends the event and returns its position. */
    static long renameProduct(String id, String name) {
        KeyHolder key = new GeneratedKeyHolder();
        jdbc.update(c -> {
            var st = c.prepareStatement("INSERT INTO events (stream_id, name) VALUES (?, ?)",
                    new String[] {"POSITION"});
            st.setString(1, id);
            st.setString(2, name);
            return st;
        }, key);
        return key.getKey().longValue();
    }

    /** Read side: updated by a projector that runs every 500 ms. */
    static void project() {
        transaction.executeWithoutResult(status -> {
            long checkpoint = jdbc.queryForObject("SELECT position FROM checkpoint", Long.class);
            jdbc.query("SELECT * FROM events WHERE position > ? ORDER BY position", rs -> {
                jdbc.update("UPDATE products SET name = ? WHERE id = ?",
                        rs.getString("name"), rs.getString("stream_id"));
                jdbc.update("UPDATE checkpoint SET position = ?", rs.getLong("position"));
            }, checkpoint);
        });
    }

    static String query(String id) {
        return jdbc.queryForObject("SELECT name FROM products WHERE id = ?", String.class, id);
    }

    /** Waits until the read model has processed the given position, or gives up. */
    static String queryAfter(String id, long position) throws InterruptedException {
        for (int i = 0; i < 50; i++) {
            long done = jdbc.queryForObject("SELECT position FROM checkpoint", Long.class);
            if (done >= position) {
                return query(id);
            }
            Thread.sleep(50);
        }
        throw new IllegalStateException("read model is behind");
    }

    public static void main(String[] args) throws InterruptedException {
        DataSource ds = new DriverManagerDataSource("jdbc:h2:mem:lag;DB_CLOSE_DELAY=-1");
        jdbc = new JdbcTemplate(ds);
        transaction = new TransactionTemplate(new DataSourceTransactionManager(ds));
        jdbc.execute("CREATE TABLE events (position BIGINT AUTO_INCREMENT PRIMARY KEY,"
                + " stream_id VARCHAR(20), name VARCHAR(40))");
        jdbc.execute("CREATE TABLE products (id VARCHAR(20) PRIMARY KEY, name VARCHAR(40))");
        jdbc.execute("CREATE TABLE checkpoint (position BIGINT)");
        jdbc.update("INSERT INTO products VALUES ('p-1', 'Desk lamp')");
        jdbc.update("INSERT INTO checkpoint VALUES (0)");

        ScheduledExecutorService projector = Executors.newSingleThreadScheduledExecutor();
        projector.scheduleWithFixedDelay(ReadLag::project, 500, 500, TimeUnit.MILLISECONDS);

        long position = renameProduct("p-1", "LED desk lamp");
        System.out.println("command: renamed p-1, event at position " + position);
        System.out.println("query right after the command      : " + query("p-1"));
        System.out.println("query that waits for position " + position + "    : "
                + queryAfter("p-1", position));
        projector.shutdown();
    }
}
Output
command: renamed p-1, event at position 1
query right after the command      : Desk lamp
query that waits for position 1    : LED desk lamp
  • The command stored its event at position 1 and returned.
  • A query straight afterwards still returned Desk lamp, because the projector had not run yet.
  • The second query passed the position the command returned and waited until the read model's checkpoint reached it, then returned LED desk lamp.

Waiting for a position, sometimes sent as a version or an ETag header, gives a user consistent reads of their own changes without slowing everyone else down. Other options are to update the read model in the same transaction as the events, which works only when both are in one database, or to have the user interface show the change it just made without reading it back. Whichever you choose, decide it per screen. A dashboard can be a second behind; a confirmation page cannot.

Snapshots for long streams

Loading an aggregate means replaying its whole stream, which is fast for 50 events and slow for 100,000. A snapshot stores the state at some version, so loading starts there and replays only the events after it. This account has 100,002 events and a snapshot every 1,000:

Java
import java.util.List;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

public class Snapshots {

    static final int EVENTS = 100000;
    static final int SNAPSHOT_EVERY = 1000;

    record State(long balance, int version) {
    }

    static JdbcTemplate jdbc;

    static State replayAll() {
        long[] balance = {0};
        int[] version = {0};
        jdbc.query("SELECT version, amount FROM events WHERE stream_id = 'acc-1'"
                + " ORDER BY version", rs -> {
                    balance[0] += rs.getInt(2);
                    version[0] = rs.getInt(1);
                });
        return new State(balance[0], version[0]);
    }

    static State fromSnapshot() {
        List<State> snapshot = jdbc.query("SELECT balance, version FROM snapshots"
                + " WHERE stream_id = 'acc-1' ORDER BY version DESC FETCH FIRST 1 ROW ONLY",
                (rs, n) -> new State(rs.getLong(1), rs.getInt(2)));
        long[] balance = {snapshot.get(0).balance()};
        int[] version = {snapshot.get(0).version()};
        jdbc.query("SELECT version, amount FROM events WHERE stream_id = 'acc-1'"
                + " AND version > ? ORDER BY version", rs -> {
                    balance[0] += rs.getInt(2);
                    version[0] = rs.getInt(1);
                }, version[0]);
        return new State(balance[0], version[0]);
    }

    interface Load {
        State run();
    }

    static long bestOfThreeMicros(Load load) {
        long best = Long.MAX_VALUE;
        for (int i = 0; i < 3; i++) {
            long start = System.nanoTime();
            load.run();
            best = Math.min(best, (System.nanoTime() - start) / 1000);
        }
        return best;
    }

    public static void main(String[] args) {
        jdbc = new JdbcTemplate(new DriverManagerDataSource("jdbc:h2:mem:snap;DB_CLOSE_DELAY=-1"));
        jdbc.execute("CREATE TABLE events (stream_id VARCHAR(20), version INT, amount INT,"
                + " PRIMARY KEY (stream_id, version))");
        jdbc.execute("CREATE TABLE snapshots (stream_id VARCHAR(20), version INT,"
                + " balance BIGINT, PRIMARY KEY (stream_id, version))");
        long balance = 0;
        for (int v = 1; v <= EVENTS; v++) {
            int amount = v % 3 == 0 ? -7 : 5;
            jdbc.update("INSERT INTO events VALUES ('acc-1', ?, ?)", v, amount);
            balance += amount;
            if (v % SNAPSHOT_EVERY == 0) {
                jdbc.update("INSERT INTO snapshots VALUES ('acc-1', ?, ?)", v, balance);
            }
        }
        jdbc.update("INSERT INTO events VALUES ('acc-1', ?, 5)", EVENTS + 1);
        jdbc.update("INSERT INTO events VALUES ('acc-1', ?, 5)", EVENTS + 2);

        System.out.println("replay all events    : " + replayAll());
        System.out.println("snapshot + new events: " + fromSnapshot());
        for (int warmup = 0; warmup < 5; warmup++) {
            replayAll();
            fromSnapshot();
        }
        long all = bestOfThreeMicros(Snapshots::replayAll);
        long snap = bestOfThreeMicros(Snapshots::fromSnapshot);
        System.out.println("rough comparison, best of 3:");
        System.out.printf("  replay %d events: %.1f ms%n", EVENTS + 2, all / 1000.0);
        System.out.printf("  snapshot + 2 events : %.1f ms%n", snap / 1000.0);
    }
}
Output
replay all events    : State[balance=100014, version=100002]
snapshot + new events: State[balance=100014, version=100002]
rough comparison, best of 3:
  replay 100002 events: 308.2 ms
  snapshot + 2 events : 0.4 ms
  • Both loads produced the same state, balance 100014 at version 100002, which is the check every snapshot implementation needs.
  • Replaying everything read all 100,002 rows. The snapshot load read one snapshot row and 2 events.
  • This is a rough comparison, best of 3 timings per run, on a shared 2-core Intel Xeon at 2.10 GHz with H2 in memory. Across seven runs the full replay took between about 35 and 310 ms and the snapshot load between 0.3 and 1.2 ms, so the snapshot load was always at least 30 times faster. The gap grows with the length of the stream.

Snapshots are a cache, not a source of truth: they can be deleted and rebuilt from the events at any time, and they must be discarded when the state's shape changes. Most aggregates never need one. A stream that grows to many thousands of events is often a sign of a modelling problem, such as one aggregate for something that should be a series of them, like one account per year.

Changing events that are already stored

Events are kept forever, but the code that reads them changes. Rewriting stored events breaks the promise of an immutable history, so the usual approach is upcasting: each stored event keeps its schema version, and the reader converts old versions to the current one as it loads them. Here version 1 of MoneyDeposited had no currency:

Java
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class Upcasting {

    /** Version 2 of the event: version 1 had no currency and stored cents as "amount". */
    record MoneyDeposited(long minorUnits, String currency) {
    }

    /** Converts any stored version to the current one, as the event is read. */
    static MoneyDeposited upcast(Map<String, String> stored) {
        return switch (stored.get("schema")) {
            case "1" -> new MoneyDeposited(Long.parseLong(stored.get("amount")), "EUR");
            case "2" -> new MoneyDeposited(Long.parseLong(stored.get("minorUnits")),
                    stored.get("currency"));
            default -> throw new IllegalArgumentException("unknown schema " + stored);
        };
    }

    public static void main(String[] args) {
        // Rows as they sit in the event store: written by two versions of the code.
        List<Map<String, String>> stored = List.of(
                Map.of("schema", "1", "amount", "2500"),
                Map.of("schema", "1", "amount", "1000"),
                Map.of("schema", "2", "minorUnits", "4000", "currency", "USD"));
        for (Map<String, String> row : stored) {
            System.out.println("stored " + new TreeMap<>(row) + " -> " + upcast(row));
        }
        Map<String, Long> totals = stored.stream().map(Upcasting::upcast).collect(
                Collectors.groupingBy(MoneyDeposited::currency, TreeMap::new,
                        Collectors.summingLong(MoneyDeposited::minorUnits)));
        System.out.println("totals by currency: " + totals);
    }
}
Output
stored {amount=2500, schema=1} -> MoneyDeposited[minorUnits=2500, currency=EUR]
stored {amount=1000, schema=1} -> MoneyDeposited[minorUnits=1000, currency=EUR]
stored {currency=USD, minorUnits=4000, schema=2} -> MoneyDeposited[minorUnits=4000, currency=USD]
totals by currency: {EUR=3500, USD=4000}
  • The two schema 1 rows became current MoneyDeposited events with the currency EUR, the only currency the old code supported. The schema 2 row was read as it was.
  • The rest of the code sees only the current type: the totals, 3500 EUR and 4000 USD, did not need to know that two schemas exist.

Plan for this from the first event: store a schema version with every event, prefer adding fields with defaults to renaming them, and never change what an existing field means. A change too large for an upcaster becomes a new event type, and the aggregate handles both.

Choosing whether to use CQRS and event sourcing

Common situations and the design that fits them
SituationUse
Ordinary business data with simple screensPlain CRUD with @Transactional services
Read load far above write load, or queries a write model cannot serveCQRS alone: read tables, a search index or a cache fed by events
The full history is a requirement: ledgers, audits, bookingsEvent sourcing with an append-only store and optimistic versions
New questions about the past keep arrivingEvent sourcing with projections that can be rebuilt
A user must see their own change at onceWait for the command's position, or update the read model in the same transaction
Streams that grow to thousands of eventsSnapshots, or a smaller aggregate
A team that wants a framework rather than its own storeAxon Framework, or a dedicated database such as KurrentDB, formerly EventStoreDB

Apply these patterns to the parts of a system that need them, not to all of it: an event-sourced order service can sit next to CRUD services for products and customers. The rules that keep them working are an optimistic version check on every append, checkpoints stored with the projection's updates, positions that a projector cannot skip, and stored events that are never changed, only upcast. Related pages: the transactional outbox, saga choreography, idempotency and Spring application events.