Software Architecture
CQRS and Event Sourcing: High-Concurrency Data Architectures Without Write Contention
technology.efektifpro.com – In traditional CRUD (Create-Read-Update-Delete) systems, the same database schema handles both high-throughput write mutations and complex analytical queries. As concurrent traffic scales, table-level locking, index maintenance overhead, and read-write contention degrade performance exponentially. Command Query Responsibility Segregation (CQRS) paired with Event Sourcing eliminates write contention by segregating mutations into an append-only event log while projecting read models into optimized read stores.
Core Concept: State as a Stream of Immutable Facts
In a standard CRUD ledger, an account balance update overwrites row state: UPDATE accounts SET balance = 500 WHERE id = 1;. In Event Sourcing, state is never overwritten. Instead, every mutation is recorded as an immutable business event in an append-only log:
AccountCreatedEvent(id=1, initial_deposit=1000)FundsTransferredEvent(from=1, to=2, amount=300)FundsWithdrawnEvent(account=1, amount=200)
The current balance ($500) is calculated by replaying events from genesis (or from the latest snapshot). This architectural guarantee provides an audit trail that is mathematically impossible to falsify or tamper with.
The CQRS Data Flow Architecture
Under CQRS, write traffic hits the Command Side (validates business invariants, writes to the Event Store). An asynchronous event projector consumes these events and updates the Query Side (denormalized read tables optimized for specific UI views):
# Python — Event-sourced Aggregate Root pattern
from dataclasses import dataclass
from typing import List
@dataclass
class AccountAggregate:
account_id: str
balance: float = 0.0
status: str = "PENDING"
version: int = 0
def apply_event(self, event):
# State mutation happens strictly through event application
if event["type"] == "ACCOUNT_OPENED":
self.account_id = event["account_id"]
self.status = "ACTIVE"
elif event["type"] == "MONEY_DEPOSITED":
self.balance += event["amount"]
elif event["type"] == "MONEY_WITHDRAWN":
self.balance -= event["amount"]
self.version += 1
def execute_withdraw_command(self, amount: float) -> dict:
# Command validation enforces business invariants before event generation
if self.status != "ACTIVE":
raise ValueError("Account is not active")
if self.balance < amount:
raise ValueError("Insufficient funds")
# Invariants passed — return new event to be appended
return {
"type": "MONEY_WITHDRAWN",
"account_id": self.account_id,
"amount": amount,
"expected_version": self.version
}
Optimistic Concurrency Control (OCC)
To eliminate database row locks across concurrent workers, Event Stores use expected version checking. If two workers attempt to append an event at version 5 simultaneously, the database rejects the second write via unique constraint, prompting that worker to re-read the latest events and retry without deadlock:
-- PostgreSQL Event Store append with version concurrency check
INSERT INTO event_store (stream_id, version, event_type, payload, created_at)
VALUES ('account-1001', 6, 'MONEY_WITHDRAWN', '{"amount": 100}', CURRENT_TIMESTAMP);
-- UNIQUE constraint on (stream_id, version) guarantees only one append succeeds
Eventual Consistency and Read Model Projection
Because projections update asynchronously (typically via Kafka consumer pipelines), the read model is eventually consistent (typically < 50ms replication lag). For UI interactions requiring immediate feedback, use command response payloads to return the generated event ID, or query the Command model directly for critical read-after-write confirmation.
When to Use CQRS & Event Sourcing
- Use It: Financial ledgers, payment processing, inventory reservation, order fulfillment, medical record tracking, gaming state.
- Avoid It: Simple CRUD apps, CMS platforms, internal tools where auditability is unneeded and eventual consistency adds unnecessary cognitive overhead.
