Event Sourcing and CQRS: Event Store, Projections
Event sourcing and CQRS: event store design, aggregate roots, projections, snapshots, eventual consistency, and when to skip the pattern.
Introduction
Event sourcing stores state changes as a sequence of events rather than mutable current state. CQRS separates read and write models — commands modify state, queries read from optimized projections. Together they provide an auditable, replayable, and scalable architecture for complex domains. The following walks through event store design, aggregate roots, projections, read models, snapshots, eventual consistency, and when the pattern is (and isn’t) worth it.
When to Use and When to Skip
Use CQRS + event sourcing when:
- Auditing every state change is a hard requirement (finance, compliance, regulated domains)
- Read and write workloads don’t share access patterns
- You need to rebuild read models without touching the write path
- Temporal queries are real business requirements (“what was the balance on March 15?”)
- Event-driven microservices need a reliable source of truth
Skip it for simple CRUD — the pattern adds real complexity: eventual consistency to manage in the UI, schema evolution to version, projections to maintain, and a second data model to keep consistent. If “audit log” is the only need, a table of changes is a column, not an architecture.
Core Concepts
The write side appends events; the read side projects them into queryable views. Same events, two models — that’s the split.
The event store is the only source of truth: read models are disposable views you can drop and rebuild by replaying the stream. That asymmetry is what makes the pair powerful — you can add a brand-new read model (a reporting table, a search index, a cache) for a feature that didn’t exist when the events were written, and it’s correct by construction.
Event Store
Event schema
CREATE TABLE events (
event_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
event_type VARCHAR(100) NOT NULL,
aggregate_id UUID NOT NULL,
aggregate_type VARCHAR(50) NOT NULL,
event_data JSONB NOT NULL,
metadata JSONB NOT NULL DEFAULT '{}',
version INTEGER NOT NULL,
timestamp TIMESTAMPTZ NOT NULL DEFAULT NOW(),
UNIQUE(aggregate_id, version)
);
CREATE INDEX idx_events_aggregate ON events(aggregate_id, version);
CREATE INDEX idx_events_type ON events(event_type);
CREATE INDEX idx_events_timestamp ON events(timestamp);
Event store implementation
// eventstore/EventStore.ts — Append-only event storage
interface DomainEvent {
eventId: string;
eventType: string;
aggregateId: string;
aggregateType: string;
data: Record<string, any>;
metadata: Record<string, any>;
version: number;
timestamp: Date;
}
class PostgresEventStore {
constructor(private readonly pool: Pool) {}
async append(
aggregateId: string,
events: DomainEvent[],
expectedVersion: number,
): Promise<void> {
const client = await this.pool.connect();
try {
await client.query('BEGIN');
// Optimistic concurrency control
const currentVersion = await this.getCurrentVersion(client, aggregateId);
if (currentVersion !== expectedVersion) {
throw new ConcurrencyError(
`Expected version ${expectedVersion}, got ${currentVersion}`,
);
}
// Append events
for (let i = 0; i < events.length; i++) {
const event = events[i];
event.version = expectedVersion + i + 1;
await client.query(
`INSERT INTO events (event_id, event_type, aggregate_id, aggregate_type, event_data, metadata, version, timestamp)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,
[
event.eventId,
event.eventType,
event.aggregateId,
event.aggregateType,
JSON.stringify(event.data),
JSON.stringify(event.metadata),
event.version,
event.timestamp,
],
);
}
await client.query('COMMIT');
} catch (error) {
await client.query('ROLLBACK');
throw error;
} finally {
client.release();
}
}
async getEvents(
aggregateId: string,
fromVersion: number = 0,
): Promise<DomainEvent[]> {
const result = await this.pool.query(
`SELECT * FROM events WHERE aggregate_id = $1 AND version > $2 ORDER BY version ASC`,
[aggregateId, fromVersion],
);
return result.rows.map(this.mapRowToEvent);
}
async getEventsByType(
eventType: string,
fromTimestamp: Date = new Date(0),
): Promise<DomainEvent[]> {
const result = await this.pool.query(
`SELECT * FROM events WHERE event_type = $1 AND timestamp > $2 ORDER BY timestamp ASC`,
[eventType, fromTimestamp],
);
return result.rows.map(this.mapRowToEvent);
}
private async getCurrentVersion(
client: PoolClient,
aggregateId: string,
): Promise<number> {
const result = await client.query(
`SELECT COALESCE(MAX(version), 0) as version FROM events WHERE aggregate_id = $1`,
[aggregateId],
);
return result.rows[0].version;
}
private mapRowToEvent(row: any): DomainEvent {
return {
eventId: row.event_id,
eventType: row.event_type,
aggregateId: row.aggregate_id,
aggregateType: row.aggregate_type,
data: row.event_data,
metadata: row.metadata,
version: row.version,
timestamp: row.timestamp,
};
}
}
Aggregate Root
// domain/OrderAggregate.ts — Aggregate root that applies events
abstract class AggregateRoot {
protected id: string;
protected version: number = 0;
protected uncommittedEvents: DomainEvent[] = [];
abstract apply(event: DomainEvent): void;
protected raise(event: DomainEvent): void {
this.apply(event);
this.uncommittedEvents.push(event);
}
getUncommittedEvents(): DomainEvent[] {
return this.uncommittedEvents;
}
markEventsAsCommitted(): void {
this.uncommittedEvents = [];
}
getVersion(): number {
return this.version;
}
loadFromHistory(events: DomainEvent[]): void {
for (const event of events) {
this.apply(event);
this.version = event.version;
}
}
}
class OrderAggregate extends AggregateRoot {
private customerId: string | null = null;
private items: OrderItem[] = [];
private status: OrderStatus = 'non-existent';
private totalAmount: number = 0;
// Command: Place order
static place(
orderId: string,
customerId: string,
items: OrderItemInput[],
): OrderAggregate {
const order = new OrderAggregate();
order.id = orderId;
if (items.length === 0) {
throw new Error('Cannot place an empty order');
}
const total = items.reduce((sum, item) => sum + item.price * item.quantity, 0);
order.raise({
eventId: crypto.randomUUID(),
eventType: 'OrderPlaced',
aggregateId: orderId,
aggregateType: 'Order',
data: {
customerId,
items: items.map(i => ({
productId: i.productId,
quantity: i.quantity,
price: i.price,
})),
totalAmount: total,
},
metadata: { correlationId: crypto.randomUUID() },
version: 0,
timestamp: new Date(),
});
return order;
}
// Command: Cancel order
cancel(reason: string): void {
if (this.status !== 'pending' && this.status !== 'processing') {
throw new Error(`Cannot cancel order in ${this.status} state`);
}
this.raise({
eventId: crypto.randomUUID(),
eventType: 'OrderCancelled',
aggregateId: this.id,
aggregateType: 'Order',
data: { reason, previousStatus: this.status },
metadata: {},
version: this.version,
timestamp: new Date(),
});
}
// Command: Ship order
ship(trackingNumber: string): void {
if (this.status !== 'processing') {
throw new Error(`Cannot ship order in ${this.status} state`);
}
this.raise({
eventId: crypto.randomUUID(),
eventType: 'OrderShipped',
aggregateId: this.id,
aggregateType: 'Order',
data: { trackingNumber },
metadata: {},
version: this.version,
timestamp: new Date(),
});
}
// Apply events to rebuild state
apply(event: DomainEvent): void {
switch (event.eventType) {
case 'OrderPlaced':
this.customerId = event.data.customerId;
this.items = event.data.items;
this.status = 'pending';
this.totalAmount = event.data.totalAmount;
break;
case 'OrderCancelled':
this.status = 'cancelled';
break;
case 'OrderShipped':
this.status = 'shipped';
break;
case 'OrderCompleted':
this.status = 'completed';
break;
}
this.version = event.version;
}
}
Command Handler
// application/OrderCommandHandler.ts — Process commands, save events
class OrderCommandHandler {
constructor(
private readonly eventStore: PostgresEventStore,
private readonly eventBus: EventBus,
) {}
async handlePlaceOrder(command: PlaceOrderCommand): Promise<string> {
const orderId = crypto.randomUUID();
// Create aggregate and apply command
const order = OrderAggregate.place(
orderId,
command.customerId,
command.items,
);
// Persist events
await this.eventStore.append(
orderId,
order.getUncommittedEvents(),
0, // expected version for new aggregate
);
// Publish events to bus for projections
for (const event of order.getUncommittedEvents()) {
await this.eventBus.publish(event);
}
order.markEventsAsCommitted();
return orderId;
}
async handleCancelOrder(command: CancelOrderCommand): Promise<void> {
// Load aggregate from history
const events = await this.eventStore.getEvents(command.orderId);
if (events.length === 0) {
throw new Error('Order not found');
}
const order = new OrderAggregate();
order.loadFromHistory(events);
// Apply command
order.cancel(command.reason);
// Persist new events
const currentVersion = order.getVersion() - order.getUncommittedEvents().length;
await this.eventStore.append(
command.orderId,
order.getUncommittedEvents(),
currentVersion,
);
// Publish events
for (const event of order.getUncommittedEvents()) {
await this.eventBus.publish(event);
}
order.markEventsAsCommitted();
}
}
Projections and Read Models
// projections/OrderProjection.ts — Build read model from events
class OrderProjection {
constructor(private readonly readDb: ReadDatabase) {}
async handle(event: DomainEvent): Promise<void> {
switch (event.eventType) {
case 'OrderPlaced':
await this.readDb.execute(
`INSERT INTO read_orders (id, customer_id, status, total_amount, item_count, created_at)
VALUES ($1, $2, $3, $4, $5, $6)`,
[
event.aggregateId,
event.data.customerId,
'pending',
event.data.totalAmount,
event.data.items.length,
event.timestamp,
],
);
// Insert order items
for (const item of event.data.items) {
await this.readDb.execute(
`INSERT INTO read_order_items (order_id, product_id, quantity, price)
VALUES ($1, $2, $3, $4)`,
[event.aggregateId, item.productId, item.quantity, item.price],
);
}
break;
case 'OrderCancelled':
await this.readDb.execute(
`UPDATE read_orders SET status = $1, cancelled_at = $2 WHERE id = $3`,
['cancelled', event.timestamp, event.aggregateId],
);
break;
case 'OrderShipped':
await this.readDb.execute(
`UPDATE read_orders SET status = $1, shipped_at = $2, tracking_number = $3 WHERE id = $4`,
['shipped', event.timestamp, event.data.trackingNumber, event.aggregateId],
);
break;
case 'OrderCompleted':
await this.readDb.execute(
`UPDATE read_orders SET status = $1, completed_at = $2 WHERE id = $3`,
['completed', event.timestamp, event.aggregateId],
);
break;
}
}
}
// Wire projection to event bus
eventBus.subscribe('OrderPlaced', orderProjection);
eventBus.subscribe('OrderCancelled', orderProjection);
eventBus.subscribe('OrderShipped', orderProjection);
eventBus.subscribe('OrderCompleted', orderProjection);
Handling out-of-order events
Events can reach a projection out of order when they travel over partitioned buses or get retried. Each projection stores the last version it applied per stream: an event with a lower version is skipped, and one that leaves a gap gets buffered until the missing events arrive. When the read model doesn’t depend on ordering — counters, presence flags — plain idempotent upserts are enough and no buffering is needed. On Kafka, partitioning by aggregateId keeps per-aggregate order for free, so out-of-order handling only matters across aggregates.
Query Handler
// application/OrderQueryHandler.ts — Read from optimized read models
class OrderQueryHandler {
constructor(private readonly readDb: ReadDatabase) {}
async getOrderById(query: GetOrderByIdQuery): Promise<OrderView | null> {
const result = await this.readDb.query(
`SELECT * FROM read_orders WHERE id = $1`,
[query.orderId],
);
return result.rows[0] || null;
}
async getOrdersByCustomer(query: GetOrdersByCustomerQuery): Promise<OrderView[]> {
const result = await this.readDb.query(
`SELECT * FROM read_orders WHERE customer_id = $1 ORDER BY created_at DESC LIMIT $2 OFFSET $3`,
[query.customerId, query.limit, query.offset],
);
return result.rows;
}
async getOrderStatistics(query: GetOrderStatisticsQuery): Promise<OrderStatistics> {
const result = await this.readDb.query(
`SELECT
COUNT(*) as total_orders,
COUNT(CASE WHEN status = 'completed' THEN 1 END) as completed,
COUNT(CASE WHEN status = 'cancelled' THEN 1 END) as cancelled,
COALESCE(SUM(CASE WHEN status = 'completed' THEN total_amount END), 0) as revenue
FROM read_orders
WHERE created_at BETWEEN $1 AND $2`,
[query.from, query.to],
);
return result.rows[0];
}
}
Eventual Consistency
The read model always lags the event store — plan for it in the UI instead of pretending it doesn’t happen:
| Strategy | When to use |
|---|---|
| Polling | Simple UI with low latency requirements |
| WebSockets / SSE | Real-time UI updates (dashboards, live order status) |
| Return projection ID | Let the client poll the read model directly — 202 Accepted + a checkStatusAt URL |
| Synchronous projection | Only for critical paths with low volume — couples write latency to read write |
// Option: return read model location after the command
async function placeOrder(command: PlaceOrderCommand) {
const orderId = await commandBus.send(command);
return {
status: 202,
body: { message: 'Order processing', checkStatusAt: `/orders/${orderId}` },
};
}
Schema Evolution
Events outlive the code that wrote them, so evolve schemas compatibly:
- Add optional fields — never remove or rename (same rule as any durable schema)
- Never modify stored events — they’re the audit trail
- Use upcasters when reading old events: transform
OrderPlacedv1 into the current shape before applying it to the aggregate - For breaking changes, mint a new event type (
OrderPlacedV2) and keep both in the store until aggregates on v1 are archived — consumers handle both during the transition - Document each change in an event catalog so consumers know which versions to expect
// Upcaster — transform v1 events on read
function upcast(event: DomainEvent): DomainEvent {
if (event.eventType === 'OrderPlaced' && event.data.currency === undefined) {
return { ...event, data: { ...event.data, currency: 'USD' } }; // v1 had no currency
}
return event;
}
Snapshots
Replaying an aggregate’s full history on every load doesn’t scale — an account with 10.000 events takes seconds to hydrate. Snapshots checkpoint the state at a version: load the latest snapshot, replay only events after it. Pick the interval by stream length distribution — every 100-500 events is typical; the banking example uses 500 because power users hit 5.000+ events while the average account stays under 120.
// snapshots/SnapshotStore.ts — Optimize aggregate loading for long event streams
class SnapshotStore {
constructor(private readonly db: Database) {}
async save(aggregateId: string, snapshot: AggregateSnapshot): Promise<void> {
await this.db.query(
`INSERT INTO snapshots (aggregate_id, aggregate_type, version, state, created_at)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (aggregate_id, version) DO NOTHING`,
[
aggregateId,
snapshot.aggregateType,
snapshot.version,
JSON.stringify(snapshot.state),
new Date(),
],
);
}
async getLatest(aggregateId: string): Promise<AggregateSnapshot | null> {
const result = await this.db.query(
`SELECT * FROM snapshots WHERE aggregate_id = $1 ORDER BY version DESC LIMIT 1`,
[aggregateId],
);
return result.rows[0] || null;
}
}
// Load aggregate with snapshot optimization
class OrderRepository {
constructor(
private readonly eventStore: PostgresEventStore,
private readonly snapshotStore: SnapshotStore,
) {
this.snapshotInterval = 100; // Save snapshot every 100 events
}
async load(orderId: string): Promise<OrderAggregate> {
// Try loading from snapshot first
const snapshot = await this.snapshotStore.getLatest(orderId);
let order = new OrderAggregate();
let fromVersion = 0;
if (snapshot) {
order = Object.assign(new OrderAggregate(), snapshot.state);
fromVersion = snapshot.version;
}
// Load remaining events after snapshot
const events = await this.eventStore.getEvents(orderId, fromVersion);
order.loadFromHistory(events);
return order;
}
async save(order: OrderAggregate): Promise<void> {
const events = order.getUncommittedEvents();
const baseVersion = order.getVersion() - events.length;
await this.eventStore.append(order.id, events, baseVersion);
// Save snapshot if interval reached
if (order.getVersion() % this.snapshotInterval === 0) {
await this.snapshotStore.save(order.id, {
aggregateType: 'Order',
version: order.getVersion(),
state: { ...order },
});
}
order.markEventsAsCommitted();
}
}
Real-World Scenario: Banking Ledger
A concrete example shows why the pattern earns its complexity. A banking ledger needs full audit trails, temporal queries, and regulatory compliance — the event sourcing sweet spot:
System: Account ledger (C# + .NET + PostgreSQL + Elasticsearch)
Volume: 2M accounts, 50M transactions/year
Event store schema (PostgreSQL):
events(event_id, stream_id, version, event_type, payload JSONB,
metadata JSONB, occurred_at, UNIQUE(stream_id, version))
Domain events:
AccountOpened, MoneyDeposited, MoneyWithdrawn,
TransferInitiated, TransferCompleted, AccountClosed
Snapshot strategy:
- Snapshot every 500 events per account
- On load: latest snapshot + events after snapshot version
- Average account: ~120 events (no snapshot needed)
- Power users: 5.000+ events (snapshot saves ~4.5s load time)
Read model: Elasticsearch (denormalized for queries)
Index accounts: { accountId, customerId, balance, status, lastTransactionAt }
Index transactions: { accountId, type, amount, balanceAfter, occurredAt }
The temporal query becomes trivial — replay events up to a date and fold them into state, no special tables needed:
// "What was the balance of account ABC-123 on March 15, 2026?"
public async Task<decimal> GetBalanceAt(Guid accountId, DateTime date)
{
var events = await _eventStore.ReadStreamAsync($"account-{accountId}", until: date);
var account = Account.FromHistory(events);
return account.Balance;
}
Compliance falls out for free: every transaction is an immutable event (audit by design), quarterly exports to cold storage cover retention, upcasters keep old events readable, and PII sits encrypted in payloads with envelope encryption.
Real-World Scenario: Flight Reservations
A second example shows the audit side of the pattern. A reservation system handles 5.000 bookings and 200 cancellations a day, and disputes are routine — “the passenger says they never cancelled.” The event stream is the answer, not a log table:
System: Flight reservations (TypeScript + Node.js + PostgreSQL)
Volume: 5.000 reservations/day, 200 cancellations/day
Requirement: full audit trail, state replay for disputes
Domain events:
ReservationCreated, SeatSelected, PaymentAdded, ReservationConfirmed,
SeatChanged, BaggageAdded, ReservationCancelled
Stream IDs: reservation-{reservationId} (string, not UUID)
Snapshot strategy:
- Snapshot every 20 events — reservations stay short-lived
- Average stream: ~5 events (no snapshot ever fires)
- Compare: the banking ledger snapshots every 500
The dispute resolves itself on replay: loading reservation-RES-456 shows ReservationCreated → PaymentAdded → ReservationConfirmed → ReservationCancelled with reason: "passenger_request" and metadata.agentId: "AG-789" — who cancelled, when, and why, without a single audit table. If the cancellation came from overbooking automation, metadata.autoOverbook says so.
Two details worth stealing:
SeatChangedis a no-op when the new seat equals the current one — the aggregate stays idempotent even if the client retries the command.- Stream IDs are strings (
reservation-{id}), not aggregate UUIDs — human-readable streams make support queries and partition routing easier.
Best Practices
- Make events immutable and append-only — never update or delete events
- Use optimistic concurrency control — version numbers prevent conflicting writes
- Keep events small and focused — one event per state change, not a batch
- Use snapshots for long-lived aggregates — loading thousands of events is slow
- Make projections idempotent — replaying events should produce the same read model
- Use separate databases for write and read sides — scale independently
- Version your events — schema evolution requires upcasters for old events
- Use metadata for tracing — correlation IDs, causation IDs, user IDs
- Don’t expose events in the API — events are internal, expose read models
- Test projections by replaying events — verify read model consistency
Common Mistakes
- Updating or deleting events: events are the source of truth. Corrections are compensating events, not edits.
- No optimistic concurrency: concurrent commands corrupt state. Use version-based conflict detection.
- Projections not idempotent: replaying events creates duplicates. Use upserts or event ID tracking.
- Loading full event stream without snapshots: aggregates with thousands of events are slow. Use snapshots.
- Business logic in projections: projections should only translate events to read models. No domain rules.
- Sharing database between write and read: defeats the purpose of CQRS. Use separate stores.
- No versioning strategy: event schemas evolve; without upcasters or versioned event types, old events become unreadable.
- Over-engineering simple CRUD: CQRS + ES is heavy machinery — most domains don’t justify the operational cost.
- Large aggregates: an aggregate that generates hundreds of events per day replays slowly and snapshots poorly — split by bounded context first.
See Also
- EventStoreDB documentation — dedicated event store with projections and subscriptions
- Microservices.io — Event Sourcing and CQRS patterns
- Microsoft — Event Sourcing pattern
- Complete Guide to Event-Driven Systems — sagas, outbox, idempotency around the event stream
- Event-driven companion on GitHub — event store, aggregate, projection, snapshot code
Frequently Asked Questions
What is event sourcing?
An architecture where state changes are stored as a sequence of immutable events. The current state is derived by replaying events. That gives you a full audit trail, time-travel queries, and event replay for rebuilding read models.
What is CQRS?
Command Query Responsibility Segregation. Write operations (commands) and read operations (queries) use separate models. Commands go through the aggregate root and event store. Queries read from optimized projections. Each side scales and gets optimized independently.
What is a projection?
A handler that listens to domain events and updates a read model. Projections translate the event stream into query-optimized tables/documents. Each projection builds its own read model from the same events.
What is a snapshot?
A saved copy of an aggregate's state at a specific version. Snapshots avoid loading the full event stream when rebuilding an aggregate. Typically saved every N events (e.g., every 100). The aggregate loads from the latest snapshot plus any events after it.
When should I use event sourcing?
When you need a full audit trail, temporal queries (what was the state at time X), complex domain logic with invariants, or event-driven integration with other systems. Avoid it for simple CRUD applications where the overhead outweighs the benefits.
Can I use CQRS without event sourcing?
Yes — CQRS only requires separate read and write models. The write side can use a traditional relational model while reads go to optimized projections. Event sourcing is one way to feed the projections, not a requirement. They pair well, but each is valid alone.
What database should I use for the event store?
PostgreSQL with JSONB works well for moderate scale — it's where most teams start and often where they stay. For high throughput or multi-node setups, use specialized stores like EventStoreDB or Axon Server. Whatever you choose, the UNIQUE(stream_id, version) constraint and the optimistic concurrency check are non-negotiable.
How do I handle event schema changes?
Version your events and use upcasters — when reading old events, transform them to the current schema before applying. Never modify stored events. For breaking changes, create a new event type (e.g., OrderPlacedV2) and keep both versions until old aggregates are archived.
How do I delete personal data under GDPR when events are immutable?
You don't delete the events — you make the payload unreadable. Encrypt personal data per aggregate with its own key; to "erase" the person, destroy the key (crypto-erasure). The event stays, the data is gone. The alternative is modeling deletion as an event (DataAnonymized) that projections interpret by scrubbing the read models — the store keeps the fact, not the data.
How do I test an event-sourced aggregate?
Assert on emitted events, not on resulting state: given a history of events, when a command executes, then a specific set of events should be raised. The same given/when/then list doubles as living documentation of the aggregate's rules — given OrderPlaced, when cancel(), then OrderCancelled says more than any test name.
Related Resources
Modular Monolith: Module Boundaries, Shared Kernel
Design a modular monolith with clear module boundaries, a shared kernel, dependency rules, and a migration path to microservices when scale demands it.
PatternEvent Sourcing Pattern
Store the state of an application as a sequence of events rather than storing only the current state. An architectural pattern for audit-friendly systems.
GuideComplete Guide to Event-Driven Systems
Design event-driven backends: event sourcing, CQRS, sagas, outbox pattern, idempotency, eventual consistency, and production patterns.
PatternCQRS Pattern
Separate read and write models to optimize each for its own workload — when CQRS pays off, when it's overkill, and how it pairs with event sourcing.
PatternOutbox Pattern: Reliable Event Publishing
Reliably publish domain events by persisting them in an outbox table within the same database transaction as the business operation.
PatternEvent Bus Pattern: Decoupled Pub/Sub Messaging
Decouple components by routing events through a central bus. A behavioral pattern for loosely coupled communication between modules.