Skip to content

Set concurrency boundaries for Cratis Chronicle event sources

Concurrency dimensions on a Cratis Chronicle event source definition decide which competing appends can reject a write. Choose an account-wide boundary when every change matters, or a stream boundary when different parts of the history can progress independently. These .NET examples build on the general concurrency scope model.

When you append without passing a ConcurrencyScope, the client captures the tail, the latest matching event position, and sends it as the expected position. The kernel rejects the append if a matching event arrived after that position. The definition’s dimensions choose which routing values must match:

The append goes through The scope narrows to
No definition The append’s event source ID, event source type, event stream type and event stream ID
A definition whose dimensions are None The same four values, as without a definition
A definition with dimensions Only the dimensions it declares

The four values are the routing values of an event. What each one means is in Event source, and how they build a scope is in Concurrency. The client reads the tail with exactly the narrowing it sends, so the position and the check ask the same question. A dimension that is not declared is left out, not set to a default.

Leaving EventSourceId out of a nonempty declaration makes the condition apply across source ids. For example, a scope narrowed only to stream type and month sees matching events for every account. CHR0062 reports this at Info severity and offers a fix to include EventSourceId.

Keep a cross-source condition only when the rule needs it. A default scope captured during append does not protect state you read before that capture. Use decision reads for decisions based on earlier state, and declared dimensions for stream-wide conditions such as shared numbering. How guards are derived explains how those conditions combine.

Chronicle picks the dimensions with ConcurrencyFor:

  1. If the stream declares any dimensions, those are used. The event source’s dimensions are ignored.
  2. Otherwise the event source’s dimensions are used.
  3. An append without a stream uses the event source’s.

A stream cannot opt out. None on a stream means “not declared”, so it inherits. To make a stream narrower or wider than its event source, declare the dimensions on the stream.

using Cratis.Chronicle.Events;
using Cratis.Chronicle.EventSequences;
using Cratis.Chronicle.EventSources;
[EventType]
public record MoneyDeposited(decimal Amount);
[EventType]
public record MoneyWithdrawn(decimal Amount);
// Every event of an account conflicts with every other event of the same account, except in the
// Transactions stream, where only events of the same month conflict.
[EventSource("Account", Concurrency = ConcurrencyDimensions.EventSourceId)]
[EventStream("Onboarding")]
[EventStream(
"Transactions",
Concurrency = ConcurrencyDimensions.EventSourceId | ConcurrencyDimensions.EventStreamType | ConcurrencyDimensions.EventStreamId)]
public class AccountEventSource : IEventSource;
public class MonthlyDeposits(IEventLog eventLog)
{
// No scope is passed, so Chronicle builds one from the dimensions: it reads the tail of this
// account's Transactions stream for this month and expects it to be unchanged at append time.
public async Task<bool> Deposit(EventSourceId accountId, string month, decimal amount)
{
var result = await eventLog.Append<AccountEventSource>(
accountId,
new MoneyDeposited(amount),
eventStream: "Transactions",
eventStreamId: month);
return result.IsSuccess;
}
}

View C# snippet source on GitHub

With that definition, the scopes are:

Append Dimensions used Scope narrows to
Onboarding stream the event source’s: EventSourceId Every event of this account, in any stream
Transactions stream, month 2026-04 the stream’s: EventSourceId, EventStreamType, EventStreamId Events of this account in Transactions with stream id 2026-04
No stream the event source’s: EventSourceId Every event of this account

These scopes do not filter by event type, so any event in the selected range counts. That suits a rule for which every change to the source or stream matters. When only particular event types affect the decision, use a decision read or an explicit scope with WithEventType.

The check can be asymmetric. A Transactions deposit does not check Onboarding events, but an Onboarding append checks every event of the account, including deposits.

Assume matching history already exists, and both writers capture their expected positions before either appends. The second append is rejected if the first event falls inside the second writer’s scope:

First writer appends to Second writer appends to Conflict?
Account A, Transactions, 2026-04 Account A, Transactions, 2026-04 Yes
Account A, Transactions, 2026-04 Account A, Transactions, 2026-05 No
Account A, Transactions, 2026-04 Account B, Transactions, 2026-04 No
Account A, Transactions, 2026-04 Account A, Onboarding Yes. The onboarding scope covers the whole account
Account A, Onboarding Account A, Transactions, 2026-04 No. The transactions scope does not cover onboarding

A conflict is a normal result, not an exception. The append returns with HasConcurrencyViolations set and nothing is written. Read the new state, decide again and append again.

using Cratis.Chronicle.EventSequences;
public class DepositWithRetry(IEventLog eventLog)
{
public async Task<bool> Deposit(EventSourceId accountId, string month, decimal amount)
{
var result = await eventLog.Append<AccountEventSource>(
accountId,
new MoneyDeposited(amount),
eventStream: "Transactions",
eventStreamId: month);
if (result.HasConcurrencyViolations)
{
// Another writer appended to this month's stream between the tail read and the write.
// Nothing was appended. Read the new state and decide again.
return false;
}
return result.IsSuccess;
}
}

View C# snippet source on GitHub

A narrowed scope needs an event to compare with. When no event matches the narrowing yet, such as the first deposit of a new month, the client has no position to send and the kernel skips the check. By default two writers can both make the first append into a new stream and both succeed.

Turn on ConcurrencyOptions.CheckFirstAppendIntoAScope, or build the scope with ExpectingNoMatchingEvent() for one append, to check it. See The first append into a scope is not checked by default. The result’s ConcurrencyCheckPerformed tells you whether a check ran.

An append that passes its own ConcurrencyScope skips the dimension logic. This is how you guard a decision you made from earlier reads: capture the tail first, read the facts, decide, then append with that position.

using Cratis.Chronicle.EventSequences;
using Cratis.Chronicle.EventSequences.Concurrency;
public class DecideThenDeposit(IEventLog eventLog)
{
public async Task<bool> Withdraw(EventSourceId accountId, string month, Func<decimal> decide)
{
// Capture the position of this month's stream before you read the facts you decide on.
var tail = await eventLog.GetTailSequenceNumber(
eventSourceId: accountId,
eventSourceType: "Account",
eventStreamType: "Transactions",
eventStreamId: month);
var amount = decide();
// An empty stream has no tail (Unavailable). Explicit scopes skip that value, so expect "no event yet".
if (tail.IsUnavailable)
{
tail = EventSequenceNumber.BeforeFirst;
}
// ForEventSource names the source type, the stream type and the stream id from the definition.
// The builder does not set the event source id or the position: you do.
var scope = new ConcurrencyScopeBuilder()
.WithEventSourceId(accountId)
.ForEventSource<AccountEventSource>("Transactions", month)
.WithSequenceNumber(tail)
.Build();
var result = await eventLog.Append<AccountEventSource>(
accountId,
new MoneyWithdrawn(amount),
eventStream: "Transactions",
eventStreamId: month,
concurrencyScope: scope);
return result.IsSuccess;
}
}

View C# snippet source on GitHub

ForEventSource<TSource>(stream, streamId) resolves the source type and any supplied stream name from the definition, then uses the stream id you provide. It does not read the dimension flags. Add WithEventSourceId and WithSequenceNumber yourself to select the instance and expected position. An undeclared stream throws EventStreamDoesNotBelongToEventSource.

The scope retains a link to its definition, even through with copies. That lets the client catch a scope for T.Onboarding passed to an append through T.Transactions: it throws ConcurrencyScopeStreamDoesNotMatchAppend before sending the append. This check applies to AppendThroughEventSource, AppendManyThroughEventSource and AppendPreparedThroughEventSource, including their typed extension methods. CHR0063 warns when the mismatch is visible in source.

To intentionally guard one stream while writing another, use labelled AppendMany conditions. Ordinary AppendPrepared also stays independent because its prepared content has no definition route. The mismatch check does not refuse a scope without a definition link, one for another definition, or one without stream narrowing. ConcurrencyOptions.AllowRouteScopeStreamMismatch = true restores legacy acceptance for single-route APIs.

For an empty stream, GetTailSequenceNumber returns Unavailable. A narrowed caller-supplied scope treats that as an expectation that no matching event exists. An empty builder or wildcard-only scope does not become a whole-log expectation. Set ConcurrencyOptions.SkipIncompleteExplicitScopes = true only if you need the legacy behavior that skips incomplete scopes. The example explicitly converts to EventSequenceNumber.BeforeFirst to state the empty-stream expectation without depending on that switch.

A decision read does the capture-then-read sequence for you. See Dynamic Consistency Boundary.

A batch that needs two guards for one event source id

Section titled “A batch that needs two guards for one event source id”

An AppendMany can require several guards for the same event source id. Every guard must hold against the state before the batch; if one fails, none of the events are appended.

When you pass no explicit scope for an id, the .NET client resolves every distinct route, including routes without definitions. Identical matching conditions, called predicates, share the earliest expected position. Different stream ids, stream types, source types or event-type filters retain separate guards; Chronicle does not widen them into a whole-source check. An unchecked entry never hides a later guarded entry.

For explicit guards, pass an ordered IEnumerable<KeyValuePair<EventSourceId, ConcurrencyScope>> to AppendMany(events, correlationId, tags, concurrencyScopes). Labels may repeat for different predicates. This also supports writing just one event while guarding several streams. AppendManyWithNamedTags accepts the same list after its correlation id and tags parameters.

EventsWithConcurrencyScopes.Entries preserves every guard for reactor return values. Its legacy ConcurrencyScopes dictionary accessor works only with one scope per label and throws rather than discarding guards when a label repeats. The unit of work retains every enrolled predicate too. Conflicting expected positions for the same explicit predicate are refused; do not mix ConcurrencyScope.None with a real guard on the same label.

The connected kernel must advertise concurrency-scope-conjunctions. Without it, the .NET client throws IncompatibleConcurrencyScopesForEventSource before sending repeated labels. Upgrade the kernel, or deliberately choose one explicit scope that covers the entire decision. Splitting appends does not preserve a decision that needs both guards atomically.

This definition-backed batch keeps separate month guards on a capable kernel; the catch handles an older kernel that cannot enforce them:

using Cratis.Chronicle.EventSequences;
using Cratis.Chronicle.EventSequences.Concurrency;
public class CatchUpPosting(IEventLog eventLog)
{
public async Task<string> PostTwoMonths(EventSourceId accountId, decimal january, decimal february)
{
EventForEventSourceId[] events =
[
new(accountId, new MoneyDeposited(january))
{
EventSource = typeof(AccountEventSource),
EventStream = "Transactions",
EventStreamId = "2026-01"
},
new(accountId, new MoneyDeposited(february))
{
EventSource = typeof(AccountEventSource),
EventStream = "Transactions",
EventStreamId = "2026-02"
}
];
try
{
var result = await eventLog.AppendMany(events);
return result.IsSuccess ? "Posted" : "Rejected";
}
catch (IncompatibleConcurrencyScopesForEventSource exception)
{
// Nothing was appended. The two events need guards on different streams of one event source id.
return exception.Message;
}
}
}

View C# snippet source on GitHub

If broader conflicts are acceptable, an older kernel can use one explicit scope covering both months:

using Cratis.Chronicle.EventSequences;
using Cratis.Chronicle.EventSequences.Concurrency;
public class CatchUpPostingWithOneScope(IEventLog eventLog)
{
public async Task<bool> PostTwoMonths(EventSourceId accountId, decimal january, decimal february)
{
EventForEventSourceId[] events =
[
new(accountId, new MoneyDeposited(january))
{
EventSource = typeof(AccountEventSource),
EventStream = "Transactions",
EventStreamId = "2026-01"
},
new(accountId, new MoneyDeposited(february))
{
EventSource = typeof(AccountEventSource),
EventStream = "Transactions",
EventStreamId = "2026-02"
}
];
// One explicit scope for the account that suits both events: every month of the Transactions stream.
var tail = await eventLog.GetTailSequenceNumber(eventSourceId: accountId, eventStreamType: "Transactions");
if (tail.IsUnavailable)
{
// Nothing in the stream yet: expect that no event appears before the append.
tail = EventSequenceNumber.BeforeFirst;
}
var scope = new ConcurrencyScopeBuilder()
.WithEventSourceId(accountId)
.WithEventStreamType("Transactions")
.WithSequenceNumber(tail)
.Build();
var result = await eventLog.AppendMany(
events,
concurrencyScopes: new Dictionary<EventSourceId, ConcurrencyScope> { [accountId] = scope });
return result.IsSuccess;
}
}

View C# snippet source on GitHub

Revisions and redactions do not advance the append position. Supported .NET decision reads also capture a mutation epoch, a version that changes when stored history is revised or redacted. The kernel checks it with the append position, so a changed epoch rejects the guarded append even when no new event arrived.

A scope containing only an append position does not gain that protection. For mutation paths or clients that do not carry the epoch, pause affected producers and drain in-flight decisions before changing history, then resume with fresh reads. See history mutations and append conditions.

Apply these dimensions in Scenarios, or trace scope creation in How it works. To protect a decision based on a read, continue with Dynamic Consistency Boundary and decision reads. Dynamic Consistency Boundary in Chronicle explains the model; read protection can refuse unguarded reads and immediate appends in an invocation.