We are going to explain Event Sourcing and CQRS, covering the requested topics with code and architecture sketches.
Note: We'll use a simple example of an online auction system for illustration.
Event Sourcing: Instead of storing the current state of an entity, we store a sequence of events (state changes). The state is derived by replaying the events.
CQRS (Command Query Responsibility Segregation): Separates read and write operations. Commands change state, queries read state. Often used with event sourcing.
Let's break down:
1. Command → Event Flows
In a CQRS and event-sourced system:
A command (e.g., PlaceBid) is sent to the system.
The command is validated and then translated into one or more events (e.g., BidPlaced).
Events are stored in an append-only log (event store) and published for further processing.
The event store must be durable and provide atomic appends.
3. Read Models and Projections
Because we store events, querying the current state directly from events can be inefficient.
We build read models (projections) by subscribing to events and updating a read-optimized store (e.g., a relational database, document store, or in-memory cache).
Projections are updated asynchronously (eventually consistent) or synchronously (if we need strong consistency for that projection).
Example: For an auction, we might have a read model that shows the current highest bid and the bidder.
Projection code (simplified):
javascript
// This function would be called for each event that affects the auction's current bid.
function updateCurrentBidProjection(event, currentProjection) {
switch (event.type) {
case 'AuctionCreated':
return {
auctionId: event.data.auctionId,
currentBid: event.data.startingPrice,
currentBidder: null,
// ... other fields
};
case 'BidPlaced':
if (event.data.amount > currentProjection.currentBid) {
return {
...currentProjection,
currentBid: event.data.amount,
currentBidder: event.data.bidderId
};
}
return currentProjection;
// ... other events
default:
return currentProjection;
}
}
The projection state is stored in a separate read database (e.g., PostgreSQL table auction_current_bids).
4. Idempotency and Replay
Events must be idempotent: processing the same event multiple times should have the same effect as processing it once.
Because we store events, we can replay them to rebuild the state (for debugging, rebuilding projections, or changing the projection logic).
When replaying, we must be cautious about side effects (e.g., sending notifications). We might need to mark events as processed or use idempotency keys.
For example, when rebuilding a projection, we might clear the projection and then replay all events. But if the projection has side effects (like sending an email on a BidPlaced event), we must avoid resending. Therefore, side effects should be decoupled (e.g., by having a separate process that tracks which events have been processed for side effects).
5. Snapshotting
Replaying all events for an aggregate with a long history can be slow. We can take snapshots of the aggregate state at a certain event number.
When loading an aggregate, we load the latest snapshot and then replay events after that snapshot.
Example: After every 100 events, we take a snapshot of the auction aggregate (with its current state, e.g., current bid, status, etc.). Then, when we need to load the auction, we load the snapshot and then replay events after the snapshot.
Eventual consistency is common because projections are updated asynchronously.
We can have strong consistency for the write side (the aggregate's state is consistent because we process commands one at a time per aggregate) but the read side might be stale.
We can also use synchronous projection updates for specific reads that require up-to-date data (but that might reduce performance).
Example: When a bid is placed, the write side (the auction aggregate) updates immediately. The read model that shows the current bid might be updated a few milliseconds later (asynchronous projection). If we need to show the current bid immediately after placing, we might read from the aggregate (but that breaks CQRS) or wait for the projection to update (or use a synchronous projection).
7. Evolution and Versioning
Events are part of the contract between the past and the future. They must be versioned and handled carefully.
When an event's structure changes, we might have to handle multiple versions (upcasting) when reading old events.
Example: Suppose we have a BidPlaced event that initially had { bidderId, amount } and then we add a timestamp. We must handle both:
javascript
function upcastBidPlacedV1(event) {
// event.data is { bidderId, amount }
return {
...event,
data: {
...event.data,
timestamp: new Date(0) // or some default, but better to have a migration strategy
}
};
}
We might store events with a version number and upcast them to the latest version when reading.
8. Scaling
Write side: Aggregates can be scaled by partitioning by aggregate ID (sharding). But note: an aggregate must be processed in order, so all events for the same aggregate go to the same partition.
Read side: Projections can be scaled by having multiple instances of the projection processor (but then we must be cautious about ordering and idempotency). Often, we partition by aggregate ID and have one projection processor per partition.
Event store: Can be scaled by partitioning (sharding) by aggregate ID.
9. Testing
Unit tests for aggregates: test that given a sequence of events, the aggregate produces the correct next events and state changes.
Integration tests: test the command handler and event store.
Projection tests: test that given a sequence of events, the projection produces the correct read model state.
End-to-end tests: simulate the entire flow.
Example unit test for an auction aggregate (using a testing framework like Jest):
javascript
test('should place a bid if higher than current', () => {
const auction = new Auction(auctionId, sellerId, startingPrice);
auction.placeBid(bidderId, higherAmount);
expect(auction.uncommittedEvents).toHaveLength(1);
expect(auction.uncommittedEvents[0].type).toBe('BidPlaced');
});
+----------------+ +----------------+ +----------------+
| Command | | Command | | Event |
| API (HTTP) | ---> | Handler | ---> | Store |
+----------------+ +----------------+ +----------------+
|
| (publishes events)
v
+----------------+
| Projection |
| Processors |
+----------------+
|
| (updates read DB)
v
+----------------+
| Read Model |
| Database |
+----------------+
|
v
+----------------+
| Query API |
+----------------+
Steps:
Client sends a command to the Command API.
Command Handler validates and processes the command, producing events.
Events are stored in the Event Store (append-only) and published (e.g., via a message broker or the event store's subscription mechanism).
Projection processors (which can be separate services) consume events and update the read model database.
Query API reads from the read model database.
Note: There can be multiple projection processors for different read models.
Code Sketches
We'll write very simplified code in JavaScript (Node.js) for illustration.
Aggregate Example:
javascript
class Auction {
constructor(id, sellerId, startingPrice) {
this.id = id;
this.sellerId = sellerId;
this.currentBid = startingPrice;
this.currentBidder = null;
this.status = 'ACTIVE';
this.uncommittedEvents = [];
}
placeBid(bidderId, amount) {
if (this.status !== 'ACTIVE') {
throw new Error('Auction is not active');
}
if (amount <= this.currentBid) {
throw new Error('Bid must be higher than current bid');
}
this.currentBid = amount;
this.currentBidder = bidderId;
this.uncommittedEvents.push({
type: 'BidPlaced',
data: { auctionId: this.id, bidderId, amount }
});
}
// Other methods...
}
Command Handler:
javascript
async function handlePlaceBid(command, eventStore) {
// Load aggregate from event store (including snapshots if available)
const auction = await eventStore.loadAggregate(command.auctionId, Auction);
// Execute command on aggregate
auction.placeBid(command.bidderId, command.amount);
// Get uncommitted events and save them
const events = auction.uncommittedEvents;
await eventStore.saveEvents(auction.id, events, auction.version);
// Optionally, publish events (if event store doesn't do it automatically)
// eventStore.publish(events);
}
Event Store Interface (simplified):
javascript
class EventStore {
async loadAggregate(aggregateId, AggregateClass) {
// Load events for aggregateId from the store, order by sequence.
// If snapshot exists, load snapshot and then events after the snapshot.
// Then reconstruct the aggregate by applying events.
}
async saveEvents(aggregateId, events, expectedVersion) {
// Append events to the log for aggregateId, with sequence numbers.
// Check expectedVersion for optimistic concurrency (if needed).
}
}
Projection Processor:
javascript
class CurrentBidProjection {
constructor(readDatabase) {
this.readDb = readDatabase;
}
async processEvent(event) {
switch (event.type) {
case 'AuctionCreated':
await this.readDb.saveCurrentBid({
auctionId: event.data.auctionId,
currentBid: event.data.startingPrice,
currentBidder: null
});
break;
case 'BidPlaced':
const current = await this.readDb.getCurrentBid(event.data.auctionId);
if (event.data.amount > current.currentBid) {
await this.readDb.updateCurrentBid(event.data.auctionId, {
currentBid: event.data.amount,
currentBidder: event.data.bidderId
});
}
break;
// ... other events
}
}
}
Event sourcing and CQRS provide many benefits (audit trail, temporal queries, decoupling) but also introduce complexity (eventual consistency, event versioning, replay). They are suited for domains with complex business logic and where the audit trail is valuable.
This is a high-level overview. Each topic could be expanded further.
I'll provide a comprehensive explanation of Event Sourcing and CQRS with architectural sketches and code examples. Let's break this down systematically.
Core Concepts Overview
mermaid
graph LR
A[Command] --> B[Command Handler]
B --> C[Validation & Business Logic]
C --> D[Event Generation]
D --> E[Event Store]
E --> F[Event Publishers]
F --> G[Projections/Read Models]
G --> H[Query API]
E --> I[Event Replay/Snapshots]
// Domain Events
interface Event {
readonly id: string;
readonly type: string;
readonly aggregateId: string;
readonly version: number;
readonly timestamp: Date;
readonly payload: any;
}
// Example Events
class BidPlaced implements Event {
type = 'BidPlaced';
constructor(
public readonly aggregateId: string,
public readonly payload: {
bidderId: string;
amount: number;
timestamp: Date;
},
public readonly version: number
) {}
}
class AuctionStarted implements Event {
type = 'AuctionStarted';
constructor(
public readonly aggregateId: string,
public readonly payload: {
sellerId: string;
startingPrice: number;
title: string;
},
public readonly version: number
) {}
}
// Command
class PlaceBid {
constructor(
public readonly auctionId: string,
public readonly bidderId: string,
public readonly amount: number
) {}
}
// Aggregate Root
class Auction {
private uncommittedEvents: Event[] = [];
private state: AuctionState;
constructor(private readonly id: string, initialState: AuctionState) {
this.state = initialState;
}
applyEvent(event: Event): void {
// Apply event to state (rehydration)
switch (event.type) {
case 'AuctionStarted':
this.state = {
...this.state,
sellerId: event.payload.sellerId,
startingPrice: event.payload.startingPrice,
currentBid: event.payload.startingPrice,
status: 'ACTIVE'
};
break;
case 'BidPlaced':
this.state.currentBid = event.payload.amount;
this.state.highestBidder = event.payload.bidderId;
break;
}
}
placeBid(command: PlaceBid): void {
if (this.state.status !== 'ACTIVE') {
throw new Error('Auction is not active');
}
if (command.amount <= this.state.currentBid) {
throw new Error('Bid must be higher than current bid');
}
const event = new BidPlaced(
this.id,
{
bidderId: command.bidderId,
amount: command.amount,
timestamp: new Date()
},
this.state.version + 1
);
this.applyEvent(event);
this.uncommittedEvents.push(event);
}
getUncommittedEvents(): Event[] {
return this.uncommittedEvents;
}
clearUncommittedEvents(): void {
this.uncommittedEvents = [];
}
}
2. Append-Only Logs & Serialization
Event Store Schema
sql
-- PostgreSQL example
CREATE TABLE events (
id UUID PRIMARY KEY,
aggregate_id VARCHAR(255) NOT NULL,
sequence BIGINT NOT NULL,
type VARCHAR(100) NOT NULL,
payload JSONB NOT NULL,
metadata JSONB,
timestamp TIMESTAMPTZ DEFAULT NOW(),
UNIQUE(aggregate_id, sequence)
);
CREATE INDEX idx_events_aggregate_id ON events(aggregate_id);
CREATE INDEX idx_events_timestamp ON events(timestamp);
CREATE INDEX idx_events_type ON events(type);
graph TD
A[Command] --> B[Write DB - Strong Consistency]
B --> C[Event Store]
C --> D[Async Projection]
D --> E[Read DB - Eventual Consistency]
F[Read Query] --> E
style B fill:#e1f5fe
style E fill:#fce4ec