2026-09-20 · 12 min
Event Sourcing and CQRS: A Practical Node.js Guide for 2026
A wallet service for a fintech client near Pasar Modern BSD was losing transaction state. Not often — maybe twice a week — but each incident required manual SQL patches, a post-mortem, and a very uncomfortable call with their compliance team. The root cause was classic: mutable state, no audit log, and a bug that updated the balance column but skipped writing to the history table. Event sourcing and CQRS would have made that incident impossible by design. State is derived from events; you can’t have balance drift from history because history is the balance.
This guide skips the theory. You can read the Fowler article. What follows is the actual implementation — event store schema, aggregate pattern in TypeScript, projection setup, and the operational tradeoffs that only show up after you’ve run this in production.
The core idea in one paragraph
Instead of storing current state (balance: 50000), you store the sequence of things that happened (MoneyDeposited: 100000, MoneyWithdrawn: 50000). Current state is computed by replaying events. CQRS separates the write path (commands that produce events) from the read path (projections that consume events and build query-optimized views). The write side never has to care about how the data will be queried. The read side never has to care about business rules.
Event store schema in PostgreSQL
EventStoreDB is excellent, but for most services PostgreSQL is the right default. This schema handles optimistic concurrency:
CREATE TABLE events (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
stream_id TEXT NOT NULL, -- e.g. "wallet-uuid-here"
stream_type TEXT NOT NULL, -- e.g. "Wallet"
version INTEGER NOT NULL, -- per-stream sequence
event_type TEXT NOT NULL,
payload JSONB NOT NULL,
metadata JSONB NOT NULL DEFAULT '{}',
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
CONSTRAINT uq_stream_version UNIQUE (stream_id, version)
);
CREATE INDEX idx_events_stream ON events (stream_id, version);
CREATE INDEX idx_events_type ON events (event_type, created_at);
The UNIQUE (stream_id, version) constraint is the optimistic concurrency control. If two concurrent writes try to append version 5 to the same stream, one will win and the other gets a unique constraint violation — which you translate into a concurrency error and retry at the application layer.
Aggregate pattern in TypeScript
// src/domain/wallet/wallet.aggregate.ts
type WalletEvent =
| { type: "WalletCreated"; payload: { ownerId: string; currency: string } }
| { type: "MoneyDeposited"; payload: { amount: number; reference: string } }
| { type: "MoneyWithdrawn"; payload: { amount: number; reference: string } };
interface WalletState {
id: string;
ownerId: string;
balance: number;
currency: string;
version: number;
}
export class WalletAggregate {
private state: WalletState;
private uncommitted: WalletEvent[] = [];
private constructor(state: WalletState) {
this.state = state;
}
static create(id: string, ownerId: string, currency: string): WalletAggregate {
const wallet = new WalletAggregate({
id, ownerId, balance: 0, currency, version: 0,
});
wallet.apply({ type: "WalletCreated", payload: { ownerId, currency } });
return wallet;
}
static fromHistory(id: string, events: WalletEvent[]): WalletAggregate {
const wallet = new WalletAggregate({
id, ownerId: "", balance: 0, currency: "IDR", version: 0,
});
for (const event of events) {
wallet.applyEvent(event, false);
}
return wallet;
}
deposit(amount: number, reference: string): void {
if (amount <= 0) throw new Error("Deposit amount must be positive");
this.apply({ type: "MoneyDeposited", payload: { amount, reference } });
}
withdraw(amount: number, reference: string): void {
if (amount > this.state.balance) {
throw new Error(`Insufficient balance: ${this.state.balance}`);
}
this.apply({ type: "MoneyWithdrawn", payload: { amount, reference } });
}
private apply(event: WalletEvent): void {
this.applyEvent(event, true);
}
private applyEvent(event: WalletEvent, track: boolean): void {
// Pure state transitions — no side effects here
switch (event.type) {
case "WalletCreated":
this.state.ownerId = event.payload.ownerId;
this.state.currency = event.payload.currency;
break;
case "MoneyDeposited":
this.state.balance += event.payload.amount;
break;
case "MoneyWithdrawn":
this.state.balance -= event.payload.amount;
break;
}
this.state.version += 1;
if (track) this.uncommitted.push(event);
}
getUncommittedEvents(): WalletEvent[] { return [...this.uncommitted]; }
clearUncommittedEvents(): void { this.uncommitted = []; }
getState(): Readonly<WalletState> { return { ...this.state }; }
}
Note applyEvent(event, false) when replaying history — events from the store are applied without being added to uncommitted again. This is the distinction that trips up most first implementations.
Saving and loading via the event store
// src/infrastructure/event-store.ts
import { Pool } from "pg";
export class PostgresEventStore {
constructor(private pool: Pool) {}
async append(
streamId: string,
streamType: string,
events: { type: string; payload: unknown }[],
expectedVersion: number
): Promise<void> {
const client = await this.pool.connect();
try {
await client.query("BEGIN");
for (let i = 0; i < events.length; i++) {
const version = expectedVersion + i + 1;
await client.query(
`INSERT INTO events (stream_id, stream_type, version, event_type, payload)
VALUES ($1, $2, $3, $4, $5)`,
[streamId, streamType, version, events[i].type, events[i].payload]
);
}
await client.query("COMMIT");
} catch (err: unknown) {
await client.query("ROLLBACK");
// pg unique violation code
if ((err as { code?: string }).code === "23505") {
throw new Error(`Concurrency conflict on stream ${streamId}`);
}
throw err;
} finally {
client.release();
}
}
async load(streamId: string): Promise<{ type: string; payload: unknown }[]> {
const result = await this.pool.query(
`SELECT event_type, payload FROM events
WHERE stream_id = $1 ORDER BY version ASC`,
[streamId]
);
return result.rows.map((r) => ({ type: r.event_type, payload: r.payload }));
}
}
CQRS: the read side
The write side is done. Now the read side needs its own model. A wallet balance summary for a dashboard doesn’t need to replay events — it reads from a projection table that gets updated asynchronously as events arrive.
-- Projection: wallet balance summaries
CREATE TABLE wallet_summaries (
wallet_id TEXT PRIMARY KEY,
owner_id TEXT NOT NULL,
balance BIGINT NOT NULL DEFAULT 0,
currency TEXT NOT NULL,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
-- Projection checkpoint: tracks where the projector left off
CREATE TABLE projection_checkpoints (
name TEXT PRIMARY KEY,
position BIGINT NOT NULL DEFAULT 0
);
The projector polls for new events (or uses LISTEN/NOTIFY from PostgreSQL — simpler than it sounds) and updates the read model:
// src/projections/wallet-summary.projector.ts
export class WalletSummaryProjector {
constructor(private pool: Pool) {}
async run(): Promise<void> {
const checkpoint = await this.getCheckpoint("wallet_summary");
const events = await this.fetchEventsSince(checkpoint);
for (const event of events) {
const client = await this.pool.connect();
try {
await client.query("BEGIN");
if (event.event_type === "WalletCreated") {
await client.query(
`INSERT INTO wallet_summaries (wallet_id, owner_id, currency)
VALUES ($1, $2, $3)
ON CONFLICT (wallet_id) DO NOTHING`,
[event.stream_id, event.payload.ownerId, event.payload.currency]
);
} else if (event.event_type === "MoneyDeposited") {
await client.query(
`UPDATE wallet_summaries
SET balance = balance + $1, updated_at = NOW()
WHERE wallet_id = $2`,
[event.payload.amount, event.stream_id]
);
} else if (event.event_type === "MoneyWithdrawn") {
await client.query(
`UPDATE wallet_summaries
SET balance = balance - $1, updated_at = NOW()
WHERE wallet_id = $2`,
[event.payload.amount, event.stream_id]
);
}
// Advance checkpoint in the same transaction
await client.query(
`INSERT INTO projection_checkpoints (name, position) VALUES ($1, $2)
ON CONFLICT (name) DO UPDATE SET position = $2`,
["wallet_summary", event.sequence]
);
await client.query("COMMIT");
} catch (err) {
await client.query("ROLLBACK");
throw err;
} finally {
client.release();
}
}
}
}
The checkpoint update inside the same transaction is not optional. It’s what gives you exactly-once semantics when the process restarts.
Snapshots: when replaying gets slow
If a wallet has 100,000 events, loading it means 100,000 rows on every write. That’s when you add snapshots. A snapshot stores the aggregate state at a specific version:
async loadWithSnapshot(walletId: string): Promise<WalletAggregate> {
const snapshot = await this.loadSnapshot(walletId);
const fromVersion = snapshot?.version ?? 0;
const events = await this.eventStore.loadFrom(walletId, fromVersion);
// Rehydrate from snapshot state, then replay only newer events
const wallet = snapshot
? WalletAggregate.fromSnapshot(snapshot.state)
: WalletAggregate.fromHistory(walletId, []);
return WalletAggregate.fromHistory(walletId, events, wallet);
}
Snapshot every N events (100–500 is typical). Write the snapshot in the same transaction as the events when the version crosses the threshold.
What this actually costs you
Event sourcing and CQRS add real complexity. Be honest with yourself about the tradeoffs before committing:
Eventual consistency on the read side. The projection runs asynchronously. There’s a window — usually milliseconds, sometimes seconds under load — where a user deposits money and then immediately checks their balance through the read model and sees the old value. You need to design for this: either use the write-side aggregate state for immediate post-command feedback, or explain to product why showing a slightly stale balance is acceptable (it usually is, once you explain it).
Schema evolution for events. Events are immutable. If you shipped a MoneyDeposited event with an amount field in cents, you can’t retroactively change all events to use rupiah. You version your event schemas and handle multiple versions in your applyEvent switch. This is tedious but manageable. Skipping it is how you end up with a 3 AM migration.
Operational overhead. The event store table grows forever (append-only by design). You need archival strategies, index maintenance, and monitoring on projection lag. None of this is hard, but you’re signing up for it.
For CRUD-heavy services with no audit requirements, this architecture is overkill. For financial systems, inventory, or anything where “how did we get here” is a legitimate business question — it pays off within the first serious incident.
When projections fall behind
Set up monitoring on projection lag from day one. A simple metric:
const lag = currentEventSequence - projectionCheckpoint;
// Alert if lag > 1000 events or > 30 seconds behind real-time
The most common cause of projection lag in production is not slow queries — it’s a projector that crashed and wasn’t restarted. Use a process manager (PM2 with --restart-delay) or run the projector as a Kubernetes Deployment with a liveness probe on checkpoint progression.
The wallet service near BSD that prompted this whole approach has been running on this architecture for eight months now. Zero balance drift incidents. The last audit request from their compliance team was answered by running a single SQL query against the event stream instead of reconstructing history from five different log files. That alone justified the implementation cost.
Ditulis oleh Reza Pradipta