CQRS Write Side: Commands and Invariants
On this page
Learning Objective
Design a command and its handler correctly, place each kind of validation where it actually belongs, understand why a command handler must not query a read model to make a decision, and handle rejection, concurrency, and idempotency on the write path.
Concept Explanation
A command is a request to change state that can be refused. It is named in the imperative, it is addressed to exactly one handler, and it either succeeds or fails with a reason. That last property is the whole reason the write side exists as a distinct thing: the command handler is the only place in the system with the authority to say no, and everything about its design follows from protecting that authority.
A command handler does four things in a fixed order. It loads the aggregate that owns the decision, which in an event-sourced system means rehydrating from the stream and in a conventional one means selecting the rows inside a transaction. It validates the command against that aggregate's current state. It applies the change, either by appending events or by mutating and saving. And it returns an outcome, which is an acknowledgment and any identifier the caller needs, not the resulting view of the data. Handlers that return a fully populated read model are quietly recreating the coupling that CQRS separates, and they break the moment the read model moves to a different store.
Validation belongs in three distinct places and putting it in the wrong one causes specific, recognizable bugs. Structural validation, is the quantity an integer, is the email syntactically valid, is the currency code known, belongs at the edge before a command is ever constructed, because it needs no domain state and rejecting early is cheap. Domain invariant validation, does this order exceed the credit limit, is this seat still available, is the account in a state that permits withdrawal, belongs inside the aggregate, because it needs the aggregate's state and must be evaluated atomically with the change. Cross-aggregate rules, this customer may hold at most three active subscriptions, cannot be enforced atomically at all in a distributed model and must either be brought inside one aggregate by redrawing the boundary or handled eventually with detection and compensation, which is the saga territory of the final phase.
The rule that surprises people most is that a command handler must not consult a read model to make a decision. The read model is eventually consistent, so it may be stale by an unknown amount, and validating against it means the decision is based on a version of reality that may already be wrong. Checking uniqueness against a read-model index, for example, lets two concurrent commands both see no conflict and both succeed. Anything a decision depends on must be loaded from the write side, inside the consistency boundary, and enforced there, typically by a database constraint or by an expected-version append.
Two further write-side concerns are worth designing in from the start. Idempotency matters because clients retry: a command carrying a client-generated command id, recorded on first execution, lets a retry after a timeout return the original outcome instead of performing the work twice. And concurrency conflicts are normal rather than exceptional, so a handler should expect an expected-version failure or a serialization error and retry by reloading and revalidating, since revalidation is essential; blindly reapplying a command against newly changed state is how invariants get violated by a retry loop that was meant to be helpful.
| Validation | Example | Where it belongs | Failure if misplaced |
|---|---|---|---|
| Structural | Quantity must be a positive integer | At the edge, before the command is built | Malformed input reaches domain logic and produces obscure errors |
| Authorization | This user may act on this account | Before the handler, from the request context | Domain code becomes tangled with identity concerns |
| Domain invariant | Order total must not exceed the credit limit | Inside the aggregate, atomically with the change | Concurrent commands each see a valid state and jointly violate the rule |
| Uniqueness | This email is not already registered | A database constraint on the write side | A read-model check lets two concurrent registrations both succeed |
| Cross-aggregate rule | At most three active subscriptions per customer | A saga with detection and compensation | A synchronous check that is stale by the time it commits |
Worked Example: A Command Handler With Idempotency and Conflict Retry
The handler below refuses correctly, deduplicates client retries, and treats a concurrency conflict as an ordinary outcome that requires revalidation rather than a blind replay.
CREATE TABLE processed_commands (
command_id UUID PRIMARY KEY,
result_json JSONB NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
// The command: named imperatively, carries its own id so retries are safe.
// { commandId, orderId, sku, qty, unitPriceCents, expectedVersion }
async function handleAddItem(cmd, ctx) {
// 1. Structural validation - no domain state needed, so reject at the edge.
assertPositiveInt(cmd.qty, 'qty');
assertKnownSku(cmd.sku);
// 2. Idempotency - a retried command returns the original outcome.
const seen = await db.processedCommands.get(cmd.commandId);
if (seen) return seen.result_json;
for (let attempt = 0; attempt < 3; attempt += 1) {
try {
return await db.transaction(async (tx) => {
// 3. Load from the WRITE side. Never from a read model: it may be stale.
const order = await Order.load(tx, cmd.orderId);
// 4. Authorization, using request context rather than domain state.
if (order.customerId !== ctx.userId) throw new Forbidden();
// 5. The invariant, evaluated atomically with the change it guards.
order.addItem(cmd.sku, cmd.qty, cmd.unitPriceCents);
await order.save(tx, { expectedVersion: cmd.expectedVersion });
const result = { orderId: order.id, version: order.version };
await tx.query(
'INSERT INTO processed_commands (command_id, result_json) VALUES ($1, $2)',
[cmd.commandId, result],
);
return result; // an acknowledgment, NOT a rendered read model
});
} catch (err) {
if (err instanceof ConcurrencyError && attempt < 2) {
continue; // reload and REVALIDATE - the state has changed
}
throw err; // DomainError propagates to the caller as a refusal
}
}
}Real-World Examples
- Stripe, Shopify, and most payment and commerce APIs require or strongly recommend a client-supplied idempotency key on every state-changing request, for exactly the reason this lesson gives: a client that times out cannot tell whether the command was applied, so it retries, and the server must be able to recognize the retry and return the original outcome rather than performing the work again. The pattern has become close to universal among APIs where a duplicated command has financial consequences.
- Domain-driven design, as set out in Eric Evans's 2003 book and refined heavily in practice since, supplies the aggregate concept this lesson depends on: a consistency boundary within which invariants are enforced and which is loaded and saved as a unit. The rule that a transaction should modify exactly one aggregate, articulated forcefully by Vaughn Vernon in his work on implementing domain-driven design, is the direct ancestor of the CQRS write-side discipline described here and of the saga patterns that handle everything the rule excludes.
Review Questions & Answers
Because returning a view makes the write path depend on the read model, which is the coupling CQRS exists to remove. Assembling that view means either loading data the write side had no reason to load, which makes every command slower, or querying the read store, which may not yet reflect the write that just happened and would therefore return a stale answer to the very caller who made the change. Returning an identifier and a version lets the caller decide how to obtain the view, and lets the read model move to a different store later without changing the command contract.
Because the conflict means the aggregate changed between the read and the write, and the command was validated against the version that no longer exists. Another item may have pushed the order past the credit limit, the order may have been submitted and become uneditable, the account may have been frozen. Reapplying the change on top of the new state without re-running the invariant checks bypasses exactly the validation the handler exists to perform, which turns an ordinary conflict into a silent invariant violation. The retry must reload the aggregate and run the full decision again, and must be prepared to refuse this time.
On a unique constraint in the write-side database, not in application code and not in a read-model lookup. A check-then-insert in application code has a window between the check and the insert in which a concurrent request can insert the same value, so both pass the check and both insert. A read-model check is worse, since it may be stale by seconds. A unique constraint makes the check and the write a single atomic operation at the storage layer, so exactly one of two concurrent attempts succeeds and the other receives a violation the handler can translate into a clean refusal.
Because the rule spans multiple aggregates, and nothing in the write model makes a count across aggregates atomic with the creation of a new one. Two concurrent commands can each count two existing subscriptions, each conclude that a third is permitted, and each create one, leaving four. There are three honest options: redraw the boundary so the customer aggregate owns its subscriptions and the count is enforced inside one consistency boundary, which is correct if the rule is genuinely hard; accept eventual enforcement with a detection process and a compensating action, which is the saga approach; or place a constraint in the database that makes the count enforceable atomically. What is not an option is a count in a handler that appears to work in testing and fails under concurrency.