Chronicle consistency: choose a guard for a write
Use a constraint when a value must be unique, a decision read when a write depends on current state, and an explicit concurrency scope when you need to check the revision a user saw. Each addresses a different way concurrent writes can invalidate a decision.
This guide is for code that appends through the Chronicle client directly, such as an endpoint or worker. Examples use the .NET and Elixir clients; API names in the comparisons below are from .NET. If Cratis Arc runs your commands, start with Choosing how a command’s rule holds for the integration that manages reads and commits.
The short answer
Section titled “The short answer”A constraint is checked by the kernel inside the append, for every writer. Use it for uniqueness or create-once rules instead of checking a read model first.
A decision read returns state together with a guard for the append. Pass the read to AppendMany(guardedBy:): if a relevant event arrived after its captured position, the append is rejected. For a rule across two keys, guard with both reads in one AppendMany. Write to each source whose history needs the new fact; a guarded source does not have to receive an event.
An explicit concurrency scope lets you supply the position and filter yourself. For an editing conflict, use the revision the user saw, rather than a fresh read that would hide the intervening change.
A plain read through IReadModels, or an unguarded injected read model, only shows state. It neither captures a position nor protects the append that follows.
Where this fits in DCB
Section titled “Where this fits in DCB”The Dynamic Consistency Boundary pattern makes an append conditional on the facts a decision used. A Chronicle concurrency scope expresses that condition as a position and a filter. A decision read builds the scope before it folds events into state, and refuses models whose event dependencies it cannot guard exactly.
Chronicle uses event source and stream metadata for these filters, not custom tags. Each event has one event source ID. If both entities need the fact in their histories, append one event to each in the same batch. Chronicle’s mapping explains the difference from tag-based DCB; DCB examples in Chronicle shows when a constraint or a single event is enough.
Decide by the shape of the rule
Section titled “Decide by the shape of the rule”| Rule shape | Use | Alternatives | Never use | Too much |
|---|---|---|---|---|
| A value is unique (username, email, ISBN) | Constraint: [Unique] on the property, or an IConstraint |
None needed. Choose per event source or per value, and release with a removal event | Reading a read model first, then appending | A decision read or a scope: they guard one key’s history, not a value across keys |
| Something is created once | Constraint: [Unique] on the event type (one event of that type per event source) |
ExpectingNoMatchingEvent() on the append for a one-off that is not worth a constraint |
“Does it exist?” read, then append | A decision read |
| A rule over one key’s history (cannot ship before payment, cannot cancel twice) | Decision read of a flat projection keyed by that event source | An explicit scope, with the tail captured before you read the events | A plain read model | Hand-rolled folds when a projection can express the state |
| Stock or count on one key (copies left, loans per member) | Decision read of a projection with [Increment] and [Decrement] |
An explicit scope on the event types you counted | A materialized counter read with no guard | None, but see the cost of a hot key |
| A rule across two keys (course capacity and a student’s course limit) | One decision read per key, one AppendMany, with an event on each source whose history must change |
Put every fact the rule needs on one event source, then use one read | Two separate appends, or a guard on only one side | None |
| An editing conflict (two people change the same record) | Explicit scope built from the revision the user saw | A decision read when the conflict only matters inside one request | Last writer wins by accident | A constraint |
| One stream inside an event source | A decision read scoped to the stream type and stream ID. Declare the stream with an event source definition so the read and the append share its names, see Event sources and the Dynamic Consistency Boundary | An explicit scope with stream type and stream ID | A read over the whole source when only one stream matters: you get conflicts from other streams | None |
| A monthly or per-process limit on one account, where a whole-source read would mix periods | A per-stream read model: [EventStream<TSource>("Transactions")] on the model, read with the stream ID. It is passive and folds that one stream |
A stream-scoped decision read of a source-keyed projection you declare yourself | A key-only read of the model: it is refused | A materialized, whole-account model |
| Every decision read in a command or request host must be guarded, with no way to forget one | Read protection: EnforceReadProtection() on the unit of work. In Arc, set read protection to On |
GetDetached with AppendMany(guardedBy:), or IDecisionReads.Get with transactional appends and an owner commit |
Plain IReadModels reads and immediate appends in the same invocation: they are refused |
Read protection around one guarded append |
| Rich behaviour (many rules over one lifecycle) | A decision read of a richer flat projection. In Arc, an aggregate root | Several decision reads, one per concern | Rules spread over validators and plain read-model checks | An aggregate where one counter rule would do |
| A rare violation is acceptable | Append normally, then repair: a reactor appends a correcting event | A constraint for whatever part is cheap to enforce | Presenting a plain read as a guard | A decision read |
| A UX hint (disable a button, show “seats left”) | A plain read of a materialized read model | None | Treating the hint as enforcement | A decision read: it costs several calls and a full fold |
| The rule depends on data outside Chronicle | Record the external fact as an event first, then decide on the event | Accept the risk and repair | Assuming a decision read covers it | None |
| A hot key with a long history | Keep each key’s history short: split the key by period or by stream | A constraint if the rule is uniqueness. Accept an advisory read and repair | Ignoring the cost: every decision read folds the key’s whole history again | None |
A flowchart for the same choice
Section titled “A flowchart for the same choice”Scenarios shows each branch as code.
How the options compare
Section titled “How the options compare”| Option | Sees committed events | Captures a position before it reads | Guards the append | Use it for |
|---|---|---|---|---|
| Constraint | Not a read. Checked inside the append | Not needed | Yes, for every writer | Uniqueness, create once, closed streams |
| Decision read | Yes. It folds the key’s events in a fresh session | Yes, before the fold | Yes: events of the model’s types for that key after the position | State rules on one or a few keys |
| Explicit concurrency scope | Whatever you read | Only if you capture the tail before you read | Yes: events that match the scope after the position | Revisions the user saw, rules you read yourself |
| Default optimistic append | Not a read | Reads the tail at append time | Only the window between that read and the write | Nothing that depends on state |
| Plain read of a materialized read model (projection, reducer or self-reducing model) | No. It can lag the log | No | No | Display, hints |
| Plain read of a passive projection | Yes, at read time | No | No | Display, checks you will repair |
| Plain read of a passive reducer (classic or self-reducing) | Yes, at read time | No | No. A plain read guards nothing, but a qualifying reducer can be read as a decision read | Display, checks you will repair |
| Reading the sink’s database directly | No. Same lag as a materialized read | No | No | Reports. It couples you to the sink’s schema, so avoid it in command logic |
Freshness depends on whether a read model is materialized or passive, not on whether a projection, reducer or self-reducing model builds it. Materialized read models store their state and update asynchronously after appends. Passive read models fold events when you read them instead of storing the result. Declare one with [Passive] on the model or .Passive() on a declarative projection. Neither kind of plain read records a position for a later concurrency check, so freshness alone does not protect the decision.
Capturing the tail yourself before a plain read does not fix this. A materialized read model can lag the log, so the state you see can be older than the position you captured, and the events in between are neither seen nor guarded. A decision read folds a fresh session and checks that the fold reached the events it expected, which is why you should not rebuild it by hand.
This is the shape that looks safe and is not:
using Cratis.Chronicle.Events;using Cratis.Chronicle.EventSequences;using Cratis.Chronicle.Projections.ModelBound;using Cratis.Chronicle.ReadModels;
[EventType]public record SeatOpened(string Row);
[EventType]public record SeatClaimed(string ClaimedBy);
[FromEvent<SeatOpened>]public record SeatAvailability( Guid Id, [Count<SeatClaimed>] int Claims);
public static class ClaimSeatWithAPlainRead{ // Do not use this to make a rule hold. Two requests can both read Claims = 0 // and both append. The read guards nothing. public static async Task<bool> Claim(IReadModels readModels, IEventLog eventLog, Guid seatId, string claimedBy) { var seat = await readModels.GetInstanceById<SeatAvailability>(seatId); if (seat.Claims > 0) { return false; }
var result = await eventLog.Append(seatId, new SeatClaimed(claimedBy)); return result.IsSuccess; }}defmodule MyApp.Events.PlainReadRaceSeatOpened do use Chronicle.Events.EventType, id: "plain-read-race-seat-opened"
defstruct [:row]end
defmodule MyApp.Events.PlainReadRaceSeatClaimed do use Chronicle.Events.EventType, id: "plain-read-race-seat-claimed"
defstruct [:claimed_by]end
defmodule MyApp.ReadModels.PlainReadRaceSeatAvailability do use Chronicle.ReadModels.ReadModel
defstruct id: nil, claims: 0
from MyApp.Events.PlainReadRaceSeatOpened, set: [id: :event_source_id] from MyApp.Events.PlainReadRaceSeatClaimed, count: :claimsend
defmodule MyApp.ClaimSeatWithAPlainRead do alias Chronicle.EventSequences.EventLog alias MyApp.Events.PlainReadRaceSeatClaimed
# Do not use this to make a rule hold. Two requests can both read claims = 0 # and both append. The read guards nothing. def claim(seat_id, claimed_by) do {:ok, seat} = Chronicle.read_model(MyApp.ReadModels.PlainReadRaceSeatAvailability, seat_id)
if seat != nil and seat.claims > 0 do false else EventLog.append(seat_id, %PlainReadRaceSeatClaimed{claimed_by: claimed_by}) == :ok end endendTwo requests can both read Claims as 0 and both append. A constraint, or a decision read on the seat, closes that race.
A read model injected into an Arc command or validator is also a plain read unless Arc is set to guard it. See Validators and protected decisions.
When not to use a decision read
Section titled “When not to use a decision read”| Do not use it when | Because | Use instead |
|---|---|---|
| The rule is uniqueness or create-once | A constraint is checked inside the append, costs no extra reads and covers every writer | Constraint |
| The read feeds a screen or a hint | You pay for a fresh fold and a guard you do not use | A plain read |
The state has joins, children, derivatives or a key that is not the event source ID, or is a classic reducer with filters or constructor dependencies other than ILogger<T> |
Chronicle refuses these shapes, because a guard it cannot compute exactly would be wrong. A self-reducing read model is exempt from the dependency rule | A flat projection keyed by event source, or a reducer without filters, and without dependencies unless it is self-reducing. See admitted projections and reducers |
| The key has a long history and many writers | Each read folds the whole history and conflicts rise with the write rate | Shorter keys, or accept an advisory read and repair |
| The data lives outside the Chronicle event log | Nothing in the log can invalidate it | Record the fact as an event |
The same applies to the other mechanisms:
| Do not use | When | Use instead |
|---|---|---|
| A constraint | The rule counts, sums or compares, or depends on state that changes over time | A decision read |
| An explicit concurrency scope | The decision is based on something you read yourself and you cannot capture the position before you read | A decision read, which notes the position first |
| Explicit scopes and decision reads together on one source | You are not under read protection: the append is refused | One of them, or read protection with a scope that covers every read. See How guards are derived |
| A per-stream read model | The rule spans the whole source, or another stream, or the key is the stream ID, or it must be a reducer | A whole-source decision read, or a stream-scoped read of a projection you declare |
| Read protection | You guard one append and pass the read to AppendMany(guardedBy:), the rule is a uniqueness rule, or you do not own the code that begins and completes the unit of work |
The guarded append, or a constraint |
Why protection is opt-in
Section titled “Why protection is opt-in”Chronicle does not guard an earlier decision unless you ask. An Append with no scope gets the default optimistic check, which covers only the window between its tail read and the write; the first append into an empty scope is unchecked by default. A detached decision read protects the append you pass it to. Reads enrolled in a unit of work protect that unit’s commit.
A host can enforce read protection for a whole invocation. This changes which operations are allowed: unguarded plain reads, immediate appends and commits by anyone but the unit’s owner are refused. Models the client cannot guard exactly are also refused. Enabling it on existing code therefore needs a review of that code’s reads and commit ownership, not just a configuration change. Each decision read also incurs a fresh fold; weigh that cost for the rules you need to protect.
Chronicle has no application-wide switch that makes protection the default. Opt in per unit of work with EnforceReadProtection(). Arc’s own switch is described on its consistency page.
For other approaches to append conditions, see the DCB specification, Axon Framework 5 event-store internals and KurrentDB appending guidance.
What Arc adds
Section titled “What Arc adds”| Arc feature | What it gives you | Where to read |
|---|---|---|
| Guarded read-model parameters on a command | The command’s read models become decision reads, committed by the command’s owner | Choosing how a command’s rule holds |
Stream decisions (IStreamReads) |
A guard on every event in one stream | Stream decisions |
| Aggregate roots | A guard on the event types the aggregate handles, taken before the events are applied | Aggregate roots |
CommandValidator<T> |
Shape rules, and early feedback on state | Validators and protected decisions |
Read protection maps Arc’s modes to the Chronicle API they drive.
Next steps
Section titled “Next steps”- Scenarios: each rule shape as working code.
- Costs and limits: what a decision read costs and where a guard does not apply.
- How guards are derived: what an append conflicts with, and how guards merge.
- Decision reads: the API, admission rules and limits.
- Read protection: make a host refuse unguarded reads and immediate appends.
- DCB examples in Chronicle: the canonical DCB examples, the Chronicle way.
- Concurrency: scopes, the builder and the first-append check.
- Event sources and streams: declare the dimensions an append is guarded by.
- Questions and answers.