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.
Simple
Section titled “Simple”A value, a create-once rule, or a limit on one key.
Unique username
Section titled “Unique username”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."; }}defmodule MyApp.Events.UniqueUsernameUserRegistered do use Chronicle.Events.EventType, id: "unique-username-user-registered"
defstruct [:username, :email]
unique(:username)end
defmodule MyApp.UniqueUsernameRegistration do alias Chronicle.EventSequences.EventLog alias MyApp.Events.UniqueUsernameUserRegistered
def register(user_id, username, email) do event = %UniqueUsernameUserRegistered{username: username, email: email}
case EventLog.append_with_result(user_id, event) do {:ok, _result} -> nil
# The kernel rejected the append, so this holds for every writer, not only this one. {:error, %{constraint_violations: [first | _]}} -> first.message
{:error, _result} -> "The user could not be registered." end endendThe 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.
Create once
Section titled “Create once”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);defmodule MyApp.Events.CreateOnceAccountOpened do use Chronicle.Events.EventType, id: "create-once-account-opened"
defstruct [:owner]
# At most one AccountOpened is ever appended for the same event source. unique_event_type()endThe 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 limit on one key
Section titled “A limit on one key”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; }}defmodule MyApp.Events.MemberLoansMemberRegistered do use Chronicle.Events.EventType, id: "member-loans-member-registered"
defstruct [:name]end
defmodule MyApp.Events.MemberLoansLoanTaken do use Chronicle.Events.EventType, id: "member-loans-loan-taken"
defstruct [:isbn]end
defmodule MyApp.Events.MemberLoansLoanReturned do use Chronicle.Events.EventType, id: "member-loans-loan-returned"
defstruct [:isbn]end
defmodule MyApp.ReadModels.MemberLoans do use Chronicle.ReadModels.ReadModel
defstruct id: nil, active: 0
from MyApp.Events.MemberLoansMemberRegistered, set: [id: :event_source_id] from MyApp.Events.MemberLoansLoanTaken, add: [active: 1] from MyApp.Events.MemberLoansLoanReturned, subtract: [active: 1]end
defmodule MyApp.MemberLoansTakeLoan do alias Chronicle.EventSequences.EventLog alias Chronicle.ReadModels.{DecisionConflict, DecisionReads} alias MyApp.Events.MemberLoansLoanTaken alias MyApp.ReadModels.MemberLoans
@max_active_loans 3
def handle(member_id, isbn) do result = Chronicle.decide(fn _unit_of_work -> {:ok, member} = DecisionReads.get(MemberLoans, member_id)
case member.instance do nil -> :unknown_member
%MemberLoans{active: active} when active >= @max_active_loans -> :limit_reached
%MemberLoans{} -> :ok = EventLog.append(member_id, %MemberLoansLoanTaken{isbn: isbn}) :taken end end)
case result do {:ok, outcome} -> outcome # Another loan or return was appended for this member after the read. Nothing was appended. {:error, %DecisionConflict{}} -> :changed_concurrently {:error, _reason} -> :failed end endendMemberLoans 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.
Two entities
Section titled “Two entities”A rule that spans two keys.
A rule across two keys
Section titled “A rule across 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; }}defmodule MyApp.Events.CourseSubscriptionCourseDefined do use Chronicle.Events.EventType, id: "course-subscription-course-defined"
defstruct [:name, :capacity]end
defmodule MyApp.Events.CourseSubscriptionCourseCapacityChanged do use Chronicle.Events.EventType, id: "course-subscription-course-capacity-changed"
defstruct [:capacity]end
# Events of the course's own story.defmodule MyApp.Events.CourseSubscriptionSeatTaken do use Chronicle.Events.EventType, id: "course-subscription-seat-taken"
defstruct [:student_id]end
defmodule MyApp.Events.CourseSubscriptionSeatReleased do use Chronicle.Events.EventType, id: "course-subscription-seat-released"
defstruct [:student_id]end
# Events of the student's own story.defmodule MyApp.Events.CourseSubscriptionStudentJoinedCourse do use Chronicle.Events.EventType, id: "course-subscription-student-joined-course"
defstruct [:course_id]end
defmodule MyApp.Events.CourseSubscriptionStudentLeftCourse do use Chronicle.Events.EventType, id: "course-subscription-student-left-course"
defstruct [:course_id]end
defmodule MyApp.ReadModels.CourseSeats do use Chronicle.ReadModels.ReadModel
defstruct id: nil, capacity: 0, subscribed: 0
from MyApp.Events.CourseSubscriptionCourseDefined, set: [id: :event_source_id, capacity: :capacity] from MyApp.Events.CourseSubscriptionCourseCapacityChanged, set: [capacity: :capacity] from MyApp.Events.CourseSubscriptionSeatTaken, add: [subscribed: 1] from MyApp.Events.CourseSubscriptionSeatReleased, subtract: [subscribed: 1]end
defmodule MyApp.ReadModels.StudentCourses do use Chronicle.ReadModels.ReadModel
defstruct id: nil, subscribed: 0
from MyApp.Events.CourseSubscriptionStudentJoinedCourse, set: [id: :event_source_id], add: [subscribed: 1]
from MyApp.Events.CourseSubscriptionStudentLeftCourse, subtract: [subscribed: 1]end
defmodule MyApp.CourseSubscriptionSubscribeStudent do alias Chronicle.EventSequences.EventLog alias Chronicle.ReadModels.{DecisionConflict, DecisionReads} alias MyApp.Events.{CourseSubscriptionSeatTaken, CourseSubscriptionStudentJoinedCourse} alias MyApp.ReadModels.{CourseSeats, StudentCourses}
@max_courses_per_student 5
def handle(course_id, student_id) do result = Chronicle.decide(fn _unit_of_work -> # One decision read per event source: the commit guards both. {:ok, course} = DecisionReads.get(CourseSeats, course_id) {:ok, student} = DecisionReads.get(StudentCourses, student_id) student_courses = if student.instance, do: student.instance.subscribed, else: 0
cond do course.instance == nil -> :unknown_course
course.instance.subscribed >= course.instance.capacity -> :course_is_full
student_courses >= @max_courses_per_student -> :student_has_too_many_courses
true -> # One fact, two event sources, two event types: each read model counts only the # types of its own source. :ok = EventLog.append(course_id, %CourseSubscriptionSeatTaken{student_id: student_id})
:ok = EventLog.append(student_id, %CourseSubscriptionStudentJoinedCourse{course_id: course_id})
:subscribed end end)
case result do {:ok, outcome} -> outcome # Either side changed after it was read. Nothing was appended for either source. {:error, %DecisionConflict{}} -> :changed_concurrently {:error, _reason} -> :failed end endendChronicle 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.
Inside one stream
Section titled “Inside one stream”A rule about one part of one entity.
A limit inside one stream
Section titled “A limit inside one stream”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; }}defmodule MyApp.Events.MonthlyLimitMoneyWithdrawn do use Chronicle.Events.EventType, id: "monthly-limit-money-withdrawn"
defstruct [:amount]end
# Names the source type and the stream, so the read and the append use the same values.defmodule MyApp.MonthlyLimitBankAccountEventSource do use Chronicle.EventSources.EventSource, name: "BankAccount"
stream "Transactions", description: "Deposits and withdrawals, one stream per month"end
# The decision model: what this account has withdrawn in the stream the read is scoped to.defmodule MyApp.ReadModels.MonthlyLimitWithdrawnThisMonth do use Chronicle.ReadModels.ReadModel, passive: true
defstruct id: nil, total: 0
from MyApp.Events.MonthlyLimitMoneyWithdrawn, set: [id: :event_source_id], add: [total: :amount]end
defmodule MyApp.MonthlyLimitWithdraw do alias Chronicle.EventSequences.EventLog alias Chronicle.ReadModels.{DecisionConflict, DecisionReads} alias MyApp.Events.MonthlyLimitMoneyWithdrawn alias MyApp.MonthlyLimitBankAccountEventSource alias MyApp.ReadModels.MonthlyLimitWithdrawnThisMonth
@monthly_limit 5000
# month is the stream id, for example "2026-10". def handle(account_id, month, amount) do result = Chronicle.decide(fn _unit_of_work -> # Reads only BankAccount / Transactions / month, and guards only that stream. {:ok, read} = DecisionReads.get( MonthlyLimitWithdrawnThisMonth, account_id, "Transactions", month, event_source_type: "BankAccount" )
withdrawn = if read.instance, do: read.instance.total, else: 0
if withdrawn + amount > @monthly_limit do :monthly_limit_reached else :ok = EventLog.append(account_id, %MonthlyLimitMoneyWithdrawn{amount: amount}, event_source: MonthlyLimitBankAccountEventSource, event_stream: "Transactions", event_stream_id: month )
:withdrawn end end)
case result do {:ok, outcome} -> outcome # A withdrawal in this month's stream was appended after the read. Nothing was appended. {:error, %DecisionConflict{}} -> :changed_concurrently {:error, _reason} -> :failed end endendguard 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; } }}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.
Process, numbering and editing conflicts
Section titled “Process, numbering and editing conflicts”Rules about a sequence, a lifecycle or what a user saw.
A process with steps and an end
Section titled “A process with steps and an end”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);}defmodule MyApp.Events.OnboardingStarted do use Chronicle.Events.EventType, id: "onboarding-started"
defstruct [:email]end
defmodule MyApp.Events.OnboardingIdentityChecked do use Chronicle.Events.EventType, id: "onboarding-identity-checked"
defstruct [:method]end
# Appending this event closes the customer's Onboarding stream in the same step.defmodule MyApp.Events.OnboardingCompleted do use Chronicle.Events.EventType, id: "onboarding-completed"
defstruct []
closes_stream()end
# 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.defmodule MyApp.OnboardingCustomerEventSource do use Chronicle.EventSources.EventSource, name: "Customer", concurrency: [:event_source_id]
stream "Onboarding", description: "The steps of one customer's onboarding", concurrency: [:event_source_id, :event_stream_type]end
defmodule MyApp.OnboardingProcess do alias Chronicle.EventSequences.EventLog alias Chronicle.Events.ConstraintViolation alias MyApp.Events.{OnboardingCompleted, OnboardingIdentityChecked, OnboardingStarted} alias MyApp.OnboardingCustomerEventSource
def start(customer_id, email), do: step(customer_id, %OnboardingStarted{email: email})
def check_identity(customer_id, method), do: step(customer_id, %OnboardingIdentityChecked{method: method})
def complete(customer_id) do match?({:ok, _}, step(customer_id, %OnboardingCompleted{})) end
# After OnboardingCompleted, any later step is refused with a stream-closed constraint violation. def refused_because_closed?({:error, %{constraint_violations: violations}}), do: Enum.any?(violations, &Map.has_key?(ConstraintViolation.details(&1), :closed_by))
def refused_because_closed?(_result), do: false
defp step(customer_id, event) do EventLog.append_with_result(customer_id, event, event_source: OnboardingCustomerEventSource, event_stream: "Onboarding" ) endendguard 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.
Gapless invoice numbers
Section titled “Gapless invoice numbers”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; }}defmodule MyApp.Events.InvoiceNumberInvoiceCreated do use Chronicle.Events.EventType, id: "invoice-number-invoice-created"
defstruct [:number, :customer]end
# The decision model: the last number issued. Every invoice is created on one numbering event source.defmodule MyApp.ReadModels.InvoiceNumbering do use Chronicle.ReadModels.ReadModel
defstruct id: nil, last: 0
from MyApp.Events.InvoiceNumberInvoiceCreated, set: [id: :event_source_id, last: :number]end
defmodule MyApp.InvoiceNumberCreateInvoice do alias Chronicle.EventSequences.EventLog alias Chronicle.ReadModels.DecisionReads alias MyApp.Events.InvoiceNumberInvoiceCreated alias MyApp.ReadModels.InvoiceNumbering
@numbering_source "invoice-numbering"
def handle(customer) do result = Chronicle.decide(fn _unit_of_work -> {:ok, numbering} = DecisionReads.get(InvoiceNumbering, @numbering_source) next = if numbering.instance, do: numbering.instance.last + 1, else: 1
# If another invoice was created after the read, the commit is rejected and nothing is written. :ok = EventLog.append(@numbering_source, %InvoiceNumberInvoiceCreated{ number: next, customer: customer })
next end)
case result do {:ok, number} -> number {:error, _reason} -> nil end endendguard 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.
An editing conflict
Section titled “An editing conflict”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; }}defmodule MyApp.Events.EditingConflictProjectRenamed do use Chronicle.Events.EventType, id: "editing-conflict-project-renamed"
defstruct [:name]end
defmodule MyApp.EditingConflictRenameProject do alias Chronicle.EventSequences.EventLog alias Chronicle.Events.ConcurrencyScope alias MyApp.Events.EditingConflictProjectRenamed
# 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. def revision(project_id) do case EventLog.has_events_for?(project_id) do # A project with no events has no tail: "no matching event had been appended when the user # loaded the form". {:ok, false} -> {:ok, :none} {:ok, true} -> EventLog.get_tail_sequence_number(project_id) {:error, reason} -> {:error, reason} end end
def rename(project_id, name, revision_the_user_saw) do # Reject if anyone renamed the project after the revision the user saw. options = [event_types: [EditingConflictProjectRenamed]]
scope = case revision_the_user_saw do :none -> ConcurrencyScope.expecting_no_matching_event([event_source_id: true] ++ options) sequence_number -> ConcurrencyScope.for_event_source(sequence_number, options) end
EventLog.append(project_id, %EditingConflictProjectRenamed{name: name}, concurrency_scope: scope) == :ok endendOrder 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 an ASP.NET Core endpoint
Section titled “In an ASP.NET Core endpoint”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(); }}defmodule MyApp.SubscribeEndpoint do alias Chronicle.EventSequences.EventLog alias Chronicle.ReadModels.{DecisionConflict, DecisionReads} alias MyApp.Events.{CourseSubscriptionSeatTaken, CourseSubscriptionStudentJoinedCourse} alias MyApp.ReadModels.{CourseSeats, StudentCourses}
# Returns the HTTP outcome for POST /courses/:course_id/students/:student_id. def handle(course_id, student_id) do # decide/2 commits as soon as the function returns, while the response can still change. result = Chronicle.decide(fn _unit_of_work -> # get/2 enrolls each read in the unit of work. {:ok, course} = DecisionReads.get(CourseSeats, course_id) {:ok, student} = DecisionReads.get(StudentCourses, student_id) student_courses = if student.instance, do: student.instance.subscribed, else: 0
cond do course.instance == nil -> :not_found
course.instance.subscribed >= course.instance.capacity or student_courses >= 5 -> :unprocessable_entity
true -> # Inside decide/2 an append is staged in the unit of work, guarded by the decision reads. :ok = EventLog.append(course_id, %CourseSubscriptionSeatTaken{student_id: student_id})
:ok = EventLog.append(student_id, %CourseSubscriptionStudentJoinedCourse{course_id: course_id})
:no_content end end)
case result do {:ok, response} -> response {:error, %DecisionConflict{}} -> :conflict {:error, _reason} -> :unprocessable_entity end endendCommit 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.
Repair and test
Section titled “Repair and test”Accepting a rare violation, and proving the rule holds.
A rare violation you can repair
Section titled “A rare violation you can repair”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; }}defmodule MyApp.Events.RepairReactorConcertAnnounced do use Chronicle.Events.EventType, id: "repair-reactor-concert-announced"
defstruct [:name, :capacity]end
defmodule MyApp.Events.RepairReactorSeatReserved do use Chronicle.Events.EventType, id: "repair-reactor-seat-reserved"
defstruct [:reserved_by]end
defmodule MyApp.Events.RepairReactorConcertOverbooked do use Chronicle.Events.EventType, id: "repair-reactor-concert-overbooked"
defstruct [:excess]end
defmodule MyApp.ReadModels.RepairReactorConcertSeats do use Chronicle.ReadModels.ReadModel, passive: true
defstruct id: nil, capacity: 0, reserved: 0
from MyApp.Events.RepairReactorConcertAnnounced, set: [id: :event_source_id, capacity: :capacity] from MyApp.Events.RepairReactorSeatReserved, count: :reservedend
defmodule MyApp.Reactors.RepairReactorOverbookingRepair do use Chronicle.Reactors.Reactor
alias MyApp.Events.{RepairReactorConcertOverbooked, RepairReactorSeatReserved} alias MyApp.ReadModels.RepairReactorConcertSeats
@handles RepairReactorSeatReserved
# A passive read model is folded when it is read, so it includes the reservation that triggered this call. @impl true def handle(%RepairReactorSeatReserved{}, context) do {:ok, seats} = Chronicle.read_model(RepairReactorConcertSeats, context.event_source_id)
case seats do %RepairReactorConcertSeats{reserved: reserved, capacity: capacity} when reserved > capacity -> {:ok, %RepairReactorConcertOverbooked{excess: reserved - capacity}}
_ -> :ok end endendThe 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.
Test the race
Section titled “Test the race”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(); }}defmodule MyApp.LoanRaceCheck do alias Chronicle.EventSequences.EventLog alias Chronicle.ReadModels.{DecisionConflict, DecisionReads} alias MyApp.Events.MemberLoansLoanTaken alias MyApp.ReadModels.MemberLoans
# Returns true when the guard rejected the second writer. Run it against a test event store # that already holds a registered member. def second_writer_rejected?(member_id) do result = Chronicle.decide(fn _unit_of_work -> {:ok, _member} = DecisionReads.get(MemberLoans, member_id)
# A competing writer appends after the read and before the commit. It runs in its own # process, so its append goes straight to the event log instead of this unit of work. :ok = Task.async(fn -> EventLog.append(member_id, %MemberLoansLoanTaken{isbn: "978-0-13-468599-1"}) end) |> Task.await()
EventLog.append(member_id, %MemberLoansLoanTaken{isbn: "978-0-596-52068-7"}) end)
match?({:error, %DecisionConflict{}}, result) endendThe 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.
Next steps
Section titled “Next steps”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.