Skip to main content

Event-Driven Architecture, CQRS & Event Sourcing

Learning objectives
  • Distinguish event notification, event-carried state transfer, event sourcing and CQRS — four ideas often lumped together as "event-driven"
  • Choose between choreography and orchestration for a multi-step business process
  • Design an event-sourced aggregate with an event store, snapshots, projections and replays
  • Evolve event schemas safely with a schema registry and upcasting
  • Decide when event sourcing is a good fit for a ledger and when it creates more problems than it solves

TL;DR​

  • Event notification: "something happened, ask me if you care" — thin events, consumers call back. Low coupling on data, but creates callback traffic.
  • Event-carried state transfer (ECST): events carry the data consumers need, so they keep a local copy and never call back. Great for availability; you now have replicated, eventually consistent data.
  • Event sourcing: the event log is the source of truth; current state is a fold over events. Powerful for audit and temporal queries, expensive in complexity.
  • CQRS: separate write model from read models. Often used with event sourcing, but independent of it.
  • Choreography (services react to each other's events) scales and decouples, but the overall process becomes invisible; orchestration (a coordinator issues commands) makes the process explicit and easier to change and monitor. Long money flows usually want orchestration.
  • Events are public contracts: version them, register their schemas, enforce compatibility in CI, and design for duplicates and reordering.

Why it matters​

Event-driven designs are everywhere in both target industries. In e-commerce, OrderPlaced fans out to inventory, payment, fraud, email, loyalty and analytics without checkout knowing any of them exist; this is what keeps checkout fast during 11.11. In banking, payments flow through multi-step processes — debit, clearing, credit, notification, reconciliation — where every step must be auditable and recoverable after a crash. Some banks and fintechs build ledgers on event sourcing; others regret it.

Interviewers use this topic to separate people who have read the buzzwords from people who have operated these systems: "What happens if the consumer sees PaymentCaptured before PaymentAuthorized?", "How do you fix a bug in a projection?", "How do you rename a field in an event that has been in Kafka for three years?"

Core concepts​

Four meanings of "event-driven"​

Martin Fowler's article What do you mean by "Event-Driven"? (2017) separates the patterns below; mixing them up leads to confused designs.

PatternEvent contentConsumer behaviourMain benefitMain cost
Event notificationID + type + minimal factsCalls producer for detailsProducer keeps data private; small eventsCallback load; temporal coupling returns through the back door
Event-carried state transferFull relevant stateStores local replicaConsumers work even if producer is down; no callbacksData duplication, eventual consistency, larger events, PII spread
Event sourcingEvery state change, as the system of recordRebuilds state by replayingComplete audit, temporal queries, replay into new modelsComplexity, schema evolution forever, querying needs projections
CQRS(not about events per se)Reads from separate, optimized modelsIndependent scaling and shape of readsSynchronization lag, more moving parts

Practical guidance: default to ECST for integration events between bounded contexts (include what consumers need, but not everything you have), use notification for large or sensitive payloads (e.g. a KYC document is ready — fetch it with authorization), and treat event sourcing as an internal implementation choice of one service, not an integration style.

Domain events vs integration events​

  • Domain events are internal to a bounded context and use its ubiquitous language (FundsReserved, LimitBreached). They can change as the model evolves.
  • Integration events are published to other contexts and are a public contract (PaymentCompleted v2). Change them like an API: versioned, backward compatible, documented.

Do not publish your internal event-sourcing events directly to the whole company; you will freeze your internal model.

Choreography vs orchestration​

Choreography — each service listens and reacts:

Orchestration — a coordinator (saga orchestrator / workflow engine) drives the steps:

ChoreographyOrchestration
CouplingServices know only eventsOrchestrator knows all participants
VisibilityProcess is implicit, spread across servicesProcess is explicit, one place to read and monitor
ChangeAdding a reactor is easy; changing the sequence is hardChanging the sequence is easy; adding steps needs orchestrator changes
Failure handlingEach service handles its own compensationsCentral compensation logic, timeouts, retries
RiskCyclic dependencies, "event spaghetti"Orchestrator becomes a god service if it absorbs domain logic
Typical toolsKafka / RabbitMQ topicsTemporal, Camunda, AWS Step Functions, or a hand-rolled state machine with outbox

Rule of thumb: choreography for fan-out of facts (notifications, analytics, loyalty), orchestration for business processes with a clear owner and compensations (transfers, refunds, loan disbursement). Details of compensation logic are in Distributed Transactions.

CQRS​

Command Query Responsibility Segregation: commands go to a write model optimized for invariants; queries go to one or more read models optimized for specific screens or APIs.

  • Use it when read and write shapes or volumes differ dramatically: an account has a few writes per day but its statement is read thousands of times; an order is written once and searched by status, seller, date and customer.
  • Consistency lag is the price. Mitigate with read-your-writes (return the new state in the command response, or read from the write model for the user's own recent actions) and by never using a read model to enforce an invariant — balance checks for a withdrawal must hit the write model.
  • Push instead of poll. Over a fully asynchronous write side, a reverse proxy can forward the command and hold the client's request open; the read-side projector pushes the outcome to the proxy as soon as it applies the matching event. The client gets a synchronous answer (Ch 12 · Digital Wallet).
  • Embed the read model. Instead of consumers querying a central service, ship the projection as a library each consumer runs over the same stream, keeping state in-process. That removes a network hop from hot paths, and deterministic apply keeps every copy identical at the same position. The cost: memory and replay time per consumer, and divergence if consumers run different library versions (Ch 13 · Stock Exchange).
  • CQRS does not require event sourcing; a normalized write DB plus CDC into a read store is CQRS.

Event sourcing mechanics​

State is derived from an append-only stream of events per aggregate:

CREATE TABLE events (
global_position bigserial NOT NULL,
stream_id text NOT NULL, -- e.g. 'account-VN0012345678'
version bigint NOT NULL, -- position within the stream
event_id uuid NOT NULL UNIQUE,
event_type text NOT NULL, -- 'FundsDeposited'
schema_version int NOT NULL,
payload jsonb NOT NULL,
metadata jsonb NOT NULL, -- causation id, correlation id, actor
recorded_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (stream_id, version)
);

-- Optimistic concurrency: the writer read version 41 and appends 42.
-- A concurrent writer that also read 41 hits the primary-key violation and retries.
INSERT INTO events (stream_id, version, event_id, event_type, schema_version, payload, metadata)
VALUES ('account-VN0012345678', 42, gen_random_uuid(), 'FundsWithdrawn', 2,
'{"amount_minor": 500000, "currency": "VND", "tx_id": "TX-9001"}',
'{"correlation_id": "c-77", "actor": "mobile-app"}');

Key mechanics:

  • Snapshots. Replaying 2 million events for a merchant settlement account on every command is too slow. Store a snapshot (state + version) every N events or on a schedule; load snapshot + events after it. Snapshots are a cache: you must be able to delete them and rebuild.
  • Projections. Subscribers that turn events into read models. Track each projection's checkpoint (last processed global position) in the same transaction as its writes so it can resume exactly where it stopped.
  • Replays. Fix a bug in a projection or add a new read model by replaying from position 0 into a new table, then switching reads (blue/green for projections). Plan for replay time: at 20k events/s, 2 billion events take more than a day — design partitioned, parallel replays.
  • Versioning and upcasting. Events are immutable; your code changes. Options: (1) add optional fields only (backward compatible); (2) introduce a new event type (FundsWithdrawnV2); (3) upcast old events to the new shape at read time; (4) as a last resort, rewrite the stream into a new store (copy-and-transform) with an audit trail. Greg Young's Versioning in an Event Sourced System is the reference.
  • Idempotency and ordering. Within one stream, version gives total order. Across streams there is no order; consumers must not assume one. Publish with the aggregate ID as the partition key so per-aggregate order is preserved in Kafka.
  • Personal data. You cannot delete events, but regulations may require erasure. Patterns: keep PII out of events (store a reference), or crypto-shredding (encrypt PII per subject and delete the key).

Determinism, replay and what to replicate​

An event-sourced service has two halves, and only one must be deterministic:

  • Deciding turns a command into events. It may read the clock, generate IDs, fetch an FX rate or call a fraud API, as long as what it learns goes into the event.
  • Applying folds an event into state. It must be a pure function of event and state: no clock, no randomness, no network. In the Go example below, Withdraw decides and Apply applies.

Three consequences:

  1. Replicate events, not commands. Re-running a command on a replica can yield different events (a new rate, another fraud score), and state diverges. Of commands, events, state and snapshots, only the event log needs strong replication (Raft, synchronous replicas): state and snapshots are rebuilt from it, and a command matters only until it becomes events or is rejected. Ch 12 · Digital Wallet replicates exactly this.
  2. Prove a code change by replay. Feed the same production event range through the old and new code and diff the resulting states. An empty diff is evidence; a non-empty one names the events whose outcome changed.
  3. Replay faster than real time. When time reaches state only through event timestamps, replay need not wait out the gaps between events, so recovery takes a fraction of the original wall-clock time. Timers follow suit: a hold expires through a HoldExpired event from a scheduler, never because Apply compared against now(). Ch 13 · Stock Exchange depends on this.

Event schema and registry​

A good integration event has:

  • A stable envelope — ID, type, source, time, subject, schema version, correlation/causation IDs. The CNCF CloudEvents specification standardizes such an envelope.
  • A typed payload in Avro, Protobuf or JSON Schema, with money as integer minor units plus currency, timestamps in UTC with zone info where business-relevant, and enums that tolerate unknown values.
  • A partition key chosen for the ordering you need (account ID, order ID).

A schema registry (Confluent Schema Registry, Apicurio, AWS Glue Schema Registry) stores schemas per subject and rejects incompatible changes. Confluent's registry supports modes such as BACKWARD (the default: new consumers can read old data), FORWARD, FULL, their _TRANSITIVE variants, and NONE.

ChangeBackward compatible?Notes
Add optional field with defaultYesAlso forward compatible; the preferred way to evolve
Remove a fieldYes under BACKWARDBreaks old consumers that still expect it unless it had a default (a forward-compatibility concern)
Rename fieldNoAdd new field, deprecate old, migrate consumers
Change type (int → string)NoNew field or new event type
Add enum valueDepends on format and consumer codeConsumers must handle unknown values

Document events with AsyncAPI and run compatibility checks in CI so a breaking change fails the producer's build, not the consumer's production.

When event sourcing fits a ledger — and when it hurts​

A double-entry ledger is conceptually an event log: journal entries are immutable facts, corrections are new reversing entries, and balances are derived. That makes event sourcing attractive.

Fits well when:

  • You need full history and "as of" queries (balance at 23:59:59 on the last day of the quarter for regulatory reporting).
  • Auditability and non-repudiation are first-class; every change carries actor, channel and causation.
  • The domain is naturally event-shaped: holds, releases, postings, reversals, interest accruals.
  • You want to build new views (risk exposure, customer analytics) by replaying history.

Hurts when:

  • Hot accounts. A merchant or bank-internal settlement account receives thousands of postings per second; optimistic concurrency on one stream causes constant conflicts. You need sub-accounts, batching or a different model for that account.
  • Set-based queries and invariants. "Total exposure across all accounts of this corporate group" or "no two accounts share an external number" are awkward against per-stream logs.
  • Long-lived schema evolution. Ten years of events in five schema versions — every upcaster is code you maintain forever.
  • Team experience. Event sourcing changes how you test, migrate, debug and operate. A team new to it can lose months.
  • Simpler alternative suffices. An append-only journal_entries table plus a balances table updated in the same ACID transaction gives most of the audit benefit with ordinary SQL. See Double-Entry Ledger Design.

A frequent and sensible compromise: append-only journal in a relational DB as the system of record, events published via outbox, CQRS read models for statements and analytics — event-driven around the ledger without full event sourcing inside it.

Trade-offs​

ApproachStrengthsWeaknessesChoose when
Request/response onlySimple, immediate consistencyTemporal coupling, poor fan-outFew services, synchronous answers needed
Event notificationSmall events, data stays with ownerCallback load, coupling at read timeLarge or sensitive payloads
Event-carried state transferAutonomy, resilienceReplicated data, eventual consistencyIntegration between bounded contexts
CQRS without ESOptimized reads, ordinary write DBSync lag, extra storeRead-heavy views over normalized data
Event sourcing + CQRSFull audit, temporal queries, replaysHigh complexity, schema evolution, hot streamsAudit-critical domains with event-shaped behaviour and an experienced team
ChoreographyDecoupled, easy fan-outInvisible process, hard to change orderFacts with many independent reactors
OrchestrationExplicit process, central compensationOrchestrator couplingMoney flows, multi-step processes with SLAs

In practice​

An event-sourced account aggregate in Go with an upcaster for an old event version:

package account

import (
"encoding/json"
"errors"
"fmt"
)

var (
ErrInvalidAmount = errors.New("amount must be positive")
ErrInsufficientFunds = errors.New("insufficient funds")
)

type Event interface{ eventType() string }

type FundsDeposited struct {
AmountMinor int64 `json:"amount_minor"`
Currency string `json:"currency"`
TxID string `json:"tx_id"`
}

type FundsWithdrawn struct {
AmountMinor int64 `json:"amount_minor"`
Currency string `json:"currency"`
TxID string `json:"tx_id"`
}

func (FundsDeposited) eventType() string { return "FundsDeposited" }
func (FundsWithdrawn) eventType() string { return "FundsWithdrawn" }

// Account is rebuilt from a snapshot plus the events recorded after it.
type Account struct {
ID string
Balance int64 // minor units
Version int64
}

func (a *Account) Apply(e Event) {
switch e := e.(type) {
case FundsDeposited:
a.Balance += e.AmountMinor
case FundsWithdrawn:
a.Balance -= e.AmountMinor
}
a.Version++
}

// Withdraw checks the invariant against the write model and returns the new
// event; the caller appends it with expected version a.Version.
func (a *Account) Withdraw(amountMinor int64, txID string) (Event, error) {
if amountMinor <= 0 {
return nil, ErrInvalidAmount
}
if a.Balance < amountMinor {
return nil, ErrInsufficientFunds
}
return FundsWithdrawn{AmountMinor: amountMinor, Currency: "VND", TxID: txID}, nil
}

// Decode upcasts stored events to the current shape. Schema v1 stored the
// amount as a whole-VND number named "amount"; v2 uses minor units and currency.
func Decode(eventType string, schemaVersion int, raw []byte) (Event, error) {
switch {
case eventType == "FundsDeposited" && schemaVersion == 1:
var v1 struct {
Amount int64 `json:"amount"`
TxID string `json:"tx_id"`
}
if err := json.Unmarshal(raw, &v1); err != nil {
return nil, fmt.Errorf("decode FundsDeposited v1: %w", err)
}
return FundsDeposited{AmountMinor: v1.Amount, Currency: "VND", TxID: v1.TxID}, nil
case eventType == "FundsDeposited":
var e FundsDeposited
if err := json.Unmarshal(raw, &e); err != nil {
return nil, err
}
return e, nil
case eventType == "FundsWithdrawn":
var e FundsWithdrawn
if err := json.Unmarshal(raw, &e); err != nil {
return nil, err
}
return e, nil
default:
return nil, fmt.Errorf("unknown event type %q", eventType)
}
}

(VND has no minor unit in everyday use, so "minor units" equals đồng here; for USD it would be cents. Store currency with every amount anyway.)

Operational knobs that matter:

  • Kafka producer: acks=all, idempotent producer enabled, and a replication factor of 3 with min.insync.replicas=2 is a common durability baseline for payment topics. See Message Queues & Event Streaming.
  • Consumer lag is the key health metric for projections and choreographed flows; alert on lag in time, not just messages.
  • Dead-letter topics with tooling to inspect, fix and replay; a DLQ nobody reads is a silent data-loss bucket.
  • Correlation and causation IDs on every event so tracing can reconstruct a whole saga.

Common pitfalls​

  • Events as remote procedure calls. SendEmailToCustomer published as an "event". Symptom: implicit command coupling, and nobody knows who must handle it.
  • Exposing internal events as integration events. Symptom: you cannot refactor your aggregate without breaking six teams.
  • Assuming global ordering. Symptom: PaymentRefunded processed before PaymentCaptured on a different partition, producing a negative balance in a projection.
  • Non-idempotent consumers. Symptom: duplicate emails, double loyalty points, or double credits after a consumer restart.
  • Validating invariants against read models. Symptom: two withdrawals both see the old balance in the cache and overdraw the account.
  • Snapshots as source of truth. Symptom: a buggy snapshot cannot be rebuilt because old events were archived without the code to read them.
  • Unbounded choreography. Symptom: nobody can draw the refund process, and a new step causes an event loop.

Interview angle​

  • When you say "event-driven", specify which of the four patterns you mean. This alone distinguishes you.
  • For a payment or transfer flow, propose orchestration with an explicit state machine, compensations and timeouts; for notifications and analytics, choreography.
  • If you propose event sourcing, be ready for: snapshots, projection rebuilds, upcasting, hot streams, GDPR erasure, and "why not an append-only table?". Proposing ES without discussing these is a red flag.
  • Questions to expect: "How do you guarantee the event is published if the DB commit succeeded?" (outbox / CDC), "How do consumers handle duplicates?" (idempotency keys, dedup tables), "What partition key would you use?", "How do you evolve the schema?"
  • Red flags: "Kafka guarantees exactly-once so we don't need idempotency"; using a read model to check balances; no answer for replay duration.

Self-check​

1. Explain the difference between event notification and event-carried state transfer with a shipping example.

Notification: Order publishes OrderPlaced with only the order ID; Shipping calls the Order API to fetch address and items, so Shipping still depends on Order being available. ECST: OrderPlaced carries the address and items Shipping needs; Shipping stores them locally and never calls back, staying available when Order is down, at the cost of a duplicated, eventually consistent copy.

2. Why should a withdrawal never be validated against a CQRS read model?

Read models are eventually consistent; two concurrent withdrawals could both read a stale balance and both succeed, overdrawing the account. Invariants must be enforced in the write model within a consistency boundary (an aggregate with optimistic concurrency, or a row lock / conditional update in SQL).

3. Your projection had a bug for three months. How do you fix the data without downtime?

Fix the projector code, then replay the event store from position 0 into a new version of the read model table while the old one keeps serving. When the new projection catches up to the live position, switch query traffic to it (blue/green), then drop the old table. Make sure the projector is idempotent and stores its checkpoint atomically with its writes.

4. What are three ways to evolve an event schema, from safest to most invasive?
  1. Add optional fields with defaults (backward compatible, enforced by the schema registry).
  2. Introduce a new event type or version and upcast old events to the new shape when reading.
  3. Copy-and-transform the stream into a new store, keeping an audit trail of the migration — only when the old shape is unworkable.
5. Scenario: a fintech's event-sourced ledger slows down because one merchant settlement account gets 3,000 postings per second. What do you do?

The single stream is a concurrency hotspot. Options: split it into N sub-account streams (sharded by hash of transaction ID) and aggregate the balance in a projection; batch postings into periodic summary events; or move that account type to a different model (e.g. append-only rows with periodic balance roll-ups) since it does not need per-posting invariant checks. Keep invariant checks only where they are needed (customer accounts that cannot go negative).

6. When would you choose orchestration over choreography for an e-commerce refund?

When the refund has multiple dependent steps (cancel shipment, return stock, refund payment, reverse loyalty points, notify) with timeouts and compensations, and the business needs to see where each refund is stuck. An orchestrator makes the state explicit, centralizes retries and compensation, and makes changing the sequence a single-place change. Choreography suits independent reactions (send email, update analytics) to a RefundCompleted fact.

7. How do you reconcile event sourcing's immutability with a data-erasure request?

Keep PII out of events where possible, storing only references to a separately deletable profile store. Where PII must be in events, encrypt it with a per-subject key stored in a key store; deleting the key ("crypto-shredding") renders the data unreadable while preserving the event structure for audit. Confirm with legal what must be retained for financial regulation, which may override erasure for some fields.

🧠 Flashcards0/10 learned · 0 retries

Exercise​

Build a minimal event-sourced wallet in Go backed by PostgreSQL:

  1. Create the events table above and implement Append(streamID, expectedVersion, events) that returns a concurrency error on primary-key conflict.
  2. Implement Deposit and Withdraw commands; prove with a test that two concurrent withdrawals of 600 from a balance of 1,000 result in exactly one success.
  3. Add a projector that maintains a balances table with a checkpoint updated in the same transaction; kill it mid-run and show it resumes without double counting.
  4. Add a snapshot every 100 events and measure command latency for a stream of 100,000 events with and without snapshots.
  5. Introduce schema v2 of FundsDeposited and an upcaster; show v1 and v2 events load correctly.

Done when: the concurrency test passes 100 times in a row (go test -count=100 -race) and a full projection rebuild produces identical balances to the live projection.

Further reading​

  • Martin Fowler, "What do you mean by 'Event-Driven'?" (2017) and "CQRS" (2011), martinfowler.com.
  • Greg Young, Versioning in an Event Sourced System (Leanpub).
  • Designing Data-Intensive Applications — Martin Kleppmann. Chapters on stream processing and derived data.
  • Microservices Patterns — Chris Richardson. Sagas, event sourcing and CQRS chapters.
  • Building Event-Driven Microservices — Adam Bellemare (O'Reilly, 2020).
  • CloudEvents specification (cloudevents.io) and AsyncAPI specification (asyncapi.com).
  • Confluent documentation: Schema Registry schema evolution and compatibility.
Finished this page?

Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).