Event Sourcing: Projections, Replay, and Recovery
An operations guide to event streams, idempotent projections, schema changes, snapshots, lag, and safe read-model rebuilds.
CQRS does not require event sourcing. This guide focuses on event-sourced operations: append events within a stream, build idempotent projections, evolve event schemas, and recover safely from lag or failed rebuilds. Event sourcing adds durable history and replay, along with storage, privacy, and operational costs.
Event Sourcing: Projections, Replay, and Recovery
First decide: do you need event sourcing?
CQRS separates command and query models. Event sourcing stores domain changes as events and rebuilds state by replaying them. They can be used together, but CQRS does not require event sourcing. For the decision to separate read and write models, see CQRS Pattern.
Choose event sourcing when the durable sequence of domain changes has a clear use, such as replaying state or answering historical questions. A CRUD table plus an audit log or change feed may be enough when you only need the current state and routine history. This guide covers event stream operations, projection reliability, schema evolution, snapshots, and recovery.
Event Sourcing Fundamentals
Event sourcing changes how you think about persistence. Instead of storing current state, you store the sequence of events that led to that state.
Storing Events Instead of State
Traditional state storage overwrites values:
UPDATE accounts SET balance = 500 WHERE id = 1;
The old state is lost.
Event sourcing appends instead:
AccountOpened { account_id: 1, currency: "USD" }
AccountCredited { account_id: 1, amount: 200, currency: "USD" }
AccountCredited { account_id: 1, amount: 300, currency: "USD" }
The current balance is derived by applying those facts in stream order. The events do not repeat a final balance that can disagree with the prior history.
An append-only event model preserves application history, but it does not by itself make an audit log tamper-proof or satisfy compliance requirements. Access controls, retention, backups, administrator audit records, and any integrity mechanism need their own design and review. Event payloads can also retain sensitive data long after a current-state record would have been changed or deleted.
An event store is a specialized database designed for event sourcing. Core operations:
- Append events: Add new events to a stream
- Read stream: Retrieve all events for an aggregate in order
- Subscribe: Get notified when new events are added
The event store is the source of truth. Everything else is derived.
An event store must support the operations your application relies on: appending to a stream, reading that stream in order, and handling concurrent appends. Replay and subscription behavior vary by product. A broker or streaming platform may retain records and support replay too, but its ordering and retention rules may be partition-based rather than aggregate-based. Check the chosen system’s contract and key events so all changes for one aggregate stay within its ordering boundary.
graph LR
E1[AccountOpened] --> Store[(Event Store)]
E2[Deposited] --> Store
E3[Withdrawn] --> Store
Store -->|replay| Snapshot[Current State]
Aggregates and Event Streams
In domain-driven design, an aggregate is a cluster of related objects treated as a single unit for data changes. Each aggregate has its own event stream.
For an order management system:
OrderAggregatestream contains:OrderCreated,ItemAdded,ItemRemoved,OrderConfirmed,OrderShipped,OrderCancelledInventoryAggregatestream contains:InventoryReserved,InventoryReleased,InventoryDamaged
Each stream is append-only. Events are immutable once written.
Ordering is scoped to the stream or partition guarantee provided by the event store. An aggregate usually uses one stream so its command handler can validate a change against the expected version and append with optimistic concurrency. This can protect invariants within that stream if every writer follows the same protocol; it does not create a global order across streams.
Changes across aggregates are separate operations. If a workflow needs multiple aggregates to progress together, coordinate it explicitly and define what happens when one step fails. This guide focuses on stream and projection behavior; for the command/query separation decision, see CQRS Pattern.
Event sourcing helps when the history supports a real operation:
- Rebuild a projection after correcting its logic.
- Create a new read model from retained events.
- Reconstruct state at a stream version, when the event model supports that query.
- Inspect the sequence that led to a current state.
These capabilities depend on event design and retention. Replaying a stream does not automatically produce a compliant audit trail or answer a wall-clock-time query; those require their own semantics and controls.
Event sourcing is not without friction:
Event schema evolution. Event schemas change over time. Old events must still deserialize correctly. You need a strategy for handling changes: upcasters, version numbers, or both.
Projection rebuild times. Replaying millions of events takes time. Large aggregates can become slow to reconstruct. Periodic snapshots help mitigate this.
Eventual consistency. Read models built from events lag behind writes. Your application must handle stale data.
Increased complexity. The mental model differs from traditional CRUD. Teams need time to adapt.
Illustrative schema change: an OrderCreated event originally contains customer_name; a later version stores customer_first_name and customer_last_name. Historical events still use the old shape. An upcaster can translate the old payload for a projection, but splitting a name on whitespace may not preserve the original meaning. Choose a migration rule that fits the domain, keep the original event immutable, and test old payloads through the same replay path used in production.
Projection throughput depends on handler work, storage, retries, and how consumers share the event stream.
Delivery and idempotency
Delivery guarantees depend on the event store, broker, consumer, checkpoint, and database transaction. A consumer can receive an event again after a failure or retry, so projection updates should be idempotent. “Exactly once” is not a blanket property of a whole application: state changes and checkpoints must commit together, or retries must be safe.
Design your projections assuming events will arrive more than once. The idempotent handler pattern handles this:
def handle_transfer_event(event, database):
with database.transaction():
if database.has_processed(event.event_id):
return
database.update_read_model(event)
database.record_processed(event.event_id)
Event ordering boundaries
Treat order as a property of the storage or delivery contract, not of the word “event.” A stream or partition may preserve its own append order; separate streams generally have no shared total order. Key related events to the same stream or partition when the aggregate’s invariants depend on their order, and validate expected versions on append.
For aggregate-centric operations, ordering within the stream matters. For cross-aggregate workflows, you need additional coordination.
For example, a balance projection must apply AccountOpened, Deposited, and Withdrawn in the account stream’s defined order. If the same invariant spans different streams, per-stream ordering is not enough; the application needs an explicit coordination and conflict policy.
Backpressure Handling
Fast event producers can overwhelm slow projection consumers. Without backpressure, lag grows until your system breaks.
Consumer-side backpressure: Kafka consumers control their own fetch rate. If projections process slowly, consumer lag grows.
Producer-side backpressure: Commands wait if the event store is overwhelmed. This backpressure propagates to callers.
Mitigation approaches:
- Scale horizontally: Add projection worker instances
- Prioritize streams: Process critical streams first during high load
- Batch processing: Accumulate events and process in batches for throughput
- Circuit breakers: Stop consuming when downstream systems fail
Tune broker and consumer settings against the client version you run. Change one setting at a time, then observe memory use, processing throughput, rebalances, and projection freshness under representative load. Avoid copying sample values from another workload.
When backpressure builds despite configuration tuning, circuit breakers prevent cascading failures. If a downstream read model database becomes unavailable, continue consuming and buffering events in memory risks OOM errors. A circuit breaker opens after N consecutive failures, stops fetching new events, and allows the projection to recover gracefully. Some teams implement a dead-letter queue for events that exceed a retry threshold, ensuring these events are not lost while the main projection continues processing newer events.
Projections vs Transformations
Projections build read models from events. Transformations convert events between schemas.
Projections: OrderCreated → OrderSummary for the orders read model
Transformations: OrderCreated_v1 → OrderCreated_v2 (upcaster)
Keep transformations focused. A transformation should only adapt schema, not change semantic meaning. Business logic belongs in projections.
An upcaster demonstrates the distinction clearly. Suppose the original OrderCreated_v1 event contains:
{
"event_type": "OrderCreated",
"version": 1,
"order_id": "abc123",
"customer_name": "Acme Corp",
"total": 99.99
}
After a schema change, OrderCreated_v2 adds a customer_id field and renames total to order_total. The upcaster transforms the v1 event when replaying historical events:
def upcast_order_created_v1_to_v2(event_data):
return {
"event_type": "OrderCreated",
"version": 2,
"order_id": event_data["order_id"],
"customer_id": None, # Unknown for legacy events
"customer_name": event_data["customer_name"],
"order_total": event_data["total"]
}
The upcaster handles schema migration without introducing business rules. It maps fields, fills defaults for new fields, and preserves the original semantic data. If you find yourself adding conditional logic or derived calculations in an upcaster, that logic belongs in a projection handler instead. Projections apply business logic to build read models; upcasters only bridge schema versions.
Cold Start Considerations
New projection consumers start from the beginning of the event stream. For mature systems, this takes time.
Full replay: Read from offset 0. Process all historical events. Takes time proportional to event history length.
From timestamp: Some event stores let you replay from a specific time. Useful for disaster recovery.
Parallel replay: Partition the event stream and process partitions in parallel. Requires consumer support for parallel processing.
Replay cost depends on event count, event size, projection work, storage throughput, and the destination database. Benchmark with representative data before deciding whether snapshots or parallel consumers are needed. Parallelism can shorten rebuilds only when work can be partitioned without violating the stream ordering contract; test that boundary and failure recovery too.
Event store and broker responsibilities
An event store is the source of truth for event-sourced state. A broker can distribute events to projections and other consumers. One product may provide both roles, or the system may use separate components. Verify retention, replay, per-stream or per-partition ordering, optimistic concurrency, subscription checkpoints, and backup/restore behavior for the actual product and version you deploy.
Building Read Models with Projections
Projections build read models from events. A projection subscribes to event streams and updates a read model accordingly.
How Projections Work
graph LR
EventStore[(Event Store)] --> Projection[Projection]
Projection --> ReadModel[(Read Model)]
subgraph Projection Logic
P1[Handle AccountOpened]
P2[Handle Deposit]
P3[Handle Withdrawal]
end
Projection --> P1
Projection --> P2
Projection --> P3
When an event is written, the projection handler for that event type executes. It reads the event, updates the read model, and commits.
Projection Examples
Given these events:
OrderCreated { order_id: 123, customer_id: 456, items: [...] }
ItemAdded { order_id: 123, item_id: 789, quantity: 2 }
OrderConfirmed { order_id: 123 }
A “orders by customer” read model projection:
def handle_order_created(event):
read_model.insert({
'order_id': event.order_id,
'customer_id': event.customer_id,
'status': 'created',
'total_items': len(event.items)
})
def handle_item_added(event):
read_model.update(
{'order_id': event.order_id},
{'$inc': {'total_items': event.quantity}}
)
def handle_order_confirmed(event):
read_model.update(
{'order_id': event.order_id},
{'$set': {'status': 'confirmed'}}
)
Projection code should stay deterministic and safe to rerun. Keep external side effects in separate consumers.
Command Handler Implementation
# Pseudocode: adapt expected-version tokens and transaction boundaries to the event store API.
class CommandHandler:
"""Handles commands and emits events."""
def __init__(self, event_store):
self.event_store = event_store
def handle_create_order(self, command: CreateOrderCommand) -> OrderCreatedEvent:
# Validate business rules
if not command.items:
raise InvalidOrderError("Order must have at least one item")
# Create and persist event
event = OrderCreatedEvent(
order_id=str(uuid.uuid4()),
customer_id=command.customer_id,
items=command.items,
total=sum(item.price * item.quantity for item in command.items),
created_at=datetime.utcnow()
)
self.event_store.append(event, expected_version=0)
return event
def handle_confirm_order(self, command: ConfirmOrderCommand) -> OrderConfirmedEvent:
# Load current state from event stream
events = self.event_store.get_stream(command.order_id)
order = OrderAggregate.reconstruct(events)
# Validate state transition
if order.status != "pending":
raise InvalidStateTransitionError(f"Cannot confirm order in status: {order.status}")
# Emit event
event = OrderConfirmedEvent(
order_id=command.order_id,
confirmed_at=datetime.utcnow()
)
self.event_store.append(event, expected_version=order.version)
return event
Aggregate Reconstruction with Snapshots
class OrderAggregate:
"""Reconstructs aggregate state from events with snapshot support."""
@classmethod
def reconstruct(cls, events: list[Event], snapshot: Snapshot = None) -> "OrderAggregate":
aggregate = cls()
if snapshot:
# Start from snapshot
aggregate.order_id = snapshot.order_id
aggregate.customer_id = snapshot.customer_id
aggregate.status = snapshot.status
aggregate.items = snapshot.items
aggregate.total = snapshot.total
aggregate.version = snapshot.version
else:
# Replay from beginning
aggregate.version = 0
# Apply remaining events
# snapshot.version counts events already applied; event offsets are zero-based.
start_version = snapshot.version if snapshot else 0
for event in events[start_version:]:
aggregate._apply(event)
aggregate.version += 1
return aggregate
def _apply(self, event: Event):
if isinstance(event, OrderCreated):
self.order_id = event.order_id
self.customer_id = event.customer_id
self.items = event.items
self.total = event.total
self.status = "pending"
elif isinstance(event, ItemAdded):
self.items.append(event.item)
self.total += event.item.price * event.item.quantity
elif isinstance(event, OrderConfirmed):
self.status = "confirmed"
def should_snapshot(self, interval: int) -> bool:
# Choose the interval from measured reconstruction cost and write rate.
return interval > 0 and self.version > 0 and self.version % interval == 0
def create_snapshot(self) -> Snapshot:
return Snapshot(
order_id=self.order_id,
customer_id=self.customer_id,
status=self.status,
items=self.items,
total=self.total,
version=self.version
)
Idempotent Projection Handler
class IdempotentProjection:
"""Pseudocode: commit a projection update and its checkpoint atomically."""
def __init__(self, read_model_db):
self.read_model = read_model_db
def handle(self, event: Event):
with self.read_model.transaction():
if not self.read_model.insert_processed_id_if_absent(event.event_id):
return
if isinstance(event, OrderCreated):
self._handle_order_created(event)
elif isinstance(event, OrderConfirmed):
self._handle_order_confirmed(event)
self.read_model.advance_checkpoint(event.stream_id, event.version)
def _handle_order_created(self, event):
# Upsert instead of insert
self.read_model.upsert(
{'order_id': event.order_id},
{
'$set': {
'customer_id': event.customer_id,
'status': 'created',
'created_at': event.created_at
},
'$setOnInsert': {'_id': event.order_id}
}
)
Projections are derived from events, so they can be rebuilt when:
- You find a bug in projection logic
- You need a new read model from historical data
- You want to change the read model schema
For a live system, build into a new read-model generation while the active model continues serving queries. Start the new projection from its documented checkpoint, verify counts and domain invariants, then switch readers over. Retain the previous generation until the cutover is known to be healthy.
Exercise: observe lag, retry, and rebuild
Use a small fixture stream and a disposable read model. This is an illustrative exercise; choose values that fit your implementation.
- Pause the projection consumer and append an event to the stream.
- Query the active read model and record its last applied stream version. It should still show the prior projection state.
- Resume the consumer and verify the new event appears once. Force a retry and verify that neither the read model nor its processed-event record is duplicated.
- Build a second read-model generation by replaying the fixture. Compare its result with the active model, then test the reader cutover and rollback path.
- Record how your system reports the oldest unprocessed event, checkpoint position, and time to catch up. Use those observations to set the projection freshness objective.
Projection lag and user-visible reads
A projection can lag behind a committed event. A command may return success while a query still reads the prior state. This guide focuses on event-sourced projections; CQRS model separation is covered in CQRS Pattern.
Measure freshness
Measure time from event append to query visibility, the oldest unprocessed event, and checkpoint progress for each projection. Set a freshness objective based on the query’s users, then test recovery against it. Do not treat another system’s timing as a baseline.
User Experience Considerations
Users notice eventual consistency in specific scenarios:
- They submit an order and immediately check their order list
- They update their profile and refresh the page
- They delete an item and see it briefly before the page updates
Mitigation strategies:
- Optimistic UI: Show the expected state immediately, reconcile if needed
- Read-your-writes consistency: Route reads to a model that includes your own writes
- Refresh mechanisms: Provide manual refresh or auto-refresh for stale-sensitive views
An optimistic UI can show the expected change before a projection catches up, but it should distinguish a submitted command from a confirmed one. If the command is rejected, reconcile the local view and explain what happened.
A read-your-writes path can route the user to an authoritative model, wait until the projection reaches the command’s stream version, or overlay the confirmed command result in the client. Each choice has different latency and failure behavior; make that behavior visible to the user.
Eventual Consistency Flow
graph LR
Command[Command] --> Validate[Validate Command]
Validate --> Persist[Persist to Event Store]
Persist --> Emit[Emit Event]
Emit --> Async[Async Projection]
Async --> Update[Update Read Model]
Update --> Query[Query Read Model]
Query --> User[Return to User]
Persist --> Query[Read immediately<br/>after write]
Production Failure Scenarios
| Failure | Impact | Mitigation |
|---|---|---|
| Projection lag too long | Users see stale data for extended period | Monitor projection lag; scale projection workers; alert on SLA breach |
| Event schema changes break projections | Read models stop updating | Implement upcasters; version event schemas; test schema evolution |
| Projection worker crashes mid-update | Partial update to read model | Idempotent projections; event replay capability; transactional outbox |
| Replay repeats an external side effect | Duplicate emails, payments, or webhooks | Keep projections deterministic; isolate effects behind idempotent consumers |
| Checkpoint advances before data commits | Replay skips events after a crash | Commit checkpoint with the read-model update, or advance it only after a durable write |
| Rebuild runs against live readers | Users see empty or partially rebuilt data | Build into a versioned read store, validate it, then switch readers over |
| Event store becomes unavailable | Commands cannot be processed | Use replicated event store; partition for availability |
| Snapshot too old | Long aggregate reconstruction time | Define snapshot frequency; monitor snapshot age |
| Concurrent projections conflict | Duplicate or lost updates in read model | Use optimistic concurrency; idempotent operations; event ordering guarantees |
| Kafka consumer group rebalance | Brief read model unavailability | Plan for rebalance delays; use consumer lag monitoring |
| Read model database unavailable | Reads fail but writes succeed | Read replicas; circuit breakers; graceful degradation |
Observability Checklist
Projection health needs more than a process-up signal. A worker can stay alive while its checkpoint falls further behind, or keep advancing while silently writing incomplete read models. Track the path from event append to a usable query result.
- Measure consumer lag by projection and partition, plus the age of the oldest unprocessed event. Alert against the freshness objective for each read model.
- Record event processing rate, retry count, failures by event type, and time spent in handlers and read-store writes. A sudden drop in throughput can explain rising lag before users report stale views.
- Track checkpoint progress and compare it with the last successful read-model update. Keep checkpoint writes consistent with projection writes so a crash cannot skip data.
- Include event ID, aggregate ID, correlation ID, projection name, and event version in structured logs. Avoid logging the full event payload, which may contain personal or confidential data.
- Run a reconciliation check for important projections, such as comparing aggregate counts or totals against the authoritative event stream.
- Test alerts and recovery procedures by pausing a consumer, replaying a failed event, and rebuilding a disposable projection. Record expected recovery time and the freshness impact.
When an alert fires, first identify which projection and partition stopped advancing. Check handler errors and read-store availability, then decide whether to retry, quarantine a poison event, or scale consumers. Do not reset offsets or clear a production read model as a first response; confirm the recovery point and rebuild plan before changing checkpoints.
Security and Compliance Notes
An append-only event log changes how privacy and access controls work. Correcting a current record does not erase sensitive values already copied into historical events, snapshots, backups, and downstream projections.
- Keep event payloads focused on facts needed to enforce domain rules. Store references to sensitive data when possible instead of copying names, payment details, or health information into every event.
- Classify event fields and restrict event-store, replay, and export permissions by role. Projection workers should have only the access needed for their streams and destination stores.
- Define retention and deletion behavior before launch. Where law or policy requires erasure, use an approved design such as separately held personal data with revocable references, encryption with controlled key destruction, or retention-limited event streams. Validate the approach with the applicable compliance owner.
- Protect events in transit and at rest, and manage encryption keys separately from the event store. Apply the same controls to snapshots, backups, dead-letter queues, and replay tooling.
- Preserve audit records for administrative actions such as event exports, permission changes, projection resets, and replay jobs. Keep these audit records separate from ordinary application logs.
- Redact or tokenize sensitive fields in logs and traces. Correlation identifiers should help investigations without exposing the event body.
If an event schema change introduces a sensitive field, treat it as a data migration: find every consumer and stored copy, update access rules, and verify that logs and replay tools do not expose the new field by default.
Consistency Guarantees
Event sourcing has several consistency boundaries:
- Commands validate against current state before accepting changes
- Events are written atomically within an aggregate
- Read models eventually catch up
The consistency boundary depends on the event store and the command handler’s concurrency check. A handler can load stream version N, validate the command, and append only if the stream is still at N. If another writer has advanced the stream, the append must be rejected and the handler should reload and revalidate. This protects invariants only when all writers use the same rule. It does not give different streams a global order.
Projections can lag behind the stream, so queries may be stale until they catch up. Workflows across aggregates need explicit coordination, such as a saga or process manager, and a defined response to partial failure.
Where CQRS ends and event sourcing begins
CQRS can separate command and query models while current state remains authoritative. Event sourcing makes the event history authoritative and builds state from that history. For the model-separation decision, see CQRS Pattern.
Moving from a CRUD audit log to event sourcing
| Decision factor | CRUD with an audit log | Event sourcing |
|---|---|---|
| Consistency | Current state and its audit entry can be saved in one transaction. | Events are authoritative; derived views may lag behind the event stream. |
| Complexity | The application updates current state and records changes. | The application models domain events, versioning, and projection behavior. |
| Storage and replay | Keeps current rows plus history; reconstructing past state needs custom logic. | Keeps events as the source of truth; replay rebuilds state and projections. |
| Operational cost | Manage database backups, audit retention, and indexes. | Manage event retention, schema evolution, replay capacity, and projection recovery. |
When event sourcing fits
Event sourcing adds a durable history and replay path. Use it when those capabilities are worth the cost.
Trade-off comparison
| Concern | CRUD with an audit log | Event sourcing |
|---|---|---|
| Source of truth | Current state plus recorded audit changes | Ordered domain events |
| Historical state | Requires purpose-built history queries | Reconstructed by replaying events |
| Read models | Usually query current tables or replicas | Built and rebuilt by projections |
| Schema changes | Migrate current records and audit format | Keep old events readable or migrate them deliberately |
| Operations | Backups, indexes, and audit retention | Event retention, projections, replay, and schema evolution |
Good Fits
Event sourcing fits when:
History is part of the product or domain. A ledger or workflow may need to explain how its current state came to be. An event log can preserve that sequence, but it does not automatically satisfy audit or regulatory requirements.
Historical reconstruction matters. Questions about a prior state can be answered by replay when the event schema, retention policy, and time semantics support it.
Replay must rebuild derived state. If projections need to be regenerated from retained domain events, an event stream can serve as their source.
A financial ledger can be a fit when the sequence of credits and debits is part of the domain model. It still needs access controls, retention rules, reconciliation, and a review of applicable audit requirements.
Illustrative counterexample: a small content site that only needs the current published article may not benefit from preserving every edit as an event. A current-state table and backups may meet the need with less operational work.
Event sourcing is often unnecessary when:
Simple CRUD is enough. If the application needs current state and straightforward queries, durable event history may add cost without solving a requirement.
Limited operational capacity. Event retention, projection recovery, schema evolution, and backups need clear ownership.
Queries need the latest write. Keep those reads on the authoritative model or use an explicit read-your-writes path; do not rely on an asynchronous projection to be current.
A small application that only needs current state and ordinary CRUD queries rarely benefits from keeping a durable event history. Start with the simpler model unless replay or historical reconstruction solves a real requirement.
Before adopting event sourcing:
- Do you have a genuine need for event replay or temporal queries?
- Do you need multiple, differently-optimized read models?
- Is the team prepared for the operational complexity?
- Is eventual consistency acceptable for your use cases?
Adopt it only when replay or durable history is worth the extra operating work.
Common Pitfalls / Anti-Patterns
- Editing historical events in place. Event history is the source of truth. Correct mistakes with an explicit compensating event or a documented migration; mutating old records makes audits and replay results unreliable.
- Replaying side effects. A projection rebuild may run every handler again. Keep projections deterministic and isolate email, payment, or webhook effects behind separate consumers with idempotency keys.
- Resetting a live projection without a cutover plan. Clearing its read store before replay completes can leave users with an empty or partial view. Rebuild into a versioned store, validate it, then switch readers over.
- Treating checkpoints as independent from writes. If a checkpoint advances before the read-model update commits, a crash can permanently skip events. Commit both atomically where possible, or make replay safe and checkpoints conservative.
- Assuming event order across aggregates. Ordering is normally guaranteed only within a stream or partition. Use a saga or explicit version checks when a workflow depends on events from multiple aggregates.
- Using snapshots as the authoritative record. Snapshots speed up reconstruction, but they can be discarded and rebuilt. Keep them versioned and verify them against the underlying events.
- Putting sensitive data in every event. Historical events persist through ordinary updates and may be copied to many projections. Minimize payloads and design deletion, retention, and access controls before the first production event.
Related Patterns
Event sourcing connects to other event and recovery patterns.
Event sourcing can be used with event-driven architecture, but the event store and broker have separate responsibilities.
The saga pattern handles distributed transactions across microservices. Sagas work well with event sourcing because each saga step can emit events that trigger the next step.
For distributed transactions across services, see distributed transactions which covers two-phase commit and related approaches.
The database per service pattern supports CQRS because each side can use a database optimized for its workload. The write side might use a relational database for transactional integrity. The read side might use a document store or columnar database for query performance.
Quick Recap Checklist
Key Points
- CQRS and event sourcing are related, separate choices
- Event sourcing makes the event history authoritative
- Projections build query models from events and need retry-safe updates
- Ordering is scoped to the store’s stream or partition contract
- Replay, schema evolution, privacy, and recovery need an operating plan
Pre-Deployment Checklist
- [ ] Event store selected and its ordering, replay, retention, concurrency, and restore behavior documented
- [ ] Aggregate boundaries defined and documented
- [ ] Event schema versioning strategy implemented (upcasters or versioned types)
- [ ] Projection infrastructure in place for read model updates
- [ ] Snapshot strategy defined for long-running aggregates
- [ ] Monitoring for projection lag and event consumption delays
- [ ] Read model rebuild procedure documented and tested
- [ ] Replay handlers are deterministic; external side effects use separate idempotent consumers
- [ ] Projection checkpoint and read-model write have a crash-safe commit strategy
- [ ] Rebuilds use a validated cutover plan that keeps the active read model available
- [ ] Eventual consistency handling documented for UI teams
- [ ] Security model defined for event store access
- [ ] Schema evolution testing implemented
Interview Questions
Expected answer points:
- Current-state storage keeps the latest value as the source of truth
- Event sourcing keeps domain changes as the source of truth and derives state by replay
- Replay can rebuild projections or answer historical questions when event and time semantics support them
- It adds event retention, schema evolution, privacy, and recovery work
Expected answer points:
- CQRS and event sourcing are complementary but independent patterns
- CQRS can separate models while current state remains authoritative
- Event sourcing stores the sequence of events rather than current state, enabling replay and historical reconstruction
- Yes, you can have CQRS without event sourcing (using regular state storage for the write model)
- You can also use event sourcing without separating command and query models
- An event history does not automatically meet audit or compliance requirements
- Combine the patterns only when separate query models and durable event history each solve a real problem
Expected answer points:
- An event store keeps the append-only event history used as the source of truth
- Core operations: append events, read stream by aggregate ID, subscribe to event streams
- In an event-sourced model, application events are treated as immutable; corrections use an explicit new event or migration
- Stores the sequence of events that led to current state, not the current state itself
- Replay can reconstruct state at a stream position; wall-clock queries need explicit time semantics
- Check the chosen product documentation for stream, partition, retention, replay, and concurrency behavior
Expected answer points:
- A command can append an event before an asynchronous projection processes it
- During that gap, a query may return the prior read-model state
- Measure append-to-query visibility and compare it with the freshness objective for that projection
- Applications must be designed to handle stale reads during this window
- Mitigation strategies: optimistic UI, read-your-writes consistency, manual/auto-refresh mechanisms
Expected answer points:
- Old events must remain readable as the domain schema changes
- Versioned event types or upcasters can translate older payloads during replay
- Test historical events through the full deserialization and upcasting path before deployment
Expected answer points:
- Aggregate reconstruction replays events from the event stream to build current state
- For each event, the aggregate's apply method updates state accordingly
- Without snapshots, reconstruction time grows linearly with event count
- Snapshots store periodic state checkpoints—reconstruction starts from the nearest snapshot then replays remaining events
- Trade-off: simpler reconstruction vs storage overhead for snapshots
- Choose snapshot intervals from measured reconstruction time and event rate, not a fixed event count
Expected answer points:
- Projections may process the same event multiple times due to retries, consumer group rebalances, or crashes mid-update
- Idempotent handlers ensure duplicate processing produces the same result as single processing
- Persist the processed event ID or version so duplicate deliveries can be recognized after a restart
- Commit the read-model update and checkpoint together when the storage system allows it
- Otherwise make replay safe and advance checkpoints only after durable writes
Build into a separate generation, replay from a documented checkpoint, compare the result with domain invariants, and switch readers only after validation. Keep the previous generation available for rollback until the new model is healthy.
Expected answer points:
- Mental model shift: different from traditional CRUD, requires learning new patterns
- Eventual consistency handling: applications must be designed for stale reads
- Projection rebuild times: large aggregates can be slow to reconstruct without snapshots
- Event schema evolution complexity: upcasters and versioning add operational overhead
- Infrastructure work: event retention, projection retries, replay, backups, and schema evolution
- Team learning: event modeling and recovery need operational ownership
Expected answer points:
- Does durable history or replay solve a concrete product or operating need?
- Can the team operate event retention, projection rebuilds, and schema evolution?
- Can each query tolerate projection lag or use an explicit read-your-writes path?
- If only separate read and write models are needed, start with CQRS over current-state storage instead
Expected answer points:
- Store a versioned state checkpoint periodically so reconstruction replays only newer events
- Choose an interval from measured replay time and aggregate write rate, not a universal event count
- Trade-off: faster reconstruction vs storage overhead for snapshot objects
- Monitor snapshot age and create new snapshots when version gap grows too large
- Consider snapshot frequency based on aggregate event rate and acceptable reconstruction time
Expected answer points:
- Upcasters transform events from old schema versions to new schema versions during replay
- When event schemas change, old events stored in the event store may not deserialize correctly with new code
- Upcaster functions apply transformations to convert old event format to current format
- Typically chained: v1 → v2 → v3 upcasters applied sequentially for older events
- Alternative approach: embed version number in event and handle version branching in apply logic
- Upcasters allow adding new fields with defaults without breaking old events
- Test upcasters by replaying historical events through the full upcaster chain
Expected answer points:
- An aggregate is a cluster of related objects treated as a single unit for data changes
- An implementation often assigns an event stream to each aggregate instance; confirm its storage contract
- Ordering and consistency depend on the stream or partition contract and each writer following the expected-version protocol
- Command handlers load aggregate by replaying its event stream, apply command, emit new events
- Events reference aggregate ID, aggregate version, and contain the domain data that changed
- Keep events for an invariant within the stream or partition whose ordering contract the command handler validates
Expected answer points:
- Ordering is limited to the stream or partition guarantees documented by the chosen store
- Separate aggregates do not have a shared total order by default
- Use explicit coordination and define partial-failure behavior when a workflow spans streams
Expected answer points:
- Show that a command was accepted without claiming a lagging read model already reflects it
- Offer a read-your-writes path or a visible pending state when needed
- Set freshness objectives for views where stale data affects a user decision
- Reconcile optimistic UI state if the command is rejected
Expected answer points:
- Decide how stale a metric may be before it changes a user decision
- Measure projection freshness under representative workload before promising an update time
- Shape the projection around the dashboard's query patterns
- Track freshness and alert when it misses the dashboard's objective
- Choose aggregation and retention rules that match the dashboard questions
Expected answer points:
- Event store contains full history including deleted data—cannot just delete records
- PII in events requires encryption at rest and access controls
- Commands validate authorization; events should not leak sensitive data to unauthorized consumers
- Use separate streams per tenant in multi-tenant systems for isolation
- Implement event masking: transform sensitive fields when replaying to unauthorized consumers
- Audit log of event store access complements the event log itself
- Consider event immutability vs right to be forgotten regulations (GDPR)—requires special handling
Expected answer points:
- Test aggregates by replaying a sequence of events and asserting final state
- Given events [OrderCreated, ItemAdded], when Apply command ConfirmOrder, then emit OrderConfirmed
- Test invalid state transitions: given OrderCancelled, when ConfirmOrder, then reject with InvalidStateTransition
- Projection tests: given events, when projection processes them, then read model matches expected state
- Test idempotency by calling projection handler multiple times with same event and verifying same result
- Integration tests: real event store, real read model, verify rebuild from scratch produces correct state
- Property-based testing: generate random event sequences and verify aggregate invariants hold
Expected answer points:
- Keep current state authoritative and publish changes through a reliable change feed or outbox
- Build one read model, make its updates idempotent, and compare its output with the source
- Switch one query only after the projection is validated and its freshness is understood
- Retain the old path for rollback while monitoring lag and failures
- Event sourcing is separate; add it only when durable history or replay is needed
Expected answer points:
- Back up and restore the event store, snapshots, projection checkpoints, and encryption keys according to the recovery plan
- Rebuild read models from a known stream position, accounting for events appended after the backup
- Snapshots can reduce replay work, but verify them against the stream and keep them versioned
- Replication does not replace tested backup and failover procedures
- Restore into an isolated environment and verify aggregates, projections, and sensitive-data controls
Further Reading
- CQRS Pattern — decide whether separate read and write models solve a problem
- Event-Driven Architecture — how events connect services and support asynchronous workflows
- Distributed Transactions — alternatives and tradeoffs for multi-service consistency
- Change Data Capture — a database-log approach for feeding downstream projections and indexes
- Architecture Decision Records — document the constraints and costs behind a CQRS or event-sourcing choice
- EventStoreDB Documentation - Official documentation for EventStoreDB
- Apache Kafka Documentation - Event streaming platform docs
- Martin Fowler’s CQRS Guide - Conceptual overview
- Event Sourcing Pattern - Azure Architecture Center - trade-offs, stream boundaries, and operational considerations
- Kafka Message Delivery Guarantees - Confluent - delivery semantics and their scope
- Event Sourcing Pattern - AWS - Cloud implementation guide
Conclusion
CQRS and event sourcing solve related but separate problems. This guide focused on event-sourced operations: preserving domain events, making projections retry-safe, and recovering them through replay.
Use event sourcing when durable history or replay has a clear purpose. Plan for schema evolution, privacy, projection lag, and rebuilds. If you only need separate read and write models, CQRS Pattern covers that choice without requiring an event store.
Category
Related Posts
CQRS Pattern
Decide whether separate command and query models solve a real problem, how to begin in one store, and when a read model can tolerate lag.
Event Sourcing
Storing state changes as immutable events. Event store implementation, event replay, schema evolution, and comparison with traditional CRUD approaches.
Amazon Architecture: History and Service Design
Separate documented Amazon and AWS milestones from popular retellings, then apply the lesson about service boundaries to a current request flow.