DevLearn
Back to Platform & Architecture
platform

Event Sourcing

Store state as immutable event sequence

Event Sourcing — Overview

Store state as immutable event sequence

Event sourcing persists state changes as events, not updates. Current state is derived by replaying events. Kafka is natural event store. Enables audit trail, temporal queries, and replay for new projections.

// Event-sourced account
public sealed interface AccountEvent {
  record Opened(String id, Instant ts) {}
  record MoneyDeposited(String id, long amount, String ref) {}
  record MoneyWithdrawn(String id, long amount, String ref) {}
}

// Aggregate replays events
public class Account {
  private long balance;
  public void apply(AccountEvent event) {
    switch (event) {
      case MoneyDeposited d -> balance += d.amount();
      case MoneyWithdrawn w -> balance -= w.amount();
      default -> {}
    }
  }
}

// Kafka as event store
kafkaTemplate.send("account-events", accountId, event);
Tip: Snapshot aggregates periodically — replaying 10 years of events on every read is too slow.