Wise Hustlers — Digital Product & App Development Studio Logo
Get Consultation
By Wise Hustler Admin•11/24/2026•24 min read

Event Sourcing and CQRS at Scale: PostgreSQL vs EventStoreDB vs Apache Kafka Architecture

Event Sourcing and CQRS at Scale: PostgreSQL vs EventStoreDB vs Apache Kafka Architecture

# Event Sourcing PostgreSQL vs EventStoreDB vs Kafka: CQRS Architecture at Scale

Summary: Choosing between PostgreSQL, EventStoreDB, and Kafka for event sourcing determines system throughput, consistency guarantees, and operational complexity. While PostgreSQL provides transactional simplicity for moderate aggregate volumes, EventStoreDB delivers purpose-built catch-up projections and sub-millisecond stream writes at scale. Conversely, Kafka is an enterprise streaming fabric; using it as an aggregate store introduces concurrency races and partition bottlenecks.

---

Aggregate Boundaries vs Enterprise Streaming Fabrics

In distributed systems design, engineering teams often conflate two fundamentally distinct architectural patterns: the Aggregate Event Store (the source of truth for command processing within an individual bounded context) and the Enterprise Event Streaming Fabric (the asynchronous broadcast bus connecting multiple bounded contexts).

When software architects fail to distinguish between these two roles, they routinely select the wrong storage engine, leading to corrupted aggregate boundaries, catastrophic partition explosion, or unmanageable operational complexity.

flowchart TD
    subgraph Client["Write Request"]
        CMD["Command: SubmitOrder(id=42, items=[...])"]
    end

    subgraph AggregateStore["Aggregate Event Store (OLTP Boundary)"]
        direction TB
        REHYDRATE["1. Read Stream forward: order-42\nEvents v1..v5"]
        AGG["2. State Rehydration in Domain Model\nVerify invariants & business rules"]
        OCC["3. Optimistic Concurrency Control\nExpected Version == 5"]
        APPEND["4. Atomic Append: OrderSubmitted(v6)"]
        
        REHYDRATE --> AGG --> OCC --> APPEND
    end

    subgraph LocalProjection["Local CQRS Projections (Query Model)"]
        SUB["Catch-Up Subscription (Position: 14208)"]
        READ_DB[("Read Model DB\nPostgreSQL Materialized View / Elastic")]
        SUB --> READ_DB
    end

    subgraph CDC["Bridge: Outbox / Change Data Capture"]
        DEBEZIUM["Debezium / Transaction Log Tailer\nRead committed WAL chunks"]
    end

    subgraph Fabric["Enterprise Streaming Fabric (Broadcast Layer)"]
        KAFKA["Apache Kafka Topic: orders.v1\nCoarse Partitions (Key: CustomerId or OrderId)\nBroadcast to Downstream Microservices"]
    end

    subgraph Downstream["Decoupled Microservices"]
        BILLING["Billing Service Consumer Group"]
        SHIPPING["Shipping Service Consumer Group"]
        ANALYTICS["Data Lake / ClickHouse Ingest"]
    end

    CMD --> REHYDRATE
    APPEND -.->|New Event Committed| SUB
    APPEND -.->|Commit Log| DEBEZIUM
    DEBEZIUM -->|Publish Pub/Sub Event| KAFKA
    KAFKA --> BILLING
    KAFKA --> SHIPPING
    KAFKA --> ANALYTICS

The Mechanics of an Aggregate Event Store

An aggregate event store is an operational database specifically structured around Domain-Driven Design (DDD) aggregate boundaries. In this model:

  • Unit of Granularity: Every aggregate root instance (for example, Order-98234 or UserAccount-1102) possesses its own discrete, append-only event stream.
  • Cardinality: The system must sustain tens of millions to billions of concurrent streams.
  • Read Path: The primary read access pattern is stream rehydration: reading all events sequentially for a single stream ID from version 0 to current version to rebuild state in memory.
  • Write Path: Appends are guarded by optimistic concurrency control (OCC). The write operation asserts: "Append this event to stream `X` if and only if the stream's current version matches `expected_version`." If another process committed an event in the interim, the transaction fails immediately, preventing conflicting state transitions.
  • Read Model Generation: Background projection workers stream events sequentially using checkpointed catch-up subscriptions to build specialized read models (CQRS query side).

The Mechanics of an Enterprise Event Streaming Fabric

An enterprise event streaming fabric, typified by Apache Kafka, solves a completely different architectural problem: high-throughput, ordered distribution of events across decoupled services.

  • Unit of Granularity: Data is organized into broad, coarse topics (e.g., telemetry-events, order-lifecycle-events).
  • Cardinality: Topics are composed of a fixed, pre-allocated number of partitions (typically 12 to 256 per topic). Partitions are heavy OS-level abstractions tied directly to open file descriptors, memory buffers, and consumer thread concurrency.
  • Access Pattern: Consumers read continuous batch sequences across partitions via offset pointers. It is designed for parallel fan-out consumption rather than point-lookup stream rehydration.
  • State Semantics: The broker enforces sequential offset ordering per partition, but it has no native domain aggregate awareness or conditional state-version checking.

When engineering domain-driven architectures with high write volume, organizations often partner with specialized teams like Wise Hustlers for custom software development services to implement verified transactional boundaries and zero-data-loss projection pipelines. Understanding where aggregate consistency ends and pub/sub distribution begins is the single most critical decision in event-driven engineering.

---

PostgreSQL as an Event Store: Production Schema and Concurrency Trace

PostgreSQL is often the premier candidate for engineering teams adopting CQRS and event sourcing. Its strict ACID compliance, MVCC semantics, battle-tested operational tooling (pgBackRest, Patroni), and powerful JSONB capabilities allow teams to implement a production-grade event store without adding new distributed infrastructure to their stack.

However, treating PostgreSQL as an event store requires strict adherence to the postgresql event store jsonb append only pattern, bypassing typical relational normalization in favor of an immutable append log with explicit concurrency barriers.

Append-Only Relational Schema with JSONB Payloads

To build an aggregate store in PostgreSQL, we isolate stream metadata from event records. This avoids locking the append log while guaranteeing aggregate stream integrity.

-- Schema for High-Throughput PostgreSQL Event Store
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

-- Stream Registry: Tracks aggregate streams and their current monotonic version
CREATE TABLE event_streams (
    stream_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    stream_name VARCHAR(255) NOT NULL,
    stream_type VARCHAR(128) NOT NULL,
    current_version BIGINT NOT NULL DEFAULT 0,
    created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),
    CONSTRAINT uq_event_streams_name UNIQUE (stream_name)
);

-- Append-Only Event Log: Stores immutable event records
CREATE TABLE event_records (
    global_position BIGSERIAL PRIMARY KEY,
    event_id UUID NOT NULL DEFAULT gen_random_uuid(),
    stream_id UUID NOT NULL REFERENCES event_streams(stream_id) ON DELETE RESTRICT,
    stream_version BIGINT NOT NULL,
    event_type VARCHAR(128) NOT NULL,
    payload JSONB NOT NULL,
    metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
    recorded_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),
    CONSTRAINT uq_stream_id_version UNIQUE (stream_id, stream_version)
);

-- Indexing for Fast Aggregate Rehydration
CREATE INDEX idx_event_records_rehydration 
ON event_records (stream_id, stream_version ASC);

-- Indexing for CQRS Catch-Up Subscriptions and Projections
CREATE INDEX idx_event_records_global_position 
ON event_records (global_position ASC);

Optimistic Concurrency Control via Atomic Functions

A naive client-side implementation reads the latest version (SELECT MAX(stream_version)), checks it in application code, and executes an INSERT. Under concurrent load, this invites race conditions and phantom reads unless executed under strict SERIALIZABLE isolation, which suffers from severe abort rates.

The production-grade pattern enforces cqrs aggregate root concurrency control directly inside the database engine via a transactional stored procedure utilizing SELECT ... FOR UPDATE on the stream registry:

CREATE OR REPLACE FUNCTION append_events_to_stream(
    p_stream_name VARCHAR(255),
    p_stream_type VARCHAR(128),
    p_expected_version BIGINT,
    p_event_types VARCHAR(128)[],
    p_payloads JSONB[],
    p_metadatas JSONB[]
)
RETURNS TABLE (
    out_global_position BIGINT,
    out_event_id UUID,
    out_stream_version BIGINT
) 
LANGUAGE plpgsql
AS $$
DECLARE
    v_stream_id UUID;
    v_current_version BIGINT;
    v_new_version BIGINT;
    v_event_count INT;
    i INT;
BEGIN
    v_event_count := array_length(p_event_types, 1);
    
    IF v_event_count IS NULL OR v_event_count = 0 THEN
        RAISE EXCEPTION 'Cannot append an empty batch of events.';
    END IF;

    -- 1. Lock the stream row exclusively to establish serial write serialization
    SELECT stream_id, current_version 
    INTO v_stream_id, v_current_version
    FROM event_streams
    WHERE stream_name = p_stream_name
    FOR UPDATE;

    -- 2. Handle stream initialization or verify existing stream revision
    IF NOT FOUND THEN
        IF p_expected_version != 0 THEN
            RAISE EXCEPTION 'Concurrency Conflict: Stream % does not exist, but expected_version was %', 
                p_stream_name, p_expected_version
                USING ERRCODE = 'P0001';
        END IF;

        -- Create new stream entry
        INSERT INTO event_streams (stream_name, stream_type, current_version)
        VALUES (p_stream_name, p_stream_type, v_event_count)
        RETURNING stream_id, current_version INTO v_stream_id, v_new_version;

        v_current_version := 0;
    ELSE
        -- Stream exists: Validate expected version against actual version
        IF p_expected_version != v_current_version THEN
            RAISE EXCEPTION 'Concurrency Conflict: Stream % is at version %, but expected %', 
                p_stream_name, v_current_version, p_expected_version
                USING ERRCODE = 'P0001';
        END IF;

        -- Advance stream version counter atomically
        v_new_version := v_current_version + v_event_count;
        UPDATE event_streams 
        SET current_version = v_new_version,
            updated_at = clock_timestamp()
        WHERE stream_id = v_stream_id;
    END IF;

    -- 3. Insert events into the immutable append log
    FOR i IN 1..v_event_count LOOP
        INSERT INTO event_records (
            stream_id,
            stream_version,
            event_type,
            payload,
            metadata
        ) VALUES (
            v_stream_id,
            v_current_version + i,
            p_event_types[i],
            p_payloads[i],
            COALESCE(p_metadatas[i], '{}'::jsonb)
        )
        RETURNING global_position, event_id, stream_version
        INTO out_global_position, out_event_id, out_stream_version;

        RETURN NEXT;
    END LOOP;
END;
$$;

Storage Engine Bottlenecks and Autovacuum Tuning

While PostgreSQL is functionally complete as an event store, scaling an unpartitioned append log to high event volumes exposes clear physical boundaries:

1. Heap Bloat and MVCC Vacuuming: Because event_records is strictly append-only, row tuples are never updated in place. However, the event_streams table suffers continuous row updates on current_version. Without aggressive autovacuum tuning, table and index bloat degrade lock acquisition latency:

   ALTER TABLE event_streams SET (
       autovacuum_vacuum_scale_factor = 0.01,
       autovacuum_vacuum_cost_limit = 2000,
       autovacuum_vacuum_cost_delay = 2
   );

2. Write Amplification on Secondary Indexes: Every append must update the primary key sequence index (global_position), the foreign key index, and the unique constraint index (stream_id, stream_version). On a single primary write node with synchronous commit (synchronous_commit = on), append throughput is bound by WAL flush (fsync) serialization, B-Tree index page splits, and lock contention on the stream registry table, bottlenecking horizontal scaling unless batching or asynchronous commit strategies are introduced.

3. JSONB TOAST Thresholds: When an aggregate snapshot or batch payload exceeds the 2KB TOAST threshold, PostgreSQL compresses and slices the document into out-of-line storage chunks (pg_toast). This introduces decompression CPU overhead during full aggregate hydration queries.

---

EventStoreDB: The Purpose-Built Aggregate Engine

EventStoreDB (originally created by Greg Young) was engineered from the bare metal specifically to satisfy event sourcing requirements. Rather than layering event semantics atop an MVCC relational database, its storage engine was written around raw append-only files and memory-mapped indices.

Append-Only TFChunk Storage and Memory-Mapped Indexing

EventStoreDB organizes data into fixed-size files called TFChunks (typically 256MB raw files on disk).

  • Physical Writes: Incoming events are written sequentially to the active chunk file via unbuffered disk I/O with hardware-level flush primitives. Sequential disk writes avoid random head movements or filesystem fragmentation.
  • Indexing via PTables: To locate events across millions of streams without relational B-Trees, EventStoreDB maintains a hierarchy of memory-mapped PTables (Persistent Tables). When a chunk fills, an in-memory index table is sorted by (StreamIdHash, Version) and flushed to an immutable PTable on disk. Lookups execute via binary search through memory-mapped sparse indices, resulting in sub-millisecond point reads regardless of total database size.

Concurrency Primitives and Stream Revisions

EventStoreDB exposes native gRPC APIs that enforce aggregate concurrency out of the box without procedural code:

import { 
  EventStoreDBClient, 
  jsonEvent, 
  StreamRevision, 
  NO_STREAM, 
  WrongExpectedVersionError 
} from "@eventstore/db-client";

const client = EventStoreDBClient.connectionString("esdb://localhost:2113?tls=false");

async function appendOrderEvent(orderId: string, expectedVersion: bigint, eventData: any) {
  const streamName = `order-${orderId}`;
  const event = jsonEvent({
    type: "OrderLineAdded",
    data: eventData,
    metadata: { correlationId: "req-9912", source: "checkout-api" }
  });

  try {
    // Exact optimistic concurrency check enforced at the storage engine layer
    const result = await client.appendToStream(
      streamName, 
      [event], 
      { expectedRevision: StreamRevision(expectedVersion) }
    );
    return result.nextExpectedRevision;
  } catch (error) {
    if (error instanceof WrongExpectedVersionError) {
      throw new Error(`Aggregate concurrency violation on ${streamName}. Real version: ${error.actualVersion}`);
    }
    throw error;
  }
}

Projections, System Streams, and Catch-Up Subscriptions

A major operational strength of EventStoreDB is native eventstoredb catch up subscription projections. It eliminates polling boilerplate by pushing events to subscribers via persistent gRPC streams.

  • `$all` Stream: A master monotonic physical stream containing every event appended to the system across all aggregates.
  • Category Streams (`$ce-Order`): EventStoreDB automatically routes events containing hyphenated stream names (order-1234) to a system-maintained category stream ($ce-Order). A projection service dedicated to orders can subscribe directly to $ce-Order, bypassing unrelated domain events and eliminating read-amplification.
  • Server-Side Checkpoint Tracking: Catch-up subscriptions allow clients to specify a fromRevision or fromPosition. When a projection restarts, it resumes reading from its last recorded checkpoint without reprocessing the entire dataset.

Operational Overhead and Disk Scavenging

Despite its performance benefits, EventStoreDB introduces specialized operational demands:

1. The Scavenge Process: Because files are append-only chunks, soft-deleted events or superseded snapshots are not purged in place. Operators must periodically trigger a scavenge operation. Scavenging reads historic TFChunks, strips unreferenced events or expired data, and writes consolidated chunks to disk before unlinking the originals. During scavenge execution, storage I/O increases, and systems require sufficient disk headroom to store both the original and newly compacted chunk files concurrently until the operation completes.

2. Specialized Operational Ecosystem: Unlike PostgreSQL's ubiquitous client libraries, managed cloud platforms, and standard DBA tooling, EventStoreDB relies on specialized gRPC client libraries, custom quorum-based clustering, and dedicated Prometheus metric endpoints, requiring operational familiarity with its storage engine and cluster lifecycle.

---

Apache Kafka: Deconstructing the Event Sourcing Anti-Pattern

Due to Kafka's reputation as a high-performance, append-only log with log compaction capabilities, engineering teams frequently propose using Kafka directly as an event store for aggregate state management.

In production, using Kafka as an aggregate store is a well-documented kafka event sourcing anti pattern. The underlying distributed log design of Kafka directly contradicts the core operational requirements of Domain-Driven Design aggregates.

The Partition Cardinality Ceiling

In event sourcing, aggregate roots require independent identity and stream isolation. An e-commerce platform processing 10 million orders requires 10 million distinct event streams.

1. Topic-per-Aggregate: Creating one Kafka topic per aggregate instance rapidly exhausts cluster resources. In Apache Kafka, each topic partition maps to physical directories, segment files (.log, .index, .timeindex), and dedicated in-memory record buffers. Even with KRaft architecture removing ZooKeeper controller bottlenecks, hosting hundreds of thousands or millions of aggregate partitions on a broker exceeds operating system open file descriptor limits and degrades replication throughput, making fine-grained partition-per-aggregate topologies fundamentally unviable.

2. Multiplexing over Partitions: To bypass the partition limit, architects multiplex millions of aggregate streams into a small set of partitions (e.g., topic order-events with 32 partitions, partitioned by orderId.hashCode()). This introduces severe performance penalties on aggregate rehydration: to rebuild Order-541, an application worker must scan the entire partition from beginning to end, discarding gigabytes of irrelevant order events to locate the 6 events belonging to that specific order.

flowchart TD
    subgraph KafkaAntiPattern["Kafka Anti-Pattern: Multiplexed Aggregate Stream"]
        P0["Topic: orders (Partition 0)"]
        E1["Offset 0: Order-1 Created"]
        E2["Offset 1: Order-9 ItemAdded"]
        E3["Offset 2: Order-1 Paid"]
        E4["Offset 3: Order-44 Created"]
        E5["Offset 4: Order-1 Shipped"]
        
        P0 --> E1 --> E2 --> E3 --> E4 --> E5
    end

    subgraph Hydration["Rehydration Attempt for Order-1"]
        WORKER["Aggregate Worker"]
        WORKER -.->|Must scan entire log| E1
        WORKER -.->|Skip irrelevant data| E2
        WORKER -.->|Scan & filter| E3
        WORKER -.->|Skip irrelevant data| E4
        WORKER -.->|Scan & filter| E5
    end

The Concurrency Control Vacuum

Kafka provides no native conditional append mechanism based on entity version state:

  • The Kafka protocol supports enable.idempotence=true, which assigns a Producer ID (PID) and sequence numbers to incoming message batches. However, this only prevents network-induced duplicates from a single producer instance; it cannot validate domain state.
  • If two independent service replicas process simultaneous commands for Order-42 (e.g., CancelOrder vs AddCoupon), both producers publish their respective events (OrderCancelled, CouponAdded) to the partition.
  • Kafka appends both events sequentially without error. Because Kafka has no mechanism to assert expected_offset or expected_aggregate_version, both writes succeed, producing a split-brain domain state that violates business invariants.
  • Attempting to resolve this via distributed locks (Redis Redlock, ZooKeeper nodes) negates the benefits of event-driven architecture, introducing distributed deadlocks and high write latency.

Entity Rehydration Latency and Memory Footprint

To mitigate linear partition scanning, teams attempting this anti-pattern deploy Kafka Streams or ksqlDB with local RocksDB state stores.

  • RocksDB consumes partition streams and continuously materializes the current state of every aggregate into local key-value stores.
  • While this accelerates point reads, it shifts massive RAM overhead onto application instances. A service tracking 50 million entities must maintain tens of gigabytes of localized RocksDB state.
  • During node restarts, container rescheduling, or partition rebalances, restoring the local RocksDB state store from Kafka changelog topics requires replaying changelog segments over the network and rebuilding RocksDB SST files from scratch. For high-volume state stores running without persistent storage volumes or standby replicas (num.standby.replicas), this restoration phase can introduce substantial cold-start delays, leaving the consumer unresponsive and severely compromising the application's Recovery Time Objective (RTO).

Log Compaction vs Temporal Audit Trails

Kafka offers log compaction (cleanup.policy=compact), which retains only the latest record for each message key. Some argue this represents a built-in snapshotting system.

In practice, log compaction is designed for state changelogs rather than historical event streams:

  • It retains only the latest record for each key, discarding intermediate state transitions. This behavior conflicts with regulatory and compliance standards that require complete, immutable audit histories across the lifecycle of an entity.
  • If log compaction is disabled (cleanup.policy=delete), retention must be set to indefinite (log.retention.ms=-1). Managing unbounded event storage across Kafka broker storage tiers requires dedicated capacity planning, tiered storage offloading (such as S3), and cluster management overhead.

The Valid Architecture: CDC and the Outbox Bridge

The correct enterprise pattern isolates the Aggregate Event Store from the Event Streaming Fabric.

The domain service writes to an ACID-compliant aggregate store (PostgreSQL or EventStoreDB) under strict optimistic concurrency. An asynchronous bridge—such as Debezium Change Data Capture (CDC) or the Transactional Outbox Pattern—tails the committed event log and streams cross-boundary domain events to Kafka topics for consumption by downstream microservices.

---

Architectural Decision Matrix: Evaluating the Core Criteria

The following architectural decision matrix evaluates PostgreSQL, EventStoreDB, and Apache Kafka across the six definitive technical criteria for event-driven systems:

Architectural CriterionPostgreSQL (Custom / Marten)EventStoreDBApache Kafka (Pure Log)
1. Stream Concurrency & Aggregate IsolationHigh. Row-level locks (SELECT FOR UPDATE) and composite unique constraints (stream_id, version) provide exact OCC with immediate client aborts.Exceptional. Native engine-level OCC via gRPC revisions (ExpectedVersion). High-throughput, sub-millisecond atomic verification.Unsuitable. No domain conditional append primitives. Only deduplicates producer retries via PID sequence; cannot prevent domain race conditions.
2. Snapshotting Strategy & Hydration LatencyLow Latency when Cached. Point reads on indexed streams (WHERE stream_id = X ORDER BY stream_version ASC) achieve single-digit millisecond latency when table and index working sets reside in shared_buffers. Snapshots can be stored in a dedicated relational table with version pointers.Sub-millisecond. Direct binary search on memory-mapped PTables. Warm streams hydrate with sub-millisecond memory lookups; native snapshot stream conventions.Poor / High Overhead. Requires full partition scans or dedicated local RocksDB state stores (Kafka Streams) that inflate RAM and recovery times.
3. Projection Rebuilding & Catch-Up SubscriptionsModerate. Monotonic sequence indices (global_position) support reliable cursor polling, but full table scans on billions of rows degrade transactional cache.Native & Optimized. Purpose-built gRPC catch-up subscriptions reading from $all or $ce-* category streams with server-side checkpointing.Strong for Broadcast. Kafka consumer groups excel at sequential high-volume log consumption, but rebalancing storms introduce pipeline latency.
4. Operational TCO & Infrastructure FootprintLowest. Standard cloud-managed instances (AWS RDS, Aurora, Cloud SQL). Reuses existing DBA expertise, backup systems, and monitoring.Moderate to High. Dedicated cluster management (3-to-5 node quorum). Demands high-performance NVMe disks and specialized disk scavenge maintenance.High. Heavy operational complexity (KRaft metadata management, JVM memory tuning, partition rebalancing, storage management).
5. Query Flexibility & Out-of-Order HandlingExtensive. Full SQL, JSONB indexing (gin_trgm), joins against non-event relational data, and ad-hoc analytical queries across historical records.Specialized. Optimized strictly for stream-oriented access. Complex ad-hoc relational queries require external read-model projections.Restricted. Key-value lookups only. Analytical queries require exporting topic streams into ClickHouse, BigQuery, or Elasticsearch.
6. Event Compaction, Retention & Data GovernanceFlexible. Supports native declarative table partitioning by date or stream ID. Cold partitions can be archived to object storage (S3/GCS).Append-Only Chunking. Data is permanent by default. Deletions require soft-tombstones followed by heavy I/O disk scavenging cycles.Key-Based Compaction. Topic compaction retains only the latest key state, discarding intermediate events. Incompatible with immutable audit requirements unless raw event topics are retained in parallel.

---

Production Implementation: TypeScript Domain Aggregate and Projection Pipeline

To clarify how these theoretical principles operate in application code, review this runnable TypeScript implementation. It illustrates an aggregate root handling state rehydration with optimistic version tracking, followed by a resilient projection worker.

Domain Aggregate Root with OCC Version Guards

// Domain Aggregate Root: OrderAggregate.ts
export interface DomainEvent {
  eventId: string;
  streamId: string;
  version: number;
  type: string;
  payload: Record<string, any>;
  timestamp: Date;
}

export class OrderAggregate {
  private id: string;
  private version: number = 0;
  private status: "DRAFT" | "SUBMITTED" | "CANCELLED" = "DRAFT";
  private totalAmount: number = 0;
  private uncommittedEvents: DomainEvent[] = [];

  constructor(id: string) {
    this.id = id;
  }

  public static rehydrate(id: string, history: DomainEvent[]): OrderAggregate {
    const aggregate = new OrderAggregate(id);
    for (const event of history) {
      aggregate.applyChange(event, false);
    }
    return aggregate;
  }

  public submitOrder(amount: number, customerId: string): void {
    if (this.status !== "DRAFT") {
      throw new Error(`Invalid state transition: Cannot submit order in ${this.status} state.`);
    }
    if (amount <= 0) {
      throw new Error("Order amount must be greater than zero.");
    }

    const event: DomainEvent = {
      eventId: crypto.randomUUID(),
      streamId: this.id,
      version: this.version + 1,
      type: "OrderSubmitted",
      payload: { amount, customerId },
      timestamp: new Date()
    };

    this.applyChange(event, true);
  }

  private applyChange(event: DomainEvent, isNew: boolean): void {
    switch (event.type) {
      case "OrderSubmitted":
        this.status = "SUBMITTED";
        this.totalAmount = event.payload.amount;
        break;
      case "OrderCancelled":
        this.status = "CANCELLED";
        break;
      default:
        throw new Error(`Unhandled domain event type: ${event.type}`);
    }

    this.version = event.version;
    if (isNew) {
      this.uncommittedEvents.push(event);
    }
  }

  public getExpectedVersion(): number {
    return this.version - this.uncommittedEvents.length;
  }

  public getUncommittedEvents(): DomainEvent[] {
    return [...this.uncommittedEvents];
  }

  public clearUncommittedEvents(): void {
    this.uncommittedEvents = [];
  }
}

Resilient Catch-Up Projection Worker

This background projection tails an event store using monotonic checkpoints and writes to a denormalized PostgreSQL query table:

// Projection Worker: OrderSummaryProjection.ts
import { Pool } from "pg";

export class OrderSummaryProjection {
  private pgPool: Pool;
  private isRunning: boolean = false;
  private readonly batchSize: number = 500;

  constructor(pgPool: Pool) {
    this.pgPool = pgPool;
  }

  public async start(): Promise<void> {
    this.isRunning = true;
    while (this.isRunning) {
      const processedCount = await this.processNextBatch();
      if (processedCount === 0) {
        // Back off when caught up with the head of the log
        await new Promise((resolve) => setTimeout(resolve, 100));
      }
    }
  }

  private async processNextBatch(): Promise<number> {
    const client = await this.pgPool.connect();
    try {
      await client.query("BEGIN;");

      // 1. Fetch current projection checkpoint position
      const checkpointRes = await client.query(
        "SELECT last_processed_position FROM projection_checkpoints WHERE projection_name = $1 FOR UPDATE;",
        ["order_summary_projection"]
      );

      const lastPosition = checkpointRes.rows.length > 0 ? BigInt(checkpointRes.rows[0].last_processed_position) : 0n;

      // 2. Fetch the next sequential batch of events
      const eventsRes = await client.query(
        `SELECT global_position, stream_id, event_type, payload 
         FROM event_records 
         WHERE global_position > $1 
         ORDER BY global_position ASC 
         LIMIT $2;`,
        [lastPosition.toString(), this.batchSize]
      );

      if (eventsRes.rows.length === 0) {
        await client.query("COMMIT;");
        return 0;
      }

      let currentPosition = lastPosition;

      // 3. Apply events idempotently to the read model
      for (const row of eventsRes.rows) {
        if (row.event_type === "OrderSubmitted") {
          await client.query(
            `INSERT INTO read_model_order_summaries (order_id, status, amount, updated_at)
             VALUES ($1, 'SUBMITTED', $2, NOW())
             ON CONFLICT (order_id) DO UPDATE 
             SET status = EXCLUDED.status, amount = EXCLUDED.amount, updated_at = NOW();`,
            [row.stream_id, row.payload.amount]
          );
        }
        currentPosition = BigInt(row.global_position);
      }

      // 4. Update the projection checkpoint
      await client.query(
        `INSERT INTO projection_checkpoints (projection_name, last_processed_position, updated_at)
         VALUES ($1, $2, NOW())
         ON CONFLICT (projection_name) DO UPDATE 
         SET last_processed_position = EXCLUDED.last_processed_position, updated_at = NOW();`,
        ["order_summary_projection", currentPosition.toString()]
      );

      await client.query("COMMIT;");
      return eventsRes.rows.length;
    } catch (err) {
      await client.query("ROLLBACK;");
      console.error("Projection processing encountered an error:", err);
      throw err;
    } finally {
      client.release();
    }
  }

  public stop(): void {
    this.isRunning = false;
  }
}

---

Falsifiability and Production Failure Signatures

Architectural proposals must specify concrete failure criteria. How do engineering leaders verify empirically that their selected event store architecture has hit a scaling wall?

PostgreSQL Failure Modes

  • Autovacuum Starvation: When pg_stat_user_tables.n_dead_tup on the event_streams table grows continuously despite autovacuum tuning, vacuum workers cannot keep pace with high-frequency version updates. The resulting table and index bloat prolongs SELECT ... FOR UPDATE row lock acquisition times, cascading into transaction lock wait queues and severe application tail latency spikes during concurrent appends.
  • Cache Eviction of Hot Indexes: When total index size on (global_position) and (stream_id, stream_version) exceeds available shared_buffers, disk read IOPS spike, causing read-rehydration times to degrade linearly with table growth.
  • WAL and Replication Saturation: Under sustained high write concurrency, continuous event inserts and full-page writes (full_page_writes = on following checkpoints) generate massive WAL volume. This write amplification can saturate physical network bandwidth between primary and read replicas, causing replication lag (pg_stat_replication.write_lag) to balloon and delaying asynchronous projection readers.

EventStoreDB Failure Modes

  • Disk I/O Scavenge Exhaustion: When a cluster cannot complete a scavenge cycle before disk utilization reaches critical capacity, disk space exhaustion becomes critical. Unmanaged scavenge operations saturate storage queue depths, triggering gRPC connection drops on write commands.
  • Memory Saturation on Uncached Streams: If the active working set of stream identifiers and unmerged PTables exceeds available system RAM, binary index lookups can no longer be serviced from the OS page cache. Binary search operations then fall back to synchronous disk I/O to read PTable blocks, causing tail stream hydration latency (p95 and p99) to degrade significantly compared to warm in-memory lookups.

Apache Kafka Failure Modes

  • Split-Brain Invariant Collisions: The definitive failure signature of Kafka used as an aggregate store is silent state corruption. When two concurrent requests append contradictory events to the same aggregate partition, read models diverge because the broker cannot evaluate aggregate state guards.
  • Consumer Group Rebalance Cascades: Rebuilding projections by replaying entire topics triggers consumer timeouts. When heartbeats fail during intense batch processing, Kafka initiates rebalance storms, pausing all consumer processing across the cluster.

---

Frequently Asked Questions

When should an enterprise choose PostgreSQL over EventStoreDB for CQRS?

Select PostgreSQL when your write throughput fits within standard relational database scaling profiles, when your operations team is already proficient with PostgreSQL infrastructure (such as AWS RDS, Aurora, or Cloud SQL), and when you require unified relational tooling, transactional migrations, and direct SQL reporting. Choose EventStoreDB when your domain demands high aggregate stream density (tens of millions of discrete streams), engine-level sub-millisecond append latency, and out-of-the-box catch-up projections across complex category streams without relational vacuuming overhead.

Is EventStoreDB production-ready for financial systems requiring multi-region replication?

EventStoreDB is widely adopted in financial and payment processing systems requiring strict event immutability, but its clustering model relies on quorum consensus over low-latency network interconnects. While single-region multi-AZ clustering provides high availability with minimal consensus overhead, spanning EventStoreDB clusters synchronously across distant geographic regions introduces WAN latency penalties on the write quorum path. For active-active multi-region architectures, engineering teams typically deploy localized EventStoreDB or PostgreSQL clusters per region and synchronize cross-region state asynchronously via an external messaging fabric or replication pipeline.

Can Kafka Streams or ksqlDB replace read-model projections in PostgreSQL or Elasticsearch?

Kafka Streams and ksqlDB can generate streaming materialized views, but they are not universal replacements for dedicated read stores. They store state in localized RocksDB instances on the processing nodes, making complex SQL querying, full-text fuzzy search, and geospatial joins difficult to expose to end-user APIs. The proven pattern uses Kafka to deliver events to specialized query stores (Elasticsearch for search, PostgreSQL for relational views, Redis for low-latency key lookups).

How does snapshotting work in event-sourced systems, and when is it strictly necessary?

Snapshotting captures the serialized state of an aggregate at a specific version (e.g., version 500) and writes it to a snapshot table or dedicated stream. During rehydration, the system loads the latest snapshot first and replays only subsequent events. Snapshotting is an optimization rather than a mandatory requirement; for aggregates with short lifecycles or a modest event count, replaying events sequentially in memory is computationally inexpensive. Snapshotting introduces additional schema evolution and storage complexity, making it worthwhile primarily for high-churn, long-lived aggregates where event rehydration latency measurably impacts command processing times.

How do you handle schema evolution and breaking event structure changes in an append-only store?

Because event logs are immutable, historical events must never be rewritten or altered in place. To manage breaking schema modifications, use the Weak Schema Evolution pattern or Upcasting:

1. Weak Schema Rules: Ensure all new event properties are optional, never remove existing fields, and map unknown properties gracefully.

2. In-Flight Upcasters: Write transformation functions in application code that intercept historical event JSON representations during stream rehydration and project them forward to the current schema version before passing them into the domain model.

---

Sources

Related articles