Practical technical guides / Agent-era architecture: CQRS (read-your-own-write through a lagging projection)

An Agent Reads a Projection Before Its Own Write Lands: Return the Write Position and Wait for It

An agent reads a CQRS view before its own write lands and resends the command. Return the write position and wait for the checkpoint: 28 stale decisions became 0.

By Sandeep Belgavi · Published 2026-11-18

Read your own write: wait for the projection position
Original explanatory diagram; synthetic values where shown.

An agent reads a CQRS view before its own write lands and resends the command. Return the write position and wait for the checkpoint: 28 stale decisions became 0.

The agent wrote, then read something older

Jenya's help-desk agent at Belgavi's Book Store handles case CASE-7201. The customer wants to return a damaged hardback from order BB-1701. The agent calls the record_return tool, which sends a command to the orders service. The command succeeds. The agent then calls get_case_view to write its reply, and the case view says no return exists for BB-1701.

Nothing failed. The orders service uses CQRS: commands change the write model and append an event, and a projector reads the events and updates a separate read model that the case view serves. The projector had not applied the new event yet. A person reading that screen a second later would see the return. The agent read it 100 milliseconds later, concluded the return had not been recorded, and called record_return again.

Read models that lag their write model are normal and usually harmless, because people rarely read their own write within a fraction of a second. Agents do it on every turn: act, observe, decide. Any system that adds an agent on top of a CQRS read side needs a rule for the read that follows the agent's own write.

What goes wrong, measured on a synthetic stream

The companion model replays 40 agent turns. Each turn writes one command; the projector applies events in order, each after a transport delay of 20 ms plus up to 100 ms of jitter, and spends 30 ms applying it. The agent reads its view 100 ms after writing. Every number is a seeded synthetic draw, not a measurement of a real event store.

Read strategyDecisions on a stale viewDuplicate returnsMean wait
Read immediately28 of 40280 ms
Read immediately, write side deduplicates28 of 400 (28 suppressed)0 ms
Wait for the write position0035 ms

Two results deserve attention. First, deduplication on the write side removes the duplicate effect but not the stale decision: the agent still told 28 customers something that was no longer true, and still spent a tool call on each resend. Idempotency is necessary, but it is not a consistency model. Second, waiting cost little. The longest wait was 50 ms, one poll interval, because the projector was healthy.

When the projector cannot keep up, the picture changes. Raising the apply time from 30 ms to 70 ms, above the 50 ms between commands, makes the lag grow with every event. Reading immediately is then stale on all 40 turns, the lag reaches 910 ms, and the waiting strategy still answers correctly but waits 440 ms on average and up to 850 ms. A growing wait is the signal to fix the projector, not to remove the wait.

Return the position, wait for the checkpoint

The pattern has three parts, and none of them involves the model.

  1. The command handler returns the position of the event it appended, such as a global sequence number or a stream revision, along with the result.
  2. The projector records the position of the last event it applied, its checkpoint, in the same transaction that updates the read model.
  3. A read that must reflect a given write passes that position. The read side returns the view only when its checkpoint has reached the position, polling or blocking until a deadline.

In the tool layer it looks like this:

def record_return(case_id, order_ref, reason):
    result = orders.handle(RecordReturn(case_id, order_ref, reason))
    session.min_position = max(session.min_position, result.position)
    return {'status': result.status, 'position': result.position}


def get_case_view(case_id, deadline_ms=1000, poll_ms=50):
    waited = 0
    while projector.checkpoint() < session.min_position:
        if waited >= deadline_ms:
            return on_projection_timeout(case_id)
        sleep_ms(poll_ms)
        waited += poll_ms
    return case_views.load(case_id)

The session keeps the highest position this agent session has written, so every later read in the same session sees at least its own writes. Reads by other sessions are unaffected and keep the cheaper eventual behaviour. The model never sees the position; the tools carry it.

Decide what happens when the wait times out

A projector can stall: a deployment, a poison event, a lock. In the model a 1,500 ms stall before turn 20 pushes the lag to 1,618 ms and makes 21 turns exceed the 1,000 ms deadline. What the tool does next is a policy decision, and the three options give very different results:

On timeoutStale decisionsDuplicatesCorrect replies
Read the write model instead0040
Tell the customer the change is pending0019, plus 21 honest pending replies
Proceed with the stale view212119

Reading the authoritative write model is correct but moves load onto the side CQRS was meant to protect, so cap it and alert on it. Reporting the change as pending is safe when the customer only needs confirmation. Proceeding with the stale view is the one choice that should never be the default, because it brings back the original bug exactly when the system is already under stress.

What stays deterministic

The agent decides whether a return is warranted and what to say. The read-your-own-write guarantee, the deadline and the timeout policy live in code the agent cannot change. The tool returns an explicit status, pending or fresh, rather than an empty view, so the model is never asked to infer consistency from the absence of a record. Tests can assert all of it without a model: given a checkpoint behind the session position, get_case_view must wait, then either return the fresh view or the configured timeout outcome.

Migrating an existing CQRS system

  1. Measure first. Log, for each agent read, the gap between the session's last write position and the projector checkpoint. If it is always zero, stop here.
  2. Make command handlers return the appended position. Many event stores return it from an append; check whether your application layer discards it.
  3. Store the projector checkpoint in the read-model transaction, not in a separate file or cache, or the checkpoint can run ahead of the data.
  4. Add the position wait to the tool wrappers the agent uses, with a deadline and a timeout policy per tool, and keep human-facing screens unchanged.
  5. Add write-side deduplication anyway. The wait prevents stale decisions; idempotency limits the damage when something else goes wrong.
  6. Alert on timeouts and on fallback reads, and watch the mean wait as a lag metric.

When you do not need this

If the agent never reads a view right after writing to it, there is nothing to fix. If the write model is cheap to query and small, have the agent read it directly, which the model shows is always fresh, and skip the projection for that tool. If the read model is updated synchronously in the same transaction as the write, it cannot lag. And if a slightly stale answer is acceptable to the customer, such as a weekly order summary, an explicit as of timestamp in the tool result may be all the agent needs.

Failure modes to test

  • The checkpoint is committed before the read model rows, so the wait returns early with stale data.
  • Positions are per stream but the checkpoint is global, or the reverse; compare like with like.
  • A rebuilt projection restarts from zero and every agent read times out until it catches up.
  • The session position is lost when an agent turn moves to another worker, so the next read is unguarded.
  • The deadline is longer than the agent's own tool timeout, so the agent gives up first and retries the read in a loop.

Interactive experiment

Projection lag: read your own write with a position token. Synthetic browser-local fixtures, adjustable inputs, decision traces and JSON export.

Primary references and authorship

Original explanation and synthetic examples by Sandeep Belgavi. Companion code: Sandeep-BA/agent-decision-lab/examples/python/projection_read_own_write. Views are my own and do not represent any employer, past or present.