Skip to content

Stage and commit Chronicle events with a unit of work

A Chronicle unit of work stages events in the .NET client and sends them as one append batch when you commit. Use it when a workflow produces events across several calls, but none should be sent until the workflow is ready. The staged events share a correlation id so you can trace the operation.

Commit is still an event append operation. Chronicle checks constraints and concurrency at that point, then persists an accepted batch atomically. A unit of work does not make other work, such as an HTTP call or a write to another database, part of that event transaction.

Choose a unit of work when different parts of one command need to contribute events to the same commit. If you already have the complete event list, AppendMany is the direct way to write it atomically.

Grouping events does not enforce the rule behind the decision. If the operation depends on state you read, use concurrency protection or a decision read. Use constraints for rules the kernel must enforce for every writer. Facts that can happen independently do not need to share a commit.

Begin a unit of work through the event store’s UnitOfWorkManager. Append through store.EventLog.Transactional to stage events in that unit; a plain store.EventLog.Append writes immediately and does not join it. Commit only after every event has been staged.

The example stages an order event and an inventory event under different event source ids. Neither transactional append sends an event on its own:

using Cratis.Chronicle;
using Cratis.Chronicle.Events;
using Cratis.Execution;
public static class TransactionalOrderWorkflow
{
public static async Task CommitOrder(IEventStore store)
{
var unitOfWork = store.UnitOfWorkManager.Begin(CorrelationId.New());
try
{
await store.EventLog.Transactional.Append(
"order-123",
new TransactionalOrderPlaced("order-123", 99.95m));
await store.EventLog.Transactional.Append(
"inventory-widget",
new TransactionalInventoryReserved("widget", 1));
await unitOfWork.Commit();
// Commit reports a rejected batch through the unit of work; it does not throw.
if (!unitOfWork.IsSuccess)
{
throw new OrderWasNotCommitted(unitOfWork.GetConstraintViolations(), unitOfWork.GetAppendErrors());
}
}
catch
{
// Commit completes the unit of work even when the batch is rejected, and a completed
// unit of work cannot be rolled back. Only roll back what was never committed.
if (!unitOfWork.IsCompleted)
{
await unitOfWork.Rollback();
}
throw;
}
}
}
[EventType]
public record TransactionalOrderPlaced(string OrderId, decimal TotalAmount);
[EventType]
public record TransactionalInventoryReserved(string Sku, int Quantity);
public class OrderWasNotCommitted(IEnumerable<object> violations, IEnumerable<object> errors)
: Exception($"The order was not committed: {string.Join("; ", violations.Concat(errors))}");

View C# snippet source on GitHub

After Commit, inspect IsSuccess before reporting success. A constraint or concurrency rejection completes the unit without appending the batch; it is reported in the result rather than thrown. Roll back if the workflow fails before commit, and dispose the unit when you are finished. Rollback cannot undo events already sent to Chronicle. For a timeout or an uncertain storage outcome, follow When the outcome is unknown before retrying.

Commit an ordered batch with exact concurrency

Section titled “Commit an ordered batch with exact concurrency”

When a decision reads several streams, capture the exact revision it used and stage the resulting events with that scope. AddEvents materializes the events and scopes immediately, preserves cross-stream order, and still waits for the unit of work to commit before sending anything to Chronicle.

using Cratis.Chronicle;
using Cratis.Chronicle.Events;
using Cratis.Chronicle.EventSequences;
using Cratis.Chronicle.EventSequences.Concurrency;
using Cratis.Execution;
public static class TransactionalTransferWorkflow
{
public static async Task<bool> TryCommitTransfer(
IEventStore store,
EventSequenceNumber expectedAuthorizationRevision)
{
using var unitOfWork = store.UnitOfWorkManager.Begin(CorrelationId.New());
EventSourceId authorizationScopeLabel = "authorization-history";
var authorizationScope = new ConcurrencyScope(
expectedAuthorizationRevision,
EventStreamType: "authorization");
unitOfWork.AddEvents(
EventSequenceId.Log,
[
new EventForEventSourceId(
"account-from",
new TransferDebited(100m)),
new EventForEventSourceId(
"account-to",
new TransferCredited(100m))
],
[new(authorizationScopeLabel, authorizationScope)]);
await unitOfWork.Commit();
return unitOfWork.IsSuccess;
}
}
[EventType]
public record TransferDebited(decimal Amount);
[EventType]
public record TransferCredited(decimal Amount);

View C# snippet source on GitHub

A concurrency-scope key can be an independent label when the scope does not narrow by event-source ID. It does not need to match either event target, so one decision-wide stream-, type-, or event-type-scoped revision can protect the entire ordered batch. If a scope does narrow by event-source ID, its key must be that event-source ID.

A scope list may repeat a label for different stream predicates, in one AddEvents call or across several calls. The unit retains every guard and commits them together; conflicting expected positions for the same ordered predicate are refused. This requires a kernel advertising concurrency-scope-conjunctions. See Several guards for one source.

Every event target and scope label must contain a non-whitespace value; blank labels cannot survive transport and are rejected during enrollment.

Chronicle resolves the configured concurrency strategy for an event target that has no supplied scope or carries ConcurrencyScope.NotSet. An independent non-target label has no event target from which to resolve a strategy, so Chronicle rejects NotSet and incomplete scopes for those labels. Give an independent label a concrete exact scope or ConcurrencyScope.None.

AddEvents snapshots the event list, scope collection, and every scope’s nested event-type filter before it binds or stages anything in the unit of work. When ordered enrollment first participates in a unit of work, Chronicle also snapshots effective scopes from preceding AddEvent calls; later AddEvent scopes are snapshotted as they are enrolled. Later mutations to caller-owned collections therefore cannot change the eventual commit, and a lazy collection failure is reported during enrollment.

Dispose the unit of work even when enrollment validation fails, and inspect IsSuccess after commit. A completed Commit can still report a constraint or concurrency rejection rather than a successful append.

Consecutive AddEvent calls keep their existing source-grouped order. Each AddEvents call creates an exact-order segment between those legacy segments. Commit flattens the segments in enrollment-call order and sends all of them through one atomic append.

Legacy-only AddEvent calls retain their historical event-sequence behavior. Once AddEvents participates, every event in the unit of work must name the same event sequence; a mismatch is rejected before the ordered batch is staged.

Attach an IUnitOfWorkEnrollmentContributor with IUnitOfWork.AddEnrollmentContributor when a command must require a concurrency scope for the events it stages. Keep the returned IDisposable handle for that command invocation and dispose it when the command finishes. Each registration is independent, including nested commands sharing a unit of work. Alternate unit-of-work implementations that do not support contributors throw UnitOfWorkEnrollmentContributorsNotSupported when a contributor is attached.

Chronicle calls GetRequiredScope(UnitOfWorkEnrollment) before staging events, in registration order. The enrollment describes the event sequence, event source, caller-supplied scope (NotSet if omitted), and events for that source in this call. Return ConcurrencyScope.NotSet when no requirement applies. AddEvents consults each distinct event-target predicate, including targets without a supplied scope entry; scope-only entries are not consulted. Several supplied guards for one target produce separate enrollments, so each notification retains its own effective scope.

A required scope replaces NotSet, but cannot replace a conflicting explicit scope. Event-type filters compare as sets. Null filters and the All, Default, and unspecified source-type sentinels compare as equivalent non-narrowing filters. Conflicts throw ConflictingEnrollmentScope before anything from that enrollment call is staged. Required scopes remain on the unit after the contributor is removed: later legacy appends, ordered batches, and scope-only entries cannot drop or contradict the requirement. Once a requirement is enrolled, every event in the unit must target the same event sequence, including events staged before the requirement. A required scope cannot share its event source with an enrolled decision read.

To classify a ConflictingEnrollmentScope, inspect its get-only typed properties: EventSourceId, Effective and Required (ConcurrencyScope), and EventSequenceId (the attempted sequence, supplied by Chronicle’s unit of work; null for the original three-argument constructor). Its message is redacted by design: it names differing scope dimensions without including identifiers or scope values. You can log or surface the message without exposing those values; treat the typed properties as sensitive diagnostic data.

Chronicle calls Enrolled(enrollment, effectiveScope) only after staging succeeds. Use it to record provenance for the accepted enrollment; its default implementation does nothing. Contributors must not enroll events or reads, change registrations, commit, roll back, or dispose the unit during consultation or notification; such mutations throw UnitOfWorkMutatedDuringEnrollment. A consultation exception stages nothing. A notification exception propagates and marks the unit failed: subsequent commit throws UnitOfWorkEnrollmentNotificationFailed without appending anything. Roll back or dispose that unit.

Atomicity is per call to AddEvent, AddEventWithNamedTags, or AddEvents, not per transactional AppendMany invocation: transactional methods that loop single-event enrollments can stage earlier events before a later enrollment fails. The transaction owner must roll back the failed operation. Contributors are not consulted for decision reads or at commit, and units without contributors retain their existing scope behavior.

Stage all events before committing or rolling back. Once commit begins (even while its append is pending), after a failed commit, after rollback, or after disposal, newly staged events cannot be included in that unit’s commit. The default UnitOfWorkLifecyclePolicy.Compatibility preserves existing AddEvent and AddEvents behavior for units without decision reads: late calls still stage their events, but Chronicle emits an error-level log for each attempt, with the unit’s correlation id and no event content. Units with decision reads continue to reject late staging.

Opt in to UnitOfWorkLifecyclePolicy.Strict through ChronicleOptions.UnitOfWorkLifecyclePolicy (also inherited by ChronicleClientOptions and ChronicleAspNetCoreOptions). In strict mode, both enrollment methods throw UnitOfWorkIsCompleted before inspecting or changing their input or the staged events. This applies to units created by the client’s UnitOfWorkManager, including those used by ASP.NET Core middleware. For units constructed directly, pass the policy to the UnitOfWork constructor; custom IUnitOfWork implementations are unaffected. Strict will become the default in the next major release.

While a commit is in flight, disposing the unit does nothing in either mode: it does not roll back, discard staged events, or call the completion callback early. The callback runs once when the pending commit finishes. This differs from the former Compatibility behavior; it prevents disposal from replacing an in-flight commit’s failure. In Compatibility mode, public Rollback() during a pending commit still clears staged events for units without a claimed and enrolled decision read, but cannot cancel events already submitted to Chronicle. A claimed unit with an enrolled decision read refuses public rollback during a pending commit and retains its staged events. In Strict mode, Rollback() refuses any pending commit without changing staged events. These pending-commit refusals throw UnitOfWorkIsCompleting; see decision-consistent reads for ownership rules.

AddCratisChronicle registers middleware that begins a unit of work for every request and, by default, commits it after the endpoint returns. Stage events with Transactional.Append. A plain eventLog.Append writes immediately, outside both the unit of work and any decision reads enrolled in it.

If the response has already been written, a commit rejection cannot change it. To report the outcome to the caller, call IUnitOfWorkCompletionFeature.CommitAsync() before responding, then check IsSuccess and GetDecisionConflicts(). Do not rely on an exception to signal a rejected batch. The middleware does not commit a completed unit again, and a second CommitAsync() returns without another commit.

For automatic completion before an MVC result or a minimal API result is returned, use the response adapters below.

A caller that owns the request, such as a command pipeline, can take over completion instead of the middleware. Read IUnitOfWorkCompletionOwnershipFeature from HttpContext.Features and call Claim() (or TryClaim(out var claim), which returns false when the unit is already claimed). Only one caller can claim a unit; a second Claim() throws UnitOfWorkCompletionAlreadyClaimed, and a claimed unit refuses IUnitOfWorkCompletionFeature.CommitAsync().

The IUnitOfWorkCompletionClaim exposes Commit() and Rollback(). Both return a UnitOfWorkCompletionResult and are idempotent: once the unit is completed, they return the same Result. Append outcomes and technical failures are reported in the result rather than thrown:

  • Outcome is Committed, Failed (constraint violations, concurrency violations or append errors), RolledBack or Unknown. Failed means Chronicle refused the commit and reported why in the violations and errors. Unknown means the commit failed technically and Exception holds the cause: the events may or may not have been appended, so never report an Unknown result as rolled back.
  • ConcurrencyViolations, DecisionConflicts, ConstraintViolations and Errors list what went wrong. A decision conflict is derived from a concurrency violation, so the violation appears in both lists.
  • IsSuccess, HasConflicts and HasConstraintViolations summarize the result.

If the owner completes the unit directly instead of through the claim, Commit() and Rollback() return the recorded outcome rather than throwing. The middleware never commits behind a claim’s back. If the action ends without the claim completing the unit, the middleware rolls it back and logs an error.

Report a failed commit before the response starts

Section titled “Report a failed commit before the response starts”

By default the middleware commits after the response and a failed commit cannot change it; the failure is logged. Failure reporting is off by default so existing endpoints keep their current responses.

For MVC controllers and Razor Pages, set ChronicleAspNetCoreOptions.UnitOfWork.ReportFailuresBeforeResponseStarts to true. AddUnitOfWork (also called by AddCratisChronicle) registers global action and page-handler filters that record whether the handler pipeline completed normally. When that signal is present, a global result filter commits an unclaimed unit before MVC executes the result. A refused commit replaces the result with problem details. Action-filter or page-handler-filter short-circuits, and handled exceptions observed by those filters, roll back instead; their results are left unchanged.

If no action or page-handler filter ran, there is no completion signal. The result filter neither claims nor completes the unit, leaving today’s middleware behavior intact. This includes authorization or resource-filter short-circuits that happen before the handler filters run.

The global UnitOfWorkResultFilter uses CompletionOrder = int.MaxValue. Result filters with any lower order run before it. A result filter registered on a controller or action with the same order (int.MaxValue) runs after it. Do not stage more events in those later filters: completion has already happened.

For minimal APIs, call .WithUnitOfWork() on the endpoint builder returned by MapPost, MapGet, or another route mapping. This explicitly opts the endpoint into pre-result completion regardless of ReportFailuresBeforeResponseStarts. The filter claims the request unit, lets the endpoint run, then commits before returning its result. On failure it returns problem details instead. If the endpoint throws, it rolls back and rethrows the exception.

Both adapters leave existing completion claims, including a command pipeline’s claim, alone. They also leave already completed units alone. The request unit-of-work middleware must be registered; the adapters do nothing when its completion feature is absent. They do not buffer responses: an endpoint that writes the response itself can start it before completion.

The failure mapping is shared by both adapters and the middleware:

  • Concurrency violations or decision conflicts return 409 problem details.
  • Constraint violations without conflicts return 400 validation problem details, with errors keyed by constraint name and containing the violation messages.
  • Append errors without violations return 500 problem details. The adapters also return 500 for a technically unknown commit outcome; they do not report it as a rollback.

These problem-details responses include the unit’s correlationId. Outside the adapters, enabling the option still lets the middleware report failures when nobody claimed the unit and the response has not started yet.

Beginning a unit while another is current makes the new unit current. When it completes, the unit that was current when it began becomes current again, provided it is still open, so a command that runs its own unit inside a request still leaves the request unit available to claim afterwards.

Scenarios shows an endpoint with decision reads, and Decision reads lists the ownership rules.

Rollback before commit begins discards the events staged in the unit of work. Nothing is sent to Chronicle for those staged events.