Skip to content

Cratis Chronicle event sources and dynamic consistency boundaries

A dynamic consistency boundary (DCB) protects the facts used for one decision without making every change to the entity a conflict. In Cratis Chronicle, combine an event source definition with a decision read: the definition supplies routing names, and the read supplies the condition checked when you append. The .NET example below uses this to enforce a monthly withdrawal count. Dynamic Consistency Boundary introduces the idea; Dynamic Consistency Boundary in Chronicle explains the mapping.

DCB describes reads by event type and tags across a global sequence, where an event can carry several tags. Chronicle uses four routing fields for this part of the condition: event source id, event source type, event stream type and event stream id. Each field has one value per event, and a concurrency scope can narrow by any of them. Custom tags are separate metadata and do not participate in concurrency checks.

ConcurrencyDimensions on the definition chooses which routing fields narrow the default guard. The client captures an expected event position and sends it with those field values; a later matching append causes a conflict. Appending through the definition uses the same resolved routing for the event and its default guard.

That default capture happens during append, so it does not protect state read earlier. To base a decision on a read, capture the boundary before reading and pass the resulting guard with the write. A decision read does this for you. If you build an explicit scope instead, you are responsible for making it cover the facts you used.

A definition-derived guard counts every event type in its selected range. With event source id, stream type and stream id as its dimensions, that range is one stream instance of one entity. Choose this boundary when every append to that stream can affect the rule, as with the steps of one transfer.

When only some event types matter, use a decision read whose model consumes those types. Its guard includes the read’s source key and model event types; a stream-scoped read also includes the selected stream routing. That lets unrelated events proceed without rejecting the decision. In Arc, a stream decision instead guards the whole stream.

The full mapping of DCB concepts to Chronicle, including what a definition adds, is in Dynamic Consistency Boundary in Chronicle.

Suppose an account may make at most five withdrawals a month. The decision needs only the count of MoneyWithdrawn events in that account’s monthly Transactions stream. A read that guarded every event of the account would also conflict with deposits and changes in other months, even though they do not affect this count.

using Cratis.Chronicle;
using Cratis.Chronicle.Events;
using Cratis.Chronicle.EventSequences;
using Cratis.Chronicle.EventSources;
using Cratis.Chronicle.Projections.ModelBound;
using Cratis.Chronicle.ReadModels;
[EventType]
public record MoneyWithdrawn(decimal Amount);
[EventSource("Account", Concurrency = ConcurrencyDimensions.EventSourceId)]
[EventStream(
"Transactions",
Concurrency = ConcurrencyDimensions.EventSourceId | ConcurrencyDimensions.EventStreamType | ConcurrencyDimensions.EventStreamId)]
public class AccountEventSource : IEventSource;
// The decision model: how many withdrawals this account has made in one month's stream.
[Passive]
[FromEvent<MoneyWithdrawn>]
public record MonthlyWithdrawals(string Id, [Count<MoneyWithdrawn>] int Count);
public enum WithdrawOutcome
{
Withdrawn,
LimitReached,
ChangedConcurrently,
Failed
}
public static class Withdraw
{
const int MaxWithdrawalsPerMonth = 5;
public static async Task<WithdrawOutcome> Handle(IEventStore eventStore, EventSourceId accountId, string month, decimal amount)
{
var definition = eventStore.EventSources.GetFor(typeof(AccountEventSource));
var transactions = definition.FindStream("Transactions")!;
// The read notes the log position before it folds, and folds only this month's stream.
var read = await eventStore.GetDecisionReads().GetDetached<MonthlyWithdrawals>(
accountId,
transactions.EventStreamType,
month,
definition.EventSourceType);
if ((read.Instance?.Count ?? 0) >= MaxWithdrawalsPerMonth)
{
return WithdrawOutcome.LimitReached;
}
// The event goes through the definition. The guard is the append condition.
var result = await eventStore.EventLog.AppendMany(
[
new EventForEventSourceId(accountId, new MoneyWithdrawn(amount))
{
EventSource = typeof(AccountEventSource),
EventStream = "Transactions",
EventStreamId = month
}
],
guardedBy: [read]);
if (result.GetDecisionConflicts([read]).Any())
{
return WithdrawOutcome.ChangedConcurrently;
}
return result.IsSuccess ? WithdrawOutcome.Withdrawn : WithdrawOutcome.Failed;
}
}

View C# snippet source on GitHub

GetDetached<MonthlyWithdrawals> reads the account and month using the definition’s source type and declared stream type. It captures the log boundary before folding the events into the count. Taking that position after the read could miss an event that arrived between the read and the capture.

If the count is below five, AppendMany writes MoneyWithdrawn through the same definition and stream, with guardedBy: [read] as its append condition. In this detached flow, outside a read-protection frame, the read’s guard replaces the definition’s default scope for that source id. Under a frame, declared dimensions can add independent conditions; see How guards are derived.

The append condition checks for new MoneyWithdrawn events in this account and month. A deposit in the same month, or an append to another account or month, does not match it. Supported decision reads also carry a mutation epoch to detect revisions and redactions; see history mutations.

GetDecisionConflicts([read]) identifies a conflict with the read. Nothing is written on rejection, and the handler returns ChangedConcurrently. Read again and decide again before retrying; Chronicle does not repeat the decision for you.

Load only the facts needed for the rule. A monthly count and an account’s status answer different questions, so give them separate decision models instead of folding the account’s entire history into one model. A command that needs both can enroll both reads. Streams help separate histories, but the model’s event types still determine which events affect each read.

A definition does not let one event belong to several event sources. For a fact concerning two entities, such as a student joining a course, you can write one event per source in an atomic append with the required read guards. That is not always necessary: a constraint or a guard on a source that receives no event can avoid duplicating the fact. The DCB examples show both approaches.

If a process has finished, close its stream to refuse further appends while it remains closed. Closure does not prevent revisions or redactions of existing history.

Use Decision reads to build your own guarded model, then Read protection to refuse unguarded reads and immediate appends in an invocation. If you are deciding between a read guard and a kernel constraint, follow Choosing how a rule holds. The DCB examples in Chronicle work through common rules; Concurrency per event source and stream covers the default dimension-based guards.