I adopted CQRS and Event Sourcing for the first time on a logistics platform that had outgrown its CRUD roots. We had a single Order table with 47 columns, a handful of status flags, and an audit log that was always slightly wrong. Every new requirement — retroactive price corrections, partial shipments, compliance reporting on who changed what and when — turned into another nullable column or another trigger. The system was not incorrect, but it had lost the ability to explain itself. In my experience, that loss of explanatory power is the clearest signal that you may need a different architectural model, one that treats behavior as a first-class citizen rather than a side effect of mutating rows.
This article is a practitioner’s account of where CQRS and Event Sourcing actually help, what they cost to run in production, and how I have learned to tell the difference. These patterns are not a default for every service. They are precise tools for specific contexts where the history of decisions matters as much as the current state.
Separating Intent from Observation: What CQRS Really Enforces
CQRS — Command Query Responsibility Segregation — is often reduced to “separate reads and writes.” That description is technically accurate but misses the operational intent. The value is not in having two databases. The value is in separating operations that express intent and have business consequences from operations that merely observe state.
A command is a request to do something that might be rejected: SubmitOrder, AllocateInventory, CancelShipment. It carries who, why, and what, and it must pass invariants. A query is a question about the current world: GetOrderSummary, ListShipmentsDueToday. It should have no side effects. When you conflate the two, you end up with endpoints like GET /orders?cancel=true and service methods that both mutate and return view-specific DTOs. Over time, performance tuning and business rule enforcement fight each other inside the same model.
In practice, I keep command and query models physically separate, even when they start in the same monolith. Commands go through an application service that loads an aggregate, validates invariants, and appends events. Queries go through thin read services that hit optimized projections. This aligns well with Clean Architecture in Practice: Beyond the Theory, where the domain layer remains isolated from presentation concerns. The command side owns behavior; the query side owns representation.
Command Handling Without Anemic Services
A common mistake I have seen is pushing all logic into stateless command handlers, leaving aggregates as data bags. If the aggregate does not protect its invariants, CQRS just adds ceremony. The aggregate should be the transactional boundary that decides whether a command succeeds.
// Command and Aggregate with invariant enforcement - C# style
public record AllocateInventory(string OrderId, string Sku, int Quantity);
public class Order : AggregateRoot {
private OrderState _state = new();
public void Handle(AllocateInventory cmd) {
if (_state.Status == OrderStatus.Cancelled)
throw new DomainException("Cannot allocate for cancelled order");
var available = _inventoryPolicy.Check(cmd.Sku, cmd.Quantity);
if (!available)
throw new DomainException($"Insufficient inventory for {cmd.Sku}");
// Event records the decision, not just the data mutation
Apply(new InventoryAllocated(cmd.OrderId, cmd.Sku, cmd.Quantity, DateTime.UtcNow));
}
private void Apply(InventoryAllocated e) {
_state.Apply(e);
AddUncommittedEvent(e);
}
}
Queries, by contrast, should be boring. In my teams, query handlers are often plain SQL or a document database lookup with no domain logic at all. That is intentional. If you find yourself re-implementing business rules in query handlers to “calculate” the current status, your projections are lagging or incomplete. Fix the projection, not the query.
The Event Store as System of Record: Rebuilding State from Immutable History
Event Sourcing changes the source of truth from “current row” to “ordered sequence of events.” State becomes a left-fold over history. Instead of storing orders.status = 'shipped', you store OrderSubmitted, PaymentAuthorized, InventoryAllocated, ShipmentCreated, ShipmentDispatched. You can always derive the status, but you also retain why and when transitions occurred.
I have found that teams understand this best when they stop thinking about tables and start thinking about ledgers. An event store is append-only, ordered per stream (usually per aggregate ID), and immutable once written. Concurrency is handled via optimistic concurrency on the expected stream version, not with locks.
# Python-like event store append with optimistic concurrency
def handle_command(store, command):
stream_id = f"order-{command.order_id}"
events, current_version = store.read_stream(stream_id)
order = Order.rehydrate(events) # replay to rebuild state
new_events = order.handle(command) # validates invariants
# Fails if another writer incremented version concurrently
store.append_to_stream(
stream_id,
expected_version=current_version,
events=new_events
)
return new_events
Designing Events That Survive Contact With Reality
Good events are facts about the past, phrased in past tense, rich enough to be useful to future consumers you have not yet imagined. I use three rules that have held up:
First, capture intent and context, not just the delta. DiscountApplied { orderId, code: "WELCOME10", amount: 1000, appliedBy: "system", reason: "first_order_promo" } is far more valuable than OrderTotalUpdated { total: 9000 }. The latter tells you what changed; the former tells you why.
Second, keep events coarse-grained and business-meaningful. Avoid CRUD-like OrderFieldUpdated events. If your event names mirror database columns, you are sneaking state-based persistence back in.
Third, treat event metadata as part of the contract: eventId, aggregateId, version, timestamp, correlationId, causationId, actorId. Correlation and causation IDs have saved me more debugging time than any logging framework, especially when a single user action triggers a chain across services. For distributed propagation, I often rely on idempotency semantics as described in the IETF RFC Standards for HTTP, applying the same key-based deduplication to event consumers.
This approach becomes much clearer when bounded contexts are explicit. As described in Domain-Driven Design: Bounded Contexts and Aggregate Roots Explained, events should not leak internal aggregate structure across contexts. Publish integration events that represent a stable public contract, distinct from internal domain events used for rehydration.
Projecting History into Read Models That Actually Scale
The query side of CQRS earns its keep when reads and writes have fundamentally different shapes, scale characteristics, or consistency needs. On one trading-adjacent system I worked on, the write model processed a few dozen commands per second with strict invariant checks, while the read side served thousands of filtered, paginated queries per second with denormalized views. A single relational model optimized for both would have been compromised for both.
Projections are asynchronous subscribers that transform events into read models. They can be many: a relational table for search, a document for order detail pages, an Elasticsearch index for analytics, a cache for customer dashboards. Each projection is disposable and rebuildable, which is a feature, not a bug.
Idempotency, Ordering, and Lag
Every serious projection system must handle three realities: events will be redelivered, ordering is only guaranteed within a single stream, and consumers lag.
For idempotency, I store the last processed eventId or checkpoint atomically with the projection update, inside the same transaction as the read-model write when possible. If your projection store supports transactions, use them.
-- Idempotent projection update in Postgres
BEGIN;
INSERT INTO order_summary (order_id, status, total, last_event_id, updated_at)
VALUES ($1, $2, $3, $4, NOW())
ON CONFLICT (order_id) DO UPDATE
SET status = EXCLUDED.status,
total = EXCLUDED.total,
last_event_id = EXCLUDED.last_event_id,
updated_at = NOW()
WHERE order_summary.last_event_id < EXCLUDED.last_event_id; -- ignore duplicates/out-of-order
INSERT INTO projection_checkpoints (projection_name, last_position)
VALUES ('order_summary', $5)
ON CONFLICT (projection_name) DO UPDATE SET last_position = EXCLUDED.last_position;
COMMIT;
For ordering, I do not assume global order. If an aggregate emits PaymentAuthorized and OrderSubmitted on different streams, a consumer that joins them must tolerate arrival in either order or use a process manager to enforce causal handling. The MDN Web Docs overview of server-sent events illustrates this ordering problem well at the transport level, but in domain systems the fix is in the model: design projections that are associative and commutative where possible, or key them by aggregate stream.
For lag, expose it. Every read model should have a freshness indicator: asOfPosition or lastUpdatedAt. In my experience, product managers accept eventual consistency immediately when the UI honestly says “updated 2 seconds ago” instead of pretending to be strongly consistent and then flickering.
The Real Price of Evolution: Event Versioning, Upcasters, and Schema Migration
If the event store is immutable, how do you change what happened? You do not. You version what will happen next. This is the most underestimated cost of Event Sourcing.
Over two years on a single event-sourced system, we accumulated four versions of ShipmentCreated. We added a carrierAccountId, renamed estimatedDelivery to promisedDeliveryWindow, and split a monolithic address blob into validated fields. The old events still sit in the store exactly as they were written. Code that rehydrates a five-year-old aggregate must understand all historical shapes.
I handle this with upcasters — pure functions that convert old event versions to the current shape during replay — and with careful compatibility rules:
One, never delete or mutate a stored event in place. Upcasters run at read time, leaving storage untouched. Two, make changes additive first. Add new optional fields before making them required. Three, treat rename as copy-plus-deprecate, not an atomic rename. Emit the new field while keeping the old one for a transition period.
A simple in-memory upcaster pipeline looks like this: read raw event, apply chain of upcasters sorted by version, then apply to aggregate. Event store tooling like EventStoreDB implements this natively, but I have also built it with a decorator around the deserializer. The key is that upcasting logic lives in one well-tested place and is version-controlled alongside the aggregate.
There is also the snapshotting question. Without snapshots, rehydrating an aggregate with 10,000 events becomes painful. I snapshot every 200-500 events or when replay time exceeds a threshold like 50ms, whichever comes first. The snapshot is a cached fold, not the truth; it can be deleted and rebuilt. I never snapshot for aggregates with short lifecycles where the full replay is trivial.
Consistency Boundaries and Concurrency Control Inside Event-Sourced Aggregates
Not every invariant can live inside a single aggregate, and pretending it can leads to large, contended aggregates that destroy throughput. An aggregate is a consistency boundary, not an object graph. I design aggregates around the transactions that must be immediately consistent, and accept eventual consistency everywhere else.
For example, Order can guarantee that you cannot allocate inventory for a cancelled order, because order status and allocation events live in the same stream. It cannot guarantee that inventory across all warehouses never goes negative in real time if inventory is modeled elsewhere — that requires a reservation process.
Optimistic concurrency is the default enforcement: two concurrent commands load version 42, one wins writing version 43, the other fails with a concurrency conflict and retries by rehydrating with the new events. This is lightweight and avoids holding locks, but it means your command handlers must be retry-safe and your events must be deterministic on re-apply. I have seen teams use SELECT FOR UPDATE on a pointer table to serialize commands for hot aggregates (e.g., a flash-sale wallet), but that is an exception for known contention points, not the baseline.
For cross-aggregate workflows, I use process managers and sagas rather than distributed transactions. A process manager listens for events and issues new commands, maintaining its own state as a projection. To coordinate OrderSubmitted → PaymentAuthorized → InventoryAllocated → ShipmentCreated, the manager tracks expected events, handles timeouts, and triggers compensations like PaymentRefunded if allocation fails. This is covered thoroughly in Event-Driven Architecture: Commands, Events and Sagas, and I would not attempt CQRS plus Event Sourcing at scale without a clear pattern for these long-running workflows.
| Concern | Traditional CRUD | CQRS Without Event Sourcing | CQRS With Event Sourcing |
|---|---|---|---|
| Source of truth | Current row / current state | Current row, read/write models may differ | Append-only event log; state is derived |
| Audit & temporal queries | Requires separate audit tables, often lossy | Possible via change-data capture, not canonical | Built-in: full history, replay to any point in time |
| Read/write scaling | Shared model, indexed for both | Independently optimized models | Independently optimized; replayable projections |
| Evolution cost | Schema migrations on live tables | Moderate: keep read models in sync | High: event versioning, upcasters, snapshots needed |
| Consistency model | Strong within transaction | Strong on write, eventual on read if separated | Strong per aggregate stream, eventual across projections |
| Best fit | Simple domains, low audit need | High read/write asymmetry or performance isolation | Domains where history, compliance, or temporal logic is core |
The table above is not a scorecard where Event Sourcing wins. In my assessments, the rightmost column describes the most powerful but also the most demanding setup. Every row where it “wins” introduces operational work you must staff.
Judging the Tradeoff: When the Complexity Actually Earns Its Keep
I now apply a fairly narrow filter before recommending CQRS with Event Sourcing. The system should have at least two of these traits:
First, business-relevant history is a requirement, not a nice-to-have. If compliance, dispute resolution, or customer support regularly asks “what did we know at time T and who decided it,” events answer that without forensic queries. On the logistics platform, we could reconstruct an order’s entire life for an auditor by replaying its stream — no supplemental logging needed.
Second, write and read behaviors are genuinely divergent. When reads need search, faceted filtering, or analytics-friendly shapes that would bloat a normalized write model, separated read models are a relief. When they do not — for example, a simple admin CRUD screen — CQRS adds movement without benefit.
Third, the domain has time-based reasoning: retroactive corrections, effective-dated changes, or “as-of” reporting. Events make temporal queries natural: apply events up to timestamp T to see the world as it was. Trying to answer “what was the price on the date the order was submitted, even though the price changed yesterday” with only current-state tables is consistently painful.
When those signals are absent, I lean toward simpler alternatives. A well-designed relational model with domain services, or CQRS without Event Sourcing (separate models over a shared state store), often delivers 80% of the benefit. I also consider team maturity and operational appetite. Event Sourcing requires expertise in observability for lag and replay, storage capacity planning for an always-growing log, and discipline around schema evolution. If you are simultaneously adopting Microservices vs Monolith: A Decision Framework for Teams and breaking a monolith apart, adding Event Sourcing on top may be too many variables at once. I prefer to introduce it inside a single well-bounded service — a bounded context that truly benefits — rather than as a platform-wide mandate.
If you do proceed, start narrow: one aggregate, one event store, two projections. Automate replay from day one. Measure projection lag with alerts, not intuition. Write a runbook for rebuilding a projection from scratch, and actually test it. And keep an ADR (Architecture Decision Record) that explicitly states what you traded away — ad-hoc reporting simplicity, newcomer onboarding speed, operational simplicity — so future revisits are honest about cost versus benefit.
Frequently Asked Questions
Does CQRS require Event Sourcing, or can we use them independently?
No, they are independent. CQRS is a separation of responsibilities between commands and queries. You can implement CQRS with a traditional database where the write model and read models share the same state store but are optimized differently. Conversely, you can use Event Sourcing without full CQRS by projecting events back into a single current-state model. I use them together only when both the separation benefit and the audit/history benefit are needed.
How do we handle GDPR or the right to be forgotten with an immutable event log?
Immutability does not mean you cannot address privacy. I use two complementary tactics: store personally identifiable information (PII) in a separate, cryptographically protected payload or external store and keep only a reference or pseudonymized key in the event; and when erasure is required, destroy the PII payload and its encryption key. Some teams also implement “tombstone” or “crypto-shredding” events. Do not rewrite historical events in place — design for erasure up front and get legal guidance on what constitutes compliance for your jurisdiction.
What about reporting and ad-hoc queries if all our truth is in events?
Do not query the event store directly for business reporting. Projections exist precisely for this. I maintain a relational projection optimized for reporting and rebuild it by replaying events. For ad-hoc exploration, I expose a separate analytics projection — often in a warehouse that is fed from event handlers. If stakeholders need truly arbitrary queries, keep a batch-synced relational replica. The event log is the system of record, but it is not a query engine.
How large can an event stream get before replay becomes a problem?
It depends on aggregate lifecycle and event size, but in practice I see degradation after a few hundred to a few thousand events per stream if you replay from zero every time. Mitigate with snapshots at regular intervals, and by keeping aggregates small and short-lived rather than modeling a never-ending entity (like a customer lifetime) as one stream. Measure p95 rehydration time in production and snapshot when it approaches your command latency budget. Snapshots remain an optimization — the event sequence stays canonical.