← Back to SQL, page 23

sql-0455 · Hard senior

How does event sourcing store data, and what are its costs?

Event sourcing stores every change as an immutable event (AccountOpened, MoneyDeposited) in an append-only log, and derives current state by replaying events, usually into snapshot or read-model tables. It gives a complete history and easy audit, but queries on current state need projections, event schemas must be versioned, and correcting mistakes means appending compensating events.

Full answer
text
events(stream_id, version, type, payload jsonb, recorded_at,
       PRIMARY KEY (stream_id, version))

Appending with optimistic concurrency: INSERT ... (stream_id, version) VALUES (:acct, :expected + 1); the primary key rejects a concurrent writer who read the same version.

Current balance: replay the stream's events, or read a projection table updated as events are appended. Snapshots every N events speed up replays for long streams.

Benefits:

  • Full history and 'state as of any time'.
  • New read models can be built later from old events.
  • Natural fit for audit-heavy domains (finance, logistics).

Costs:

  • Two models to maintain (events and projections).
  • Event schema evolution: old events must remain readable forever, with upcasters.
  • Deleting personal data conflicts with immutability; crypto-shredding (deleting per-user keys) is one workaround.
  • Simple questions become projection work.

Many teams use an audit log or outbox instead, keeping state tables as the source of truth.

Key points

  • Events are the source of truth
  • State comes from replays or projections
  • Version keys give optimistic concurrency
  • Schema evolution is a lasting cost
  • Privacy deletion is hard

Common mistakes

  • Choosing event sourcing for simple CRUD
  • Editing past events

Follow-ups

  • How would you rebuild a projection?
  • How does an audit log differ from event sourcing?

Tips

  • Weigh history against complexity