Skip to content

Chronicle consistency rules by example

Use an append-time constraint in Cratis Chronicle for uniqueness, a decision read for a limit derived from events, or an explicit scope to protect what a user saw. The examples below show how each choice handles competing writers. If you have not chosen a mechanism, start with Choosing how a rule holds. Most examples have .NET and Elixir tabs; the per-stream model declaration is .NET-only.

Level Rule Mechanism Scenario
Simple A username must be unique Constraint Unique username
Simple An account can be opened once Constraint Create once
Simple A member may have three loans Decision read A limit on one key
Two entities A course has seats, a student has a course limit Two decision reads, one AppendMany A rule across two keys
Inside one stream An account may withdraw 5000 a month Decision read scoped to one stream A limit inside one stream
Inside one stream The same limit, with the stream declared on the read model Per-stream read model With a per-stream read model
Process A customer’s onboarding has steps and an end Stream guard and a closing event A process with steps and an end
Numbering Invoice numbers have no gaps One numbering source, one decision read Gapless invoice numbers
Editing Two people edit the same project Explicit concurrency scope An editing conflict
Host The same rule in an ASP.NET Core endpoint Decision reads in a unit of work In an ASP.NET Core endpoint
Repair Overbooking is rare and fixable Repair with a reactor A rare violation you can repair
Test Show that a guard rejects a race Read, append a competing event, append Test the race

Start with the rule closest to yours. Keep its facts on the source or stream the guard watches, and check the append result before reporting success.

A value, a create-once rule, or a limit on one key.

A username must be unique. Declare it on the event and append as usual.

Use a constraint because the value must be unique across keys. A decision read on one user’s source cannot detect the same username being registered on another source.

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Events.Constraints;
using Cratis.Chronicle.EventSequences;
[EventType]
public record UserRegistered([property: Unique] string Username, string Email);
public static class UserRegistration
{
public static async Task<string?> Register(IEventLog eventLog, EventSourceId userId, string username, string email)
{
var result = await eventLog.Append(userId, new UserRegistered(username, email));
if (result.IsSuccess)
{
return null;
}
// The kernel rejected the append, so this holds for every writer, not only this one.
return result.HasConstraintViolations
? result.ConstraintViolations.First().Message.Value
: "The user could not be registered.";
}
}

View C# snippet source on GitHub

The kernel checks the constraint inside the append, before the event is written. Two requests that register the same username at the same time cannot both succeed: one append is rejected and returns a result with a constraint violation. Because the kernel enforces it, the rule also holds for a writer that is not this application.

Read the result. An append that fails a constraint does not throw. If you ignore the result, the registration is lost without an error.

Uniqueness is checked within one event sequence in one namespace. Two tenants in different namespaces can hold the same username. To let a user change their username and release the old one, or to release it when the user is removed, see model-bound constraints and declarative constraints. The reasoning is in Understanding constraints.

An account can be opened only once. Put [Unique] on the event type.

The event-type constraint enforces this at append time. Reading whether the account exists and then appending without a guard leaves a race between those operations.

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Events.Constraints;
[EventType]
[Unique]
public record AccountOpened(string Owner);

View C# snippet source on GitHub

The kernel accepts one AccountOpened per event source. A second one for the same event source is rejected with a constraint violation, even when two requests race. Do not write “does the account exist?” against a read model and then append: two requests can both see that it does not.

A member may have at most three active loans. The rule is a count over one key’s history, so use a decision read.

The guard watches the member’s source and the model’s event types after the tail captured by the read. A plain read contributes no guard, and reading a loan’s own source would watch the wrong history.

using Cratis.Chronicle;
using Cratis.Chronicle.Events;
using Cratis.Chronicle.EventSequences;
using Cratis.Chronicle.Projections.ModelBound;
using Cratis.Chronicle.ReadModels;
[EventType]
public record MemberRegistered(string Name);
[EventType]
public record LoanTaken(string Isbn);
[EventType]
public record LoanReturned(string Isbn);
[FromEvent<MemberRegistered>]
public record MemberLoans(
Guid Id,
[Increment<LoanTaken>]
[Decrement<LoanReturned>]
int Active);
public enum TakeLoanOutcome
{
Taken,
UnknownMember,
LimitReached,
ChangedConcurrently,
Failed
}
public static class TakeLoan
{
const int MaxActiveLoans = 3;
public static async Task<TakeLoanOutcome> Handle(IEventStore eventStore, Guid memberId, string isbn)
{
var member = await eventStore.GetDecisionReads().GetDetached<MemberLoans>(memberId);
if (member.Instance is not { } loans)
{
return TakeLoanOutcome.UnknownMember;
}
if (loans.Active >= MaxActiveLoans)
{
return TakeLoanOutcome.LimitReached;
}
var result = await eventStore.EventLog.AppendMany(
[new EventForEventSourceId(memberId, new LoanTaken(isbn))],
guardedBy: [member]);
if (result.GetDecisionConflicts([member]).Any())
{
// Another loan or return was appended for this member after the read. Nothing was appended.
return TakeLoanOutcome.ChangedConcurrently;
}
return result.IsSuccess ? TakeLoanOutcome.Taken : TakeLoanOutcome.Failed;
}
}

View C# snippet source on GitHub

MemberLoans is a flat projection keyed by the member’s event source, with an Id property identifying that key. In .NET, [Increment] and [Decrement] maintain the count; the Elixir model uses add and subtract mappings. Both LoanTaken and LoanReturned must be written on the member’s source. Events on a loan’s own source would be missing from the member’s count.

The .NET example uses GetDetached to capture the tail before folding, then attaches the returned guard with guardedBy: [member]. The Elixir example enrolls the read and stages the append inside Chronicle.decide. If MemberRegistered, LoanTaken or LoanReturned arrives for this member after the read, the guarded append is rejected. Appends for another member, or of an unrelated type, do not conflict with this filter.

When the guard rejects the append, read again and decide again. Chronicle does not retry for you: the new state can change the answer.

Two cautions:

  • A GUID key must be in lowercase canonical form (D) in every writer, including writers that are not .NET.
  • If loans can start on a source nobody reads, a new key is in nobody’s guard. Keep the rule on the one key that carries the facts.

A rule that spans two keys.

A course has a capacity, and a student may take at most five courses. Neither number lives in one place, so you need two reads and two events.

Both source guards must protect one atomic append. Separate appends could record the course’s seat without the student’s subscription; guarding only one side leaves the other limit exposed.

using Cratis.Chronicle;
using Cratis.Chronicle.Events;
using Cratis.Chronicle.EventSequences;
using Cratis.Chronicle.Projections.ModelBound;
using Cratis.Chronicle.ReadModels;
[EventType]
public record CourseDefined(string Name, int Capacity);
[EventType]
public record CourseCapacityChanged(int Capacity);
// Events of the course's own story.
[EventType]
public record CourseSeatTaken(Guid StudentId);
[EventType]
public record CourseSeatReleased(Guid StudentId);
// Events of the student's own story.
[EventType]
public record StudentJoinedCourse(Guid CourseId);
[EventType]
public record StudentLeftCourse(Guid CourseId);
[FromEvent<CourseDefined>]
public record CourseSeats(
Guid Id,
[SetFrom<CourseDefined>(nameof(CourseDefined.Capacity))]
[SetFrom<CourseCapacityChanged>(nameof(CourseCapacityChanged.Capacity))]
int Capacity,
[Increment<CourseSeatTaken>]
[Decrement<CourseSeatReleased>]
int Subscribed);
[FromEvent<StudentJoinedCourse>]
public record StudentCourses(
Guid Id,
[Increment<StudentJoinedCourse>]
[Decrement<StudentLeftCourse>]
int Subscribed);
public enum SubscribeOutcome
{
Subscribed,
UnknownCourse,
CourseIsFull,
StudentHasTooManyCourses,
ChangedConcurrently,
Failed
}
public static class SubscribeStudentToCourse
{
const int MaxCoursesPerStudent = 5;
public static async Task<SubscribeOutcome> Handle(IEventStore eventStore, Guid courseId, Guid studentId)
{
var reads = eventStore.GetDecisionReads();
var course = await reads.GetDetached<CourseSeats>(courseId);
var student = await reads.GetDetached<StudentCourses>(studentId);
if (course.Instance is not { } seats)
{
return SubscribeOutcome.UnknownCourse;
}
if (seats.Subscribed >= seats.Capacity)
{
return SubscribeOutcome.CourseIsFull;
}
if ((student.Instance?.Subscribed ?? 0) >= MaxCoursesPerStudent)
{
return SubscribeOutcome.StudentHasTooManyCourses;
}
// One fact, two event sources, two event types: each read model counts only the types of its own source.
var result = await eventStore.EventLog.AppendMany(
[
new EventForEventSourceId(courseId, new CourseSeatTaken(studentId)),
new EventForEventSourceId(studentId, new StudentJoinedCourse(courseId))
],
guardedBy: [course, student]);
if (result.GetDecisionConflicts([course, student]).Any())
{
// Either side changed after it was read. Nothing was appended for either source.
return SubscribeOutcome.ChangedConcurrently;
}
return result.IsSuccess ? SubscribeOutcome.Subscribed : SubscribeOutcome.Failed;
}
}

View C# snippet source on GitHub

Chronicle stores one event source ID per event, so one fact about two entities is written as two events, one per source. Where DCB tags one event with both entities, Chronicle records the fact once for each. DCB examples in Chronicle says when that is acceptable. The two events have their own types, CourseSeatTaken and StudentJoinedCourse, so each read model folds only its own. AppendMany writes them atomically: either both are appended or neither is. Both decision reads guard the same append. If another student takes the last seat, or the student subscribes elsewhere, after you read, the append is rejected and neither event is written.

In .NET, GetDecisionConflicts identifies which read was invalidated. Read that state again before reporting that the course is full: a conflict means relevant facts changed, not necessarily that the new decision must be rejected.

A rule about one part of one entity.

An account may withdraw at most 5000 a month. The rule concerns one account’s Transactions stream for one month, so read that stream and nothing else. Use a decision read scoped to the stream.

using Cratis.Chronicle;
using Cratis.Chronicle.Events;
using Cratis.Chronicle.EventSequences;
using Cratis.Chronicle.EventSources;
using Cratis.Chronicle.Projections.ModelBound;
using Cratis.Chronicle.ReadModels;
public record BankAccountId(string Value) : EventSourceId(Value);
[EventType]
public record MoneyWithdrawn(decimal Amount);
// Names the source type and the stream, so the read and the append use the same values.
[EventSource("BankAccount")]
[EventStream("Transactions", Description = "Deposits and withdrawals, one stream per month")]
public class BankAccountEventSource : IEventSource;
// The decision model: what this account has withdrawn in the stream the read is scoped to.
[Passive]
[FromEvent<MoneyWithdrawn>]
public record WithdrawnThisMonth(string Id, [AddFrom<MoneyWithdrawn>(nameof(MoneyWithdrawn.Amount))] decimal Total);
public enum WithdrawOutcome
{
Withdrawn,
MonthlyLimitReached,
ChangedConcurrently,
Failed
}
public static class Withdraw
{
const decimal MonthlyLimit = 5000m;
// month is the stream ID, for example "2026-10".
public static async Task<WithdrawOutcome> Handle(IEventStore eventStore, BankAccountId account, string month, decimal amount)
{
var definition = eventStore.EventSources.GetFor(typeof(BankAccountEventSource));
var transactions = definition.FindStream("Transactions")!;
// Reads only BankAccount / Transactions / month, and guards only that stream.
var read = await eventStore.GetDecisionReads().GetDetached<WithdrawnThisMonth>(
account,
transactions.EventStreamType,
month,
definition.EventSourceType);
if ((read.Instance?.Total ?? 0m) + amount > MonthlyLimit)
{
return WithdrawOutcome.MonthlyLimitReached;
}
var result = await eventStore.EventLog.AppendMany(
[
new EventForEventSourceId(account, new MoneyWithdrawn(amount))
{
EventSource = typeof(BankAccountEventSource),
EventStream = "Transactions",
EventStreamId = month
}
],
guardedBy: [read]);
if (result.GetDecisionConflicts([read]).Any())
{
// A withdrawal in this month's stream was appended after the read. Nothing was appended.
return WithdrawOutcome.ChangedConcurrently;
}
return result.IsSuccess ? WithdrawOutcome.Withdrawn : WithdrawOutcome.Failed;
}
}

View C# snippet source on GitHub

guard BankAccount-7: types=[MoneyWithdrawn], sourceType=BankAccount, streamType=Transactions, streamId=2026-10, after <tail at read>

The .NET example takes the source type and stream type from the event source definition; the Elixir example supplies the matching route to its read. In both, the month is the stream ID and the append must use the same routing values.

WithdrawnThisMonth sums MoneyWithdrawn for that account in 2026-10. A withdrawal in another month does not affect the sum or match the guard. Neither does a deposit, because the model uses only MoneyWithdrawn. A second withdrawal in October invalidates the decision.

A constraint can enforce uniqueness, but it cannot calculate this running withdrawal total.

Why not read the whole account? It works, but the guard then covers every month, so a withdrawal in October conflicts with one in November. The narrower read removes conflicts the rule does not need.

Two cautions:

  • In .NET, a read-protection frame with kernel conjunction support keeps October and November as separate predicates. Without that support, the conservative merged guard widens differing dimensions. Outside a frame, the legacy merge drops both stream dimensions when they differ. See How guards are derived.
  • A stream-scoped read needs a specific stream type and a kernel that acknowledges stream scope. See Scoped to one event stream.

The same code in an event source definition with declared dimensions is in Event source scenarios.

A limit inside one stream with a per-stream read model

Section titled “A limit inside one stream with a per-stream read model”

The same monthly limit, with the stream declared on the read model so that no read can fold more than that stream. Put [EventStream<TSource>("Transactions")] on the model. It is passive, keyed by the account, and a read must name the stream.

namespace PerStreamScenario
{
using Cratis.Chronicle;
using Cratis.Chronicle.Events;
using Cratis.Chronicle.EventSequences;
using Cratis.Chronicle.EventSources;
using Cratis.Chronicle.Projections.ModelBound;
using Cratis.Chronicle.ReadModels;
public record SavingsAccountId(string Value) : EventSourceId(Value);
[EventType]
public record SavingsWithdrawn(decimal Amount);
[EventSource("SavingsAccount")]
[Cratis.Chronicle.EventSources.EventStream("Transactions")]
public class SavingsAccountEventSource : IEventSource;
// Passive, keyed by the account, and folded from the Transactions stream only.
[EventStream<SavingsAccountEventSource>("Transactions")]
public record WithdrawnInMonth(
SavingsAccountId Id,
[AddFrom<SavingsWithdrawn>(nameof(SavingsWithdrawn.Amount))] decimal Total);
public static class WithdrawSavings
{
const decimal MonthlyLimit = 5_000m;
public static async Task<bool> Handle(
IEventStore eventStore, SavingsAccountId account, EventStreamId month, decimal amount)
{
var definition = eventStore.EventSources.GetFor(typeof(SavingsAccountEventSource));
var read = await eventStore.GetDecisionReads().GetDetached<WithdrawnInMonth>(
account, "Transactions", month, definition.EventSourceType);
if ((read.Instance?.Total ?? 0m) + amount > MonthlyLimit)
{
return false;
}
var result = await eventStore.EventLog.AppendMany(
[new EventForEventSourceId(account, new SavingsWithdrawn(amount))
{
EventSourceType = definition.EventSourceType,
EventStreamType = "Transactions",
EventStreamId = month
}],
guardedBy: [read]);
return result.IsSuccess;
}
}
}

View C# snippet source on GitHub

The guard watches SavingsWithdrawn on SavingsAccount-7, narrowed to source type SavingsAccount, stream type Transactions and the month, after the read’s captured tail. A materialized whole-account model would mix months.

The declaration makes an incorrectly scoped read fail instead of folding more history. A key-only read is refused with ReadModelRequiresStreamScope; another stream type or a missing source type is refused with StreamScopeDoesNotMatchReadModel. See Read models scoped to one event stream for the refusals and the plain-read overload.

Writers must use the definition’s route too: an event without the source type is neither folded nor guarded. CHR0064 reports an invalid declaration at build time. How guards are derived explains what happens when a command adds more reads.

Rules about a sequence, a lifecycle or what a user saw.

A customer’s onboarding has steps, and a finished onboarding accepts nothing more. The stream is the consistency boundary: every writer of one customer’s onboarding must see every other. Declare the dimensions on the definition, and close the stream with an event.

Here the guard watches any event in the customer’s Onboarding stream after the tail at append time. This fits a stream-wide boundary; use a decision read instead when the next step depends on state loaded earlier.

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Events.Constraints;
using Cratis.Chronicle.EventSequences;
using Cratis.Chronicle.EventSources;
public record CustomerId(string Value) : EventSourceId(Value);
[EventType]
public record OnboardingStarted(string Email);
[EventType]
public record IdentityChecked(string Method);
// Appending this event closes the customer's Onboarding stream in the same step.
[EventType]
[ClosesStream]
public record OnboardingCompleted;
// One event source per customer, one stream for the onboarding process. Every writer of the
// stream is guarded against every other, whatever the event type.
[EventSource("Customer", Concurrency = ConcurrencyDimensions.EventSourceId)]
[EventStream(
"Onboarding",
Description = "The steps of one customer's onboarding",
Concurrency = ConcurrencyDimensions.EventSourceId | ConcurrencyDimensions.EventStreamType)]
public class CustomerEventSource : IEventSource;
public class Onboarding(IEventLog eventLog)
{
public Task<AppendResult> Start(CustomerId customer, string email) =>
eventLog.Append<CustomerEventSource>(customer, new OnboardingStarted(email), eventStream: "Onboarding");
public Task<AppendResult> CheckIdentity(CustomerId customer, string method) =>
eventLog.Append<CustomerEventSource>(customer, new IdentityChecked(method), eventStream: "Onboarding");
public async Task<bool> Complete(CustomerId customer)
{
var result = await eventLog.Append<CustomerEventSource>(customer, new OnboardingCompleted(), eventStream: "Onboarding");
return result.IsSuccess;
}
// After OnboardingCompleted, any later step is refused with a StreamClosed constraint violation.
public static bool WasRefusedBecauseClosed(AppendResult result) =>
result.ConstraintViolations.Any(violation => violation.ConstraintType == ConstraintType.StreamClosed);
}

View C# snippet source on GitHub

guard Customer-12: any type, streamType=Onboarding, after <tail at append>

The guard has no event-type filter, so any append in this customer’s Onboarding stream counts. Competing writes based on the same tail conflict, but a step written before your tail read does not. Different customers have different source IDs and do not match each other’s guards. The first append into a new stream is unchecked unless you enable CheckFirstAppendIntoAScope; see Concurrency.

In .NET, OnboardingCompleted carries [ClosesStream]. Once the closure is recorded, late or repeated steps are refused with a StreamClosed constraint violation. The event write and closure recording are not crash-atomic; Closing events explains index recovery after an interruption.

A reactor that drives the process is not a guard. It runs after the event is written and can see an event again after a recovery, so make each step safe to repeat. The reactor version is in A process stream.

Invoices get numbers with no gaps and no duplicates, across all invoices. No single invoice owns the sequence, so make the sequence an event source. Append every InvoiceCreated to one numbering source and guard it with a decision read of the last number.

The guard watches InvoiceCreated on invoice-numbering after the read’s captured tail. A [Unique] constraint can reject duplicates, but cannot tell the caller which number comes next or prevent skipped numbers.

using Cratis.Chronicle;
using Cratis.Chronicle.Events;
using Cratis.Chronicle.EventSequences;
using Cratis.Chronicle.Projections.ModelBound;
using Cratis.Chronicle.ReadModels;
[EventType]
public record InvoiceCreated(int Number, string Customer);
// The decision model: the last number issued. Every invoice is created on one numbering event source.
[FromEvent<InvoiceCreated>]
public record InvoiceNumbering(string Id, [SetFrom<InvoiceCreated>(nameof(InvoiceCreated.Number))] int Last);
public static class CreateInvoice
{
const string NumberingSource = "invoice-numbering";
public static async Task<int?> Handle(IEventStore eventStore, string customer)
{
var numbering = await eventStore.GetDecisionReads().GetDetached<InvoiceNumbering>(new ReadModelKey(NumberingSource));
var next = (numbering.Instance?.Last ?? 0) + 1;
// If another invoice was created after the read, the append is rejected and nothing is written.
var result = await eventStore.EventLog.AppendMany(
[new EventForEventSourceId(NumberingSource, new InvoiceCreated(next, customer))],
guardedBy: [numbering]);
return result.IsSuccess ? next : null;
}
}

View C# snippet source on GitHub

guard invoice-numbering: types=[InvoiceCreated], after <tail at read>

Two requests that read the same last number both try to append. The second is rejected, reads again and gets the next number. A [Unique] constraint on the number stops duplicates. It does not say which number is next, and it does not prevent a gap, so it is not enough for a gapless sequence.

The numbering source is a hot key: every read folds its matching history, and writers that choose from the same boundary compete for the next number. This serializes number allocation. If numbering restarts each year, use a numbering source per year to keep each history shorter.

The invoice read model is keyed by the invoice number carried in the event. Later events in the invoice’s life can therefore live on its own source rather than adding to the numbering history.

Two people open the same project and both rename it. The second save should not silently replace the first. The decision is based on what the user saw, not on what the server read, so build the scope from the revision the user saw.

Carry the captured revision back with the form and use it as the scope’s position on save. Choose the event types that invalidate the user’s view. A materialized read model can lag behind that revision, so it is not a safe source for this form.

using Cratis.Chronicle.Events;
using Cratis.Chronicle.EventSequences;
using Cratis.Chronicle.EventSequences.Concurrency;
[EventType]
public record ProjectRenamed(string Name);
public static class RenameProject
{
// Capture this BEFORE you load the form data, then return it with the form. Load the data from the
// event log or a passive read model (a fresh fold), never from a materialized read model.
public static async Task<EventSequenceNumber> GetRevision(IEventLog eventLog, EventSourceId projectId)
{
var tail = await eventLog.GetTailSequenceNumber(projectId);
// A project with no events has no tail (Unavailable). An explicit scope skips that value, so
// return BeforeFirst: "no matching event had been appended when the user loaded the form".
return tail.IsUnavailable ? EventSequenceNumber.BeforeFirst : tail;
}
public static async Task<bool> Rename(
IEventLog eventLog,
EventSourceId projectId,
string name,
EventSequenceNumber revisionTheUserSaw)
{
// Reject if anyone renamed the project after the revision the user saw.
var scope = new ConcurrencyScopeBuilder()
.WithEventSourceId(projectId)
.WithSequenceNumber(revisionTheUserSaw)
.WithEventType<ProjectRenamed>()
.Build();
var result = await eventLog.Append(projectId, new ProjectRenamed(name), concurrencyScope: scope);
return result.IsSuccess;
}
}

View C# snippet source on GitHub

Order matters. Capture the revision first, then load the data for the form, and return the revision with the form. Load the data from the event log, a passive read model or a decision read, so it includes every event up to the captured revision. Do not load it from a materialized read model: it updates asynchronously and may lag behind the captured tail. The revision would then claim the user saw events the form never showed, and the scope would accept a save made over a change the user did not see. Send the revision back with the change. The scope rejects the append when a ProjectRenamed event for that project was appended after that revision. Narrowing to ProjectRenamed means another person editing a different field does not cause a conflict. List every event type that should invalidate the user’s view, and no others.

If the project has no events yet, the tail is Unavailable, which an explicit scope skips. The example turns it into EventSequenceNumber.BeforeFirst, which means “no ProjectRenamed event yet”. ExpectingNoMatchingEvent() or a constraint also work.

In a web request, use the request’s unit of work: IDecisionReads.Get<T> enrolls each read, and Transactional.Append stages the events. The middleware that AddCratisChronicle registers starts a unit of work for every request. See Add Chronicle to an ASP.NET Core app.

The enrolled reads guard the request’s staged events. A plain eventLog.Append writes immediately, outside that unit of work, so it would bypass those guards.

using Cratis.Chronicle.AspNetCore.Transactions;
using Cratis.Chronicle.EventSequences;
using Cratis.Chronicle.ReadModels;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
public static class SubscribeEndpoint
{
public static void Map(IEndpointRouteBuilder routes) =>
routes.MapPost("/courses/{courseId:guid}/students/{studentId:guid}", Handle);
static async Task<IResult> Handle(
Guid courseId,
Guid studentId,
HttpContext http,
IDecisionReads reads,
IEventLog eventLog)
{
// Get enrolls each read in the request's unit of work.
var course = await reads.Get<CourseSeats>(courseId);
var student = await reads.Get<StudentCourses>(studentId);
if (course.Instance is not { } seats)
{
return Results.NotFound();
}
if (seats.Subscribed >= seats.Capacity || (student.Instance?.Subscribed ?? 0) >= 5)
{
return Results.UnprocessableEntity();
}
// Transactional.Append stages the event in the unit of work. A plain eventLog.Append
// would be written immediately and would not be guarded by the decision reads.
await eventLog.Transactional.Append(courseId, new CourseSeatTaken(studentId));
await eventLog.Transactional.Append(studentId, new StudentJoinedCourse(courseId));
// The middleware commits after the response is written, which is too late to report a
// conflict. Commit here, while the response can still change.
var unitOfWork = await http.Features.Get<IUnitOfWorkCompletionFeature>()!.CommitAsync();
var conflicts = unitOfWork.GetDecisionConflicts().ToArray();
if (conflicts.Length > 0)
{
// A conflict serializes as the read model, the key and the event that changed it.
return Results.Conflict(conflicts);
}
return unitOfWork.IsSuccess ? Results.NoContent() : Results.UnprocessableEntity();
}
}

View C# snippet source on GitHub

Commit while you can still change the response. Once the response has started, the middleware cannot turn a later commit failure into a conflict response. The .NET example calls IUnitOfWorkCompletionFeature.CommitAsync() and branches on the result; the middleware does not commit the completed unit again. A DecisionConflict can be returned as the response body.

Use Get to enroll a read and Transactional.Append to stage the events in that unit of work. Get requires an ambient unit; use GetDetached when you will attach the guard yourself.

The Elixir tab shows the equivalent HTTP decision flow, not ASP.NET Core middleware: Chronicle.decide commits before returning an outcome for the handler to map to a response.

For ownership rules and the full list of unit-of-work behavior see Decision reads and Transactions and unit of work.

Accepting a rare violation, and proving the rule holds.

If your business can accept a temporary overbooking, append the reservation and let a reactor detect the excess. This avoids a decision-read fold on each reservation, but there is no guard enforcing capacity before the write. Use a decision read when even a short, visible violation is unacceptable.

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Projections.ModelBound;
using Cratis.Chronicle.Reactors;
using Cratis.Chronicle.ReadModels;
[EventType]
public record ConcertAnnounced(string Name, int Capacity);
[EventType]
public record SeatReserved(string ReservedBy);
[EventType]
public record ConcertOverbooked(int Excess);
[Passive]
[FromEvent<ConcertAnnounced>]
public record ConcertSeats(
Guid Id,
int Capacity,
[Count<SeatReserved>]
int Reserved);
public class OverbookingRepair(IReadModels readModels) : IReactor
{
// A passive read model is folded when it is read, so it includes the reservation that triggered this call.
public async Task<ConcertOverbooked?> OnSeatReserved(SeatReserved @event, EventContext context)
{
var seats = await readModels.GetInstanceById<ConcertSeats>(context.EventSourceId);
return seats.Reserved > seats.Capacity
? new ConcertOverbooked(seats.Reserved - seats.Capacity)
: null;
}
}

View C# snippet source on GitHub

The reactor reads a passive read model, which is folded when it is read, so the count includes the reservation that triggered the call. It returns a new fact, ConcertOverbooked, and does not roll anything back. Something else, such as a person or another reactor, acts on that fact.

Repair has limits:

  • It appends after the violation. For some time the system holds an invalid state.
  • A side effect you cannot undo, such as a confirmation email, cannot be repaired by an event.
  • The repair is itself unguarded and can run more than once. Make the event safe to receive twice.

Use it only when a short, visible violation is acceptable. Otherwise use a decision read.

A test that never interleaves a competing writer cannot show the rule holds. Read, append a competing event, then do the guarded append.

The competing append must match the guard’s source and event filter. Otherwise the test demonstrates an unrelated write, not the race the rule must reject.

using Cratis.Chronicle;
using Cratis.Chronicle.EventSequences;
using Cratis.Chronicle.ReadModels;
public static class LoanRaceCheck
{
// Returns true when the guard rejected the second writer. Run it against a test event store
// that already holds a registered member.
public static async Task<bool> SecondWriterIsRejected(IEventStore eventStore, Guid memberId)
{
var member = await eventStore.GetDecisionReads().GetDetached<MemberLoans>(memberId);
// A competing writer appends after the read and before the guarded append.
await eventStore.EventLog.Append(memberId, new LoanTaken("978-0-13-468599-1"));
var result = await eventStore.EventLog.AppendMany(
[new EventForEventSourceId(memberId, new LoanTaken("978-0-596-52068-7"))],
guardedBy: [member]);
return result.GetDecisionConflicts([member]).Any();
}
}

View C# snippet source on GitHub

The method returns true when the guard rejects the second append. Run it against an event store that holds a registered member. A plain read cannot protect that append: without a guard, there is nothing for the kernel to invalidate.

Before adapting an example, check the model and scope requirements in Decision reads and choose your routing in Event sources and streams. For a different rule, return to Choosing how a rule holds.

Questions and answers covers common decisions. Dynamic Consistency Boundary in Chronicle and DCB examples in Chronicle explain how these patterns relate to DCB.