Reactor delivery identity for repeat-safe side effects
ReactorDelivery identifies one event delivered to one reactor partition in Cratis Chronicle, where events are grouped by event source id. Its identity stays the same when recovery or replay delivers that event again. Use it to key a side-effect receipt or a request to a receiver that deduplicates repeated requests; the identity alone does not prevent duplicate work.
using Cratis.Chronicle.Events;using Cratis.Chronicle.Reactors;
[EventType]public record IdempotentPaymentDue(string OrderId, decimal Amount);
public interface IIdempotentPaymentGateway{ Task Charge(string orderId, decimal amount);}
// Your storage, not Chronicle's. One row per completed delivery, keyed by its identity.public interface IDeliveryReceipts{ Task<bool> HasCompleted(DeliveryId delivery);
Task Complete(DeliveryId delivery);}
public class IdempotentBilling(IIdempotentPaymentGateway payments, IDeliveryReceipts receipts) : IReactor{ public async Task PaymentDue(IdempotentPaymentDue @event, ReactorDelivery delivery) { if (await receipts.HasCompleted(delivery.Id)) { return; }
await payments.Charge(@event.OrderId, @event.Amount); await receipts.Complete(delivery.Id); }}Kotlin does not support this workflow yet.Java does not support this workflow yet.defmodule IdempotentPaymentDue do use Chronicle.Events.EventType, id: "idempotent-payment-due"
defstruct [:order_id, :amount]end
defmodule IdempotentPaymentGateway do def charge(_order_id, _amount), do: :okend
# Your storage, not Chronicle's. One row per completed delivery, keyed by its identity.defmodule IdempotentDeliveryReceipts do def completed?(_delivery_id), do: false def complete(_delivery_id), do: :okend
defmodule IdempotentBilling do use Chronicle.Reactors.Reactor
@handles IdempotentPaymentDue
@impl true def handle(%IdempotentPaymentDue{} = event, %{delivery_id: delivery_id}) do if IdempotentDeliveryReceipts.completed?(delivery_id) do :ok else with :ok <- IdempotentPaymentGateway.charge(event.order_id, event.amount) do IdempotentDeliveryReceipts.complete(delivery_id) end end endendUse an application-owned receipt store and payment gateway, supplied through your client artifact activator.
// Copyright (c) Cratis. All rights reserved.// Licensed under the MIT license. See LICENSE file in the project root for full license information.
import { eventType, handles, reactor, EventContext, ReactorDelivery, ReactorServices } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()class IdempotentPaymentDue { @field(String) readonly orderId: string; @field(Number) readonly amount: number;
constructor(orderId: string = '', amount: number = 0) { this.orderId = orderId; this.amount = amount; }}
interface IIdempotentPaymentGateway { charge(orderId: string, amount: number): Promise<void>;}
// Your durable storage, not Chronicle's: one receipt per completed delivery.interface IDeliveryReceipts { hasCompleted(deliveryId: string): Promise<boolean>; complete(deliveryId: string): Promise<void>;}
@reactor('idempotent-billing')class IdempotentBilling { constructor(private readonly payments: IIdempotentPaymentGateway, private readonly receipts: IDeliveryReceipts) {}
@handles(IdempotentPaymentDue) async paymentDue(event: IdempotentPaymentDue, _context: EventContext, _services: ReactorServices, delivery: ReactorDelivery): Promise<void> { if (await this.receipts.hasCompleted(delivery.id)) return;
await this.payments.charge(event.orderId, event.amount); // A crash before this write can repeat the charge. This is not exactly-once delivery. await this.receipts.complete(delivery.id); }}delivery.id joins reactor, event store, namespace, event sequence, partition and sequence number with #,
matching the .NET receipt key. Retry and replay use the same key. Keep the reactor id explicit and stable.
Chronicle still delivers at least once and stores no receipts. Make the receipt atomic with the effect where
possible; for a remote effect, use a gateway that accepts delivery.id as an idempotency key to close the gap.
Use delivery.Id as the receipt key. Check for a completed receipt before doing the work, and record completion afterwards. This check has a failure window unless recording the receipt is atomic with the effect; see What it does and does not guarantee.
Why the existing markers are not enough
Section titled “Why the existing markers are not enough”OnceOnly and Replay control replay, such as history re-delivered after an observer rewind, redaction or revision. Recovery of a failed event-source partition is ordinary observation, so neither marker prevents the regular handler from running again.
That distinction matters when a handler charges a card and then fails before Chronicle records its progress. A retry can repeat the charge. The delivery identity stays the same across failure and recovery, so your receipt check or the payment API’s idempotency key can recognize the repeated request. See Troubleshooting for repeated-effect symptoms and Observers for retry and quarantine configuration.
How the three relate
Section titled “How the three relate”| Mechanism | Covers replay | Covers recovery after a failure | Needs storage |
|---|---|---|---|
[OnceOnly] |
Yes — the handler is skipped | No | No |
[Replay] |
Yes — a different handler takes over | No | No |
ReactorDelivery |
The identity matches; your code must check it | The identity matches; your code must check it | Application-owned receipt, or receiver-side deduplication |
Use [OnceOnly] when replay should skip the handler, or [Replay] when replay needs different handling. Add delivery-keyed duplicate protection for effects that could repeat during recovery. You can keep [OnceOnly] alongside that protection: replay skips the call, while ordinary retries still reach your receipt check.
using Cratis.Chronicle.Events;using Cratis.Chronicle.Reactors;
[EventType]public record CustomerWelcomed(string CustomerId);
public interface IWelcomeMail{ Task Send(string customerId);}
public class WelcomeMailer(IWelcomeMail mail, IDeliveryReceipts receipts) : IReactor{ [OnceOnly] public async Task SendWelcomeMail(CustomerWelcomed @event, ReactorDelivery delivery) { if (await receipts.HasCompleted(delivery.Id)) { return; }
await mail.Send(@event.CustomerId); await receipts.Complete(delivery.Id); }}Kotlin does not support this workflow yet.Java does not support this workflow yet.defmodule CustomerWelcomed do use Chronicle.Events.EventType, id: "customer-welcomed"
defstruct [:customer_id]end
defmodule WelcomeMail do def send(_customer_id), do: :okend
defmodule WelcomeMailerReceipts do def completed?(_delivery_id), do: false def complete(_delivery_id), do: :okend
defmodule WelcomeMailer do # Skip CustomerWelcomed while the observer replays. Replay exclusion is not # exactly-once: recovering a failed partition can still deliver it again, # so the delivery receipt guards the side effect as well. use Chronicle.Reactors.Reactor, once_only: [CustomerWelcomed]
@handles CustomerWelcomed
@impl true def handle(%CustomerWelcomed{} = event, %{delivery_id: delivery_id}) do if WelcomeMailerReceipts.completed?(delivery_id) do :ok else with :ok <- WelcomeMail.send(event.customer_id) do WelcomeMailerReceipts.complete(delivery_id) end end endendTypeScript does not support this workflow yet.What counts as the same delivery
Section titled “What counts as the same delivery”The identity is built from six values Chronicle already knows:
| Component | What it is |
|---|---|
Reactor |
The reactor the event is delivered to |
EventStore |
The event store the event belongs to |
Namespace |
The namespace within that event store |
EventSequence |
The event sequence the reactor observes — the event log, or an inbox |
Partition |
The event source id the event is observed under |
SequenceNumber |
The event’s position in the event sequence |
Two deliveries agreeing on all six are the same delivery; differing on any one of them makes them different. There
is deliberately nothing in there about why the event arrived, so a replay and the live delivery it repeats share
one identity. If a handler needs to know why, take an EventContext alongside and read its ObservationState.
ReactorDelivery is a record, so you can compare two of them directly. delivery.Id renders the same components
as a single string for use as a storage key.
Keys for returned events
Section titled “Keys for returned events”When a C# handler returns events, the built-in handlers derive idempotency keys from the delivery identity, the reactor’s effect epoch and each event’s position in the returned value. With a kernel that supports idempotent appends, repeating the same keys and output does not append another copy. See the linked page for conflicts and the fallback on kernels without that capability.
To key an effect you append yourself, call delivery.IdempotencyKeyFor("effect-name") and use AppendOnce; see Appending events. These keys protect event-log appends, not handler invocations or external calls. A payment, email or webhook needs its own duplicate protection.
When to bump the effect epoch
Section titled “When to bump the effect epoch”EffectEpoch is a number on the reactor attribute, 0 by default. Set it with [Reactor("id", effectEpoch: 1)], or [Reactor("id", "sequence", effectEpoch: 1)] when you also name the event sequence. It is part of the derived keys but not of delivery.Id, so your receipts keep matching when you change it.
Raise the epoch only when the same input should deliberately append new output. Review which historical inputs will run again: the new keys permit new appends. Keep the reactor’s id and event sequence stable so you retain its observer identity.
For ordinary retries and replays, keep the epoch and build output from stable inputs. Changed content under an existing key causes a conflict and fails the partition. A fresh Guid, the current time or a changed lookup result can cause that conflict even when you did not intend to change the handler’s meaning. Fix unintended variation rather than raising the epoch to bypass it.
What it does and does not guarantee
Section titled “What it does and does not guarantee”ReactorDelivery is not exactly-once delivery. Chronicle does not know whether an external effect completed and stores no application receipt for it. You own the receipt’s storage, uniqueness and retention policy, including how long old deliveries must remain recognizable.
The diagram above shows a receipt recorded before the handler fails. If the process instead dies after the charge but before writing that receipt, the retry can charge again. Concurrent attempts can also both pass a simple check. Recording the receipt before a remote call moves the failure window: a crash can leave a receipt for work that never happened.
For an effect in your own database, write the receipt and effect in the same transaction. For a remote call, pass the delivery identity as an idempotency key only if the receiver supports that contract, and account for its key retention and retry rules. The identity gives you a stable key; the transaction or receiver provides the duplicate protection.