Skip to content

Dynamic Consistency Boundary examples in Chronicle

Chronicle handles Dynamic Consistency Boundary (DCB) examples with constraints for unique values and decision reads for rules that depend on state. The examples below adapt the cases from dcb.events to Chronicle’s event-source model, where each event belongs to one source and custom tags do not participate in consistency checks. For the mapping behind these choices, read Dynamic Consistency Boundary in Chronicle.

Example Chronicle answer
Course subscription Two decision reads, two events, one AppendMany
Unique username A [Unique] constraint
Invoice number A numbering event source with one decision read, see Gapless invoice numbers
Opt-in token Both events on the sign-up’s event source
Dynamic product price One decision read per product, one event on the order
Idempotency A [Unique] constraint on the token

A course accepts at most N students, and a student joins at most five courses. DCB records one StudentSubscribedToCourse event tagged with both entities and composes the state needed for both checks into one decision model.

In Chronicle, take one decision read for the course and one for the student. Append an event of its own type to each event source in a single AppendMany, with both reads in guardedBy. If a matching event changes either history after its read, the batch is rejected and neither event is written. Read again to find out whether the course still has space and the student can still join.

The code is the A rule across two keys scenario.

The subscription is recorded in both histories. Use CourseSeatTaken and CourseSeatReleased for the course, and StudentJoinedCourse and StudentLeftCourse for the student. Each model then counts only the types belonging to its source. Appending the same type to both sources would also create seat rows keyed by student IDs. Both histories need the fact in this model; removing one event would leave one of the counts incomplete.

Keep the reads focused on the rule: capacity and seats for the course, subscription count for the student. A joined model of both entities is not admitted as a Chronicle decision read.

To keep a username unique across users, the DCB example tags claiming and releasing events with username:<name> and queries that tag.

In Chronicle, declare a constraint. The kernel checks it inside the append for every writer, without an application read or a decision-read guard. If the name is taken, handle the constraint violation rather than retrying the same value.

The code is the Unique username scenario. Normalize the value before it reaches the event, as DCB does: jamesbond and JamesBond are two values to a constraint. To release a name when a user is removed or renamed, use model-bound constraints or declarative constraints. A decision read cannot do this job: it guards one key’s history, not a value across keys.

For invoice numbers that form an unbroken sequence, the DCB example queries every InvoiceCreated event, takes the last number plus one, and appends with a condition on that query.

In Chronicle, make the sequence one event source with a fixed ID. Append each InvoiceCreated there, guarded by a decision read of the last number. If two requests read the same number, only one append succeeds; the other must read again before choosing its number. One event is written, with no duplicate copy on another source.

All numbering requests share this key. Concurrent decisions can conflict, and every read folds the numbering history again. Use Gapless invoice numbers for the code and cost discussion before choosing this design.

A sign-up should be confirmed once, with the token that was sent, before it expires. The DCB example tags SignUpInitiated and SignUpConfirmed with the email and token, then queries both tags to find the pending sign-up.

In Chronicle, put both events on the sign-up’s own event source and carry its sign-up ID in the confirmation link. Read that key through a decision read, then check the stored token, expiry and confirmation status. The read guards against a concurrent confirmation; your application performs the token and time checks. The token does not need to be a concurrency-filter dimension.

using Cratis.Chronicle;
using Cratis.Chronicle.Events;
using Cratis.Chronicle.EventSequences;
using Cratis.Chronicle.Projections.ModelBound;
using Cratis.Chronicle.ReadModels;
[EventType]
public record SignUpInitiated(string Email, string TokenHash, DateTimeOffset ExpiresAt);
[EventType]
public record SignUpConfirmed;
// Both events live on the sign-up's own event source. The token is checked against the sign-up
// the caller names, so the token itself needs no place in the boundary.
[FromEvent<SignUpInitiated>]
public record PendingSignUp(Guid Id, string TokenHash, DateTimeOffset ExpiresAt, [Count<SignUpConfirmed>] int Confirmations);
public enum ConfirmOutcome
{
Confirmed,
UnknownSignUp,
AlreadyConfirmed,
WrongToken,
Expired,
ChangedConcurrently,
Failed
}
public static class ConfirmSignUp
{
public static async Task<ConfirmOutcome> Handle(IEventStore eventStore, Guid signUpId, string tokenHash, DateTimeOffset now)
{
var read = await eventStore.GetDecisionReads().GetDetached<PendingSignUp>(signUpId);
if (read.Instance is not { } signUp)
{
return ConfirmOutcome.UnknownSignUp;
}
if (signUp.Confirmations > 0)
{
return ConfirmOutcome.AlreadyConfirmed;
}
if (signUp.TokenHash != tokenHash)
{
return ConfirmOutcome.WrongToken;
}
if (signUp.ExpiresAt < now)
{
return ConfirmOutcome.Expired;
}
// Two requests with the same valid token race: the second append is rejected.
var result = await eventStore.EventLog.AppendMany(
[new EventForEventSourceId(signUpId, new SignUpConfirmed())],
guardedBy: [read]);
if (result.GetDecisionConflicts([read]).Any())
{
return ConfirmOutcome.ChangedConcurrently;
}
return result.IsSuccess ? ConfirmOutcome.Confirmed : ConfirmOutcome.Failed;
}
}

View C# snippet source on GitHub

Use an opaque sign-up ID rather than the email as the event source ID: these IDs are stored in plaintext and cannot be encrypted. Store a hash of the token in the event, or mark the property [Encrypted]; see encrypted values.

If the caller has only an email, look up the sign-up ID in a read model first. That lookup is eventually consistent and only locates the key. The subsequent decision read, not the lookup, supplies the guard.

An order should use a current price, or a recent price still inside an allowed grace period. The DCB example builds one decision model per product in the cart and combines their conditions when placing the order.

The Chronicle example below uses a narrower price rule: it keeps the current price and the previous one, accepting the previous price only within the grace period. It does not retain every price that might still be inside DCB’s grace window after several changes.

Take one decision read per product and append one event on the order’s event source, with all reads in guardedBy. Nothing is appended to the products. If a matching price event arrives after any read, the batch is rejected and the order is not written.

using Cratis.Chronicle;
using Cratis.Chronicle.Events;
using Cratis.Chronicle.EventSequences;
using Cratis.Chronicle.Projections.ModelBound;
using Cratis.Chronicle.ReadModels;
[EventType]
public record ProductDefined(decimal Price);
[EventType]
public record ProductPriceChanged(decimal OldPrice, decimal NewPrice);
public record OrderedItem(string ProductId, decimal DisplayedPrice, int Quantity);
[EventType]
public record ProductsOrdered(IReadOnlyList<OrderedItem> Items);
// The decision model for one product: its current price, the one before and when it changed.
// A reduced variant: a price older than the previous one is never accepted, even inside the grace period.
[FromEvent<ProductDefined>]
public record ProductPrice(
string Id,
[SetFrom<ProductDefined>(nameof(ProductDefined.Price))]
[SetFrom<ProductPriceChanged>(nameof(ProductPriceChanged.NewPrice))]
decimal Current,
[SetFrom<ProductPriceChanged>(nameof(ProductPriceChanged.OldPrice))]
decimal Previous,
[SetFromContext<ProductPriceChanged>(nameof(EventContext.Occurred))]
DateTimeOffset ChangedAt);
public static class OrderProducts
{
static readonly TimeSpan GracePeriod = TimeSpan.FromMinutes(10);
public static async Task<bool> Handle(IEventStore eventStore, EventSourceId orderId, IReadOnlyList<OrderedItem> items, DateTimeOffset now)
{
var reads = eventStore.GetDecisionReads();
var guards = new List<IDecisionRead>();
// One decision read per product in the cart. The set is dynamic: it is whatever the order contains.
foreach (var item in items)
{
var read = await reads.GetDetached<ProductPrice>(new ReadModelKey(item.ProductId));
if (read.Instance is not { } price)
{
return false;
}
var isCurrent = price.Current == item.DisplayedPrice;
var isRecentPrevious = price.Previous == item.DisplayedPrice && now - price.ChangedAt <= GracePeriod;
if (!isCurrent && !isRecentPrevious)
{
return false;
}
guards.Add(read);
}
// One event on the order's own event source. The product keys are only read, never appended to,
// and a price change after the reads rejects the append.
var result = await eventStore.EventLog.AppendMany(
[new EventForEventSourceId(orderId, new ProductsOrdered(items))],
guardedBy: guards);
return result.IsSuccess;
}
}

View C# snippet source on GitHub

The set of reads is whatever the order contains, so it is dynamic in the same sense as DCB’s. One event records the order. Nothing is written to the products. The cost is one fold per product in the cart, so very large carts are the case to measure first.

Idempotency means a retried request does not place the order twice. The DCB example tags OrderPlaced with a client token and queries that tag before appending.

In Chronicle, put [Unique] on the event’s token property. The client sends the same token on every retry, while the server generates a new event source ID for each attempt. A retry then tries to claim an existing token from a different source, so the kernel rejects it as a constraint violation. Treat that token violation as “already placed”.

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Events.Constraints;
using Cratis.Chronicle.EventSequences;
[EventType]
public record OrderPlaced(string Customer, [property: Unique] string IdempotencyToken);
public enum PlaceOrderOutcome
{
Placed,
AlreadyPlaced,
Failed
}
public static class PlaceOrder
{
// The caller generates the token once per order and sends the same token on every retry.
// The order's event source id is generated here, so a retry is a different source with the same token.
public static async Task<PlaceOrderOutcome> Handle(IEventLog eventLog, string customer, string idempotencyToken)
{
var result = await eventLog.Append(EventSourceId.New(), new OrderPlaced(customer, idempotencyToken));
if (result.HasConstraintViolations)
{
return PlaceOrderOutcome.AlreadyPlaced;
}
return result.IsSuccess ? PlaceOrderOutcome.Placed : PlaceOrderOutcome.Failed;
}
}

View C# snippet source on GitHub

By default a unique constraint lets one event source reclaim its own value, so do not reuse the event source ID across retries, or the second event would be accepted. If the order ID comes from the client, derive the event source ID from the token and declare a unique event type constraint, so a second OrderPlaced for the same source is rejected. This protects against an accidental resubmission. It does not protect against someone who deliberately sends a fresh token.

To implement one of these rules, continue with Scenarios. For a different rule, use Choosing how a rule holds to select the mechanism first.

The API details are in Decision reads, Constraints and Event sources and the Dynamic Consistency Boundary.