Triamorph Systems

Architecture · 12 min read · Sep 04, 2024

CQRS & Event Sourcing in Distributed Systems: Building Immutable Audit Trails

Complete architectural guide to CQRS and Event Sourcing: modeling domain events, event stores in PostgreSQL/Kafka, asynchronous projection workers, and read model optimization.

By Aman Aslam

Core Engineering Takeaways

  • Event Sourcing persists facts (e.g. OrderPlaced, PaymentCaptured) rather than mutable snapshots, creating a complete cryptographic history of the system.
  • CQRS enables scaling read databases (Elasticsearch, Redis, read-replica PostgreSQL) independently from write-optimized event stores.
  • Projections can be replayed from genesis to rebuild read models or generate completely new analytics views retroactively.

Traditional CRUD architectures conflate write validation with read querying into a single relational schema. As applications scale to millions of users, complex relational joins choke the database, and historical state changes are permanently lost when rows are updated in-place. CQRS (Command Query Responsibility Segregation) and Event Sourcing resolve this by storing immutable business facts and projecting specialized read views asynchronously.

1. Why CRUD Fails at Complex Audit Requirements

The difference between storing current status versus business intent

In CRUD, when a user changes their address, the previous address is overwritten and destroyed. When regulators or security forensics teams demand to know what the address was on March 15th at 3:00 PM, a CRUD database is powerless. Event sourcing records every change as an immutable domain event.

2. Designing an Append-Only Event Store in PostgreSQL

Enforcing monotonic sequence versions for optimistic concurrency control

Below is a robust event store table with version constraints preventing concurrent append conflicts.

db/events/event_store.sql (sql)
CREATE TABLE event_stream (
    event_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    aggregate_type VARCHAR(64) NOT NULL,
    aggregate_id UUID NOT NULL,
    version INT NOT NULL,
    event_type VARCHAR(128) NOT NULL,
    payload JSONB NOT NULL,
    metadata JSONB NOT NULL,
    occurred_at TIMESTAMPTZ DEFAULT NOW(),
    CONSTRAINT unique_aggregate_version UNIQUE (aggregate_type, aggregate_id, version)
);

-- Append event with optimistic lock
INSERT INTO event_stream (aggregate_type, aggregate_id, version, event_type, payload, metadata)
VALUES (
    'OrderAggregate',
    '8c9e1204-7681-42cb-b7cf-00129a8f4211',
    3, -- Expected next version
    'ORDER_SHIPPED',
    '{"trackingNumber": "TRX-998210", "carrier": "FedEx"}',
    '{"actorId": "usr_admin_12", "ipAddress": "192.168.1.10"}'
);

3. Asynchronous Read Model Projections with Kafka

Streaming events into Elasticsearch and Redis read models

Dedicated projection consumers read from the event log, updating denormalized read-optimized tables. A frontend searching for orders queries pre-joined JSON tables with sub-5ms response times.

4. Managing Eventual Consistency in Modern Web UIs

Optimistic UI updates and WebSocket notification channels

Because read projections update asynchronously (typically within 50ms), the frontend uses optimistic state mutations while listening to WebSocket event channels for confirmed projection updates.

Tags: cqrs event sourcing patternimmutable audit trail architecturekafka event storeread model projection databaseDistributed Architecture

Related Engineering Practice & Case Studies

Engineering Practice Blueprint

Custom Web Development & SaaS Platforms →

Next.js & React web platforms engineered for sub-1.5s load times and 98+ Lighthouse scores.

View Practice Blueprint & Capabilities →
Production Client System

VisageGuard Biometric Security Platform →

Edge facial recognition and biometric identity verification platform with sub-300ms verification latency.

Read Deployed Case Study (99.4% verification accuracy at sub-300ms edge latency) →

Related Engineering Articles & Guides

Explore all technical guides in our Articles & Guides Index → or discuss your architecture with our engineers via Technical Discovery →