Skip to content

Choose Chronicle event source concurrency scopes

An event source definition in Cratis Chronicle lets you choose which concurrent writes should conflict. These .NET examples show how monthly account streams, per-author notes and transfers turn that choice into an append guard. A guard is the condition the kernel checks before accepting the write.

Use a definition-derived guard when the rule covers a whole event source or stream, regardless of event type. For a condition based on particular events or state, use a decision read. The examples assume the default settings, where the first append into a scope is not checked. Concurrency explains the dimension rules behind these choices.

Scenario Shows
A bank account with monthly streams Stream dimensions narrow the guard, source dimensions widen it
A monthly limit on one stream A decision read inside a definition’s stream
A stream per owner Writers on different streams of one event source do not conflict
A process stream A reactor that follows one stream, and a stream that ends
A transfer between two accounts One atomic append across two event sources

An account has one Onboarding stream and a Transactions stream with one stream id per month. In this example, deposits in different months should not conflict. Changes to onboarding data need a wider guard that notices any concurrent write to the account.

Declare EventSourceId on the definition for that account-wide guard, then give Transactions its own dimensions to narrow deposits to one month. An explicit scope on every call would repeat this choice at each call site. If the rule depends on a balance or a limit, use a decision read instead; see Dynamic Consistency Boundary.

using Cratis.Chronicle.Events;
using Cratis.Chronicle.EventSequences;
using Cratis.Chronicle.EventSources;
[EventType]
public record AccountOpened(string Owner);
[EventType]
public record IdentityVerified(string Method);
[EventType]
public record MoneyDeposited(decimal Amount);
[EventType]
public record MoneyWithdrawn(decimal Amount);
[EventSource("Account", Description = "A customer's bank account", Concurrency = ConcurrencyDimensions.EventSourceId)]
[EventStream("Onboarding", Description = "Opening the account and verifying the customer")]
[EventStream(
"Transactions",
Description = "Deposits and withdrawals, one stream per month",
Concurrency = ConcurrencyDimensions.EventSourceId | ConcurrencyDimensions.EventStreamType | ConcurrencyDimensions.EventStreamId)]
public class AccountEventSource : IEventSource;
public class AccountService(IEventLog eventLog)
{
public Task<AppendResult> Open(EventSourceId accountId, string owner) =>
eventLog.Append<AccountEventSource>(accountId, new AccountOpened(owner), eventStream: "Onboarding");
public Task<AppendResult> Verify(EventSourceId accountId, string method) =>
eventLog.Append<AccountEventSource>(accountId, new IdentityVerified(method), eventStream: "Onboarding");
public Task<AppendResult> Deposit(EventSourceId accountId, string month, decimal amount) =>
eventLog.Append<AccountEventSource>(
accountId,
new MoneyDeposited(amount),
eventStream: "Transactions",
eventStreamId: month);
}

View C# snippet source on GitHub

The scopes this produces:

Append Scope narrows to
Deposit(a1, "2026-04", …) account a1, stream type Transactions, stream id 2026-04
Verify(a1, …) every event of account a1, because Onboarding declares no dimensions of its own and inherits EventSourceId

What conflicts, when both writers read before either appends:

  • Two deposits to a1 in 2026-04 conflict. The second is rejected and nothing is written for it.
  • A deposit to a1 in 2026-05 does not conflict with a deposit in 2026-04.
  • A deposit to account a2 does not conflict with anything on a1.
  • Verify after a deposit to the same account conflicts, because its scope covers the whole account. A deposit after Verify does not conflict, because its scope covers only the month.

The first deposit of each new month is not checked by default. Two writers that open 2026-06 at the same time both succeed. To check it, turn on CheckFirstAppendIntoAScope, as described in Concurrency.

The bank account allows at most 5000 withdrawn a month. This rule depends on the withdrawals already recorded, so use a decision read to total them in the month’s stream before appending. Reuse the account definition and events from the first scenario.

Take the stream type and event source type from the definition so that the read and append use the same names. Declared dimensions alone guard every event in the month, including deposits, and do not capture what you read. Reading the whole account would also bring other months into the guard.

using Cratis.Chronicle;
using Cratis.Chronicle.Events;
using Cratis.Chronicle.EventSequences;
using Cratis.Chronicle.Projections.ModelBound;
using Cratis.Chronicle.ReadModels;
// Uses the Account definition and the MoneyWithdrawn event from the first scenario.
// The decision model totals the withdrawals in the stream it is read for.
[Passive]
[FromEvent<MoneyWithdrawn>]
public record WithdrawalsThisMonth(string Id, [AddFrom<MoneyWithdrawn>(nameof(MoneyWithdrawn.Amount))] decimal Total);
public class LimitedWithdrawals(IEventStore eventStore)
{
const decimal MonthlyLimit = 5000m;
public async Task<bool> Withdraw(EventSourceId accountId, string month, decimal amount)
{
var definition = eventStore.EventSources.GetFor(typeof(AccountEventSource));
var transactions = definition.FindStream("Transactions")!;
// The read and the append take the same names from the definition.
var read = await eventStore.GetDecisionReads().GetDetached<WithdrawalsThisMonth>(
accountId,
transactions.EventStreamType,
month,
definition.EventSourceType);
if ((read.Instance?.Total ?? 0m) + amount > MonthlyLimit)
{
return false;
}
var result = await eventStore.EventLog.AppendMany(
[
new EventForEventSourceId(accountId, new MoneyWithdrawn(amount))
{
EventSource = typeof(AccountEventSource),
EventStream = "Transactions",
EventStreamId = month
}
],
guardedBy: [read]);
return result.IsSuccess;
}
}

View C# snippet source on GitHub

guard Account-a1: types=[MoneyWithdrawn], sourceType=Account, streamType=Transactions, streamId=2026-04, after <tail at read>
  • Two withdrawals in 2026-04 on a1 conflict. The second is rejected, and its caller reads again.
  • A deposit in 2026-04 does not conflict, because the read model counts only MoneyWithdrawn.
  • A withdrawal in 2026-05, or on another account, does not conflict.
  • The guard replaces the definition’s default scope for this append. Declared dimensions widen a guard only when you commit under read protection. See How guards are derived.

A count version of this rule is explained step by step in Event sources and the Dynamic Consistency Boundary. The same rule on a BankAccount source is in A limit inside one stream.

A project collects notes from several authors. Different authors should be able to write without conflicting, while simultaneous writes from one author should be detected.

Use one Notes stream per author, with the author id as the stream id. Include the project id, stream type and stream id in the concurrency dimensions so the guard distinguishes both projects and authors. A single stream for all notes would make authors conflict with each other; a separate event source per author would lose the project as the common key.

using Cratis.Chronicle.Events;
using Cratis.Chronicle.EventSequences;
using Cratis.Chronicle.EventSources;
[EventType]
public record NoteAdded(string Text);
// One stream per author: authors write notes on the same project without conflicting with each other.
[EventSource("Project", Concurrency = ConcurrencyDimensions.EventSourceId)]
[EventStream(
"Notes",
Description = "Notes on a project, one stream per author",
Concurrency = ConcurrencyDimensions.EventSourceId | ConcurrencyDimensions.EventStreamType | ConcurrencyDimensions.EventStreamId)]
public class ProjectEventSource : IEventSource;
public class NoteService(IEventLog eventLog)
{
public Task<AppendResult> AddNote(EventSourceId projectId, string authorId, string text) =>
eventLog.Append<ProjectEventSource>(
projectId,
new NoteAdded(text),
eventStream: "Notes",
eventStreamId: authorId);
}

View C# snippet source on GitHub

The stream id is the author id. The Notes stream declares the event source id, the stream type and the stream id, so the scope narrows to one author’s notes on one project.

  • Two authors adding notes to the same project do not conflict.
  • The same author adding notes from two devices at once conflicts on the second append when both read the same existing tail. Read the new tail and append again.
  • Appends to the project’s other streams, or to other projects, are not affected.

The project’s own event source declares EventSourceId, so an append that carries no stream is guarded against every event of the project, including every author’s notes. If project-wide facts should not conflict with note-taking, give them a separate stream with its own stream-level dimensions. Merely naming a new stream still inherits EventSourceId.

A money transfer is a process with several steps. Give each transfer one event source and record its steps in a Process stream. A reactor handles those steps after they are written, while a closing event prevents further appends to the finished stream.

Use an event-source-wide guard because concurrent attempts to advance the same transfer should conflict. A typed observer filter keeps the reactor on the declared Process stream and lets the analyzer check that the stream exists. Closing it with the final event avoids a separate CompleteStream call after that append.

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Events.Constraints;
using Cratis.Chronicle.EventSequences;
using Cratis.Chronicle.EventSources;
using Cratis.Chronicle.Reactors;
[EventType]
public record TransferRequested(string From, string To, decimal Amount);
[EventType]
public record TransferFundsReserved;
[EventType]
[ClosesStream]
public record TransferCompleted;
// One event source per transfer, and one stream for the process that carries it out.
[EventSource("Transfer", Concurrency = ConcurrencyDimensions.EventSourceId)]
[EventStream("Process", Description = "The steps of one transfer")]
public class TransferEventSource : IEventSource;
// Only the steps of a transfer's own process reach this reactor.
[FromEventSource<TransferEventSource>("Process")]
public class TransferProcess(IEventLog eventLog) : IReactor
{
public async Task Requested(TransferRequested @event, EventContext context)
{
// Reserve the funds, then record the step on the same stream.
await eventLog.Append<TransferEventSource>(context.EventSourceId, new TransferFundsReserved(), eventStream: "Process");
}
public async Task Reserved(TransferFundsReserved @event, EventContext context)
{
// The closing event ends the stream: nothing more can be appended to it.
await eventLog.Append<TransferEventSource>(context.EventSourceId, new TransferCompleted(), eventStream: "Process");
}
}
public class TransferStarter(IEventLog eventLog)
{
public Task<AppendResult> Start(EventSourceId transferId, string from, string to, decimal amount) =>
eventLog.Append<TransferEventSource>(transferId, new TransferRequested(from, to, amount), eventStream: "Process");
}

View C# snippet source on GitHub

  • The reactor uses [FromEventSource<TransferEventSource>("Process")]. Its handlers receive matching events from transfer process streams, not other streams.
  • The definition declares only the event source id as a concurrency dimension. The scope covers one transfer, so different transfers do not conflict. Two writers advancing the same transfer conflict when they read the same existing tail.
  • TransferCompleted carries [ClosesStream]. Appended to the Process stream, it closes that transfer’s process stream. Once the closure is recorded, later steps are refused with StreamClosed.

The closing event and closure index are not crash-atomic: a crash can leave the event stored without its closure. Reindex the closing constraint to repair a missing closure; see Close a stream.

A reactor reacts after the event is written. It is not a guard, and it can be given an event again after a recovery. Make each step safe to repeat, and see once only for what that attribute does and does not promise.

Moving money between two accounts writes one event to each account. It is one logical operation, so both events are written together or not at all. This scenario uses the definition and events from the first scenario.

Use one atomic AppendMany with one event per account, routed through the definition. Each account gets its own month guard, and the kernel checks both before writing either event. Two separate appends could leave one side written. When the transfer depends on a balance, use a decision read per account as shown in A rule across two keys.

using Cratis.Chronicle.EventSequences;
public class AccountTransfers(IEventLog eventLog)
{
// Uses the Account definition and events from the first scenario.
public Task<AppendManyResult> Move(EventSourceId from, EventSourceId to, string month, decimal amount) =>
eventLog.AppendMany(
[
new EventForEventSourceId(from, new MoneyWithdrawn(amount))
{
EventSource = typeof(AccountEventSource),
EventStream = "Transactions",
EventStreamId = month
},
new EventForEventSourceId(to, new MoneyDeposited(amount))
{
EventSource = typeof(AccountEventSource),
EventStream = "Transactions",
EventStreamId = month
}
]);
}

View C# snippet source on GitHub

Each event source id gets its own scope, built from the definition: account from, Transactions, the month; and account to, Transactions, the month. The two scopes are checked against the state before the batch.

  • If either account got a deposit or a withdrawal in that month after the tail was read, the whole append is rejected, and neither event is written.
  • A concurrent deposit to either account in another month does not matter.

This records the transfer as two events, one on each account, because every event has exactly one event source. See Dynamic Consistency Boundary in Chronicle for what that means when one fact concerns two entities.

Continue with Dynamic Consistency Boundary to build a guarded decision on one stream. How it works traces how Chronicle resolves a definition into routing and scopes; Questions and pitfalls covers unexpected conflicts and missed events.