Skip to content

Reactor side effects by returning events

A Cratis Chronicle reactor can return follow-up events instead of calling IEventLog itself. The client appends those events after the handler completes, so the handler can focus on deciding what happened next. Returned-event appends and external calls have different duplicate-protection requirements, described below.

A returned-event append is part of handling the triggering event. If that append fails, the reactor partition fails with the append details and recovery follows the observer’s retry policy. This includes constraint violations, concurrency conflicts and append errors. See Error handling.

In C#, return a single event directly from a handler method, synchronously or as a Task<T>:

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Reactors;
[EventType]
public record SideEffectsBookReserved(string Isbn);
[EventType]
public record SideEffectsStockCheckRequested(string Isbn);
[EventType]
public record StockDecreased(string Isbn, int Quantity);
public class WarehouseReactor : IReactor
{
[OnceOnly]
public StockDecreased BookReserved(SideEffectsBookReserved @event, EventContext context) =>
new(@event.Isbn, 1);
[OnceOnly]
public async Task<StockDecreased> StockCheckRequestedAsync(SideEffectsStockCheckRequested @event, EventContext context)
{
var available = await FetchCurrentStockAsync(@event.Isbn);
return new StockDecreased(@event.Isbn, available);
}
Task<int> FetchCurrentStockAsync(string isbn) => Task.FromResult(0);
}

View C# snippet source on GitHub

By default, the returned event is appended to the event log using the EventSourceId from the incoming EventContext. You do not need to inject IEventLog.

The examples use [OnceOnly] so replay skips these handlers. Analyzer CHR0022 reports an event-returning handler without that marker. Derived keys can protect the returned-event append on supported kernels, but they do not stop the handler from running. [OnceOnly] does not suppress ordinary retries after failure; see Delivery identity.

In C#, return a sequence of known events — IEnumerable<TEvent>, TEvent[], List<TEvent>, or IReadOnlyList<TEvent> — to append several events in one handler call:

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Reactors;
[EventType]
public record MultipleSideEffectsBookReserved(string Isbn);
[EventType]
public record MultipleStockDecreased(string Isbn, int Quantity);
[EventType]
public record StockLow(string Isbn);
public class InventoryReactor : IReactor
{
public IEnumerable<object> BookReserved(MultipleSideEffectsBookReserved @event, EventContext context) =>
[
new MultipleStockDecreased(@event.Isbn, 1),
new StockLow(@event.Isbn),
];
}

View C# snippet source on GitHub

A bare event uses the triggering event’s EventSourceId, unless the C# reactor redirects it through ICanProvideEventSourceId. When the follow-up fact belongs to a different entity, return an explicit target instead.

For example, a member’s book reservation is recorded against the book:

using Cratis.Chronicle.Events;
public readonly record struct MemberId(string Value)
{
public static implicit operator EventSourceId(MemberId id) => new(id.Value);
}
public readonly record struct Isbn(string Value)
{
public static implicit operator EventSourceId(Isbn id) => new(id.Value);
}
[EventType]
public record BookReserved(MemberId MemberId, Isbn Isbn);

View C# snippet source on GitHub

To record the resulting activity against the member, return an EventForEventSourceId naming the member’s EventSourceId:

using Cratis.Chronicle.Events;
using Cratis.Chronicle.EventSequences;
using Cratis.Chronicle.Reactors;
[EventType]
public record MemberActivityRecorded(Isbn Isbn);
public class ReservationReactor : IReactor
{
public EventForEventSourceId BookReserved(BookReserved @event, EventContext context) =>
new(@event.MemberId, new MemberActivityRecorded(@event.Isbn));
}

View C# snippet source on GitHub

MemberActivityRecorded is appended to @event.MemberId, not to the book’s event source, so a member-activity projection can observe it there.

To record both member activity and a stock change, return events for both targets. In C#, IEnumerable<EventForEventSourceId>, EventForEventSourceId[], List<EventForEventSourceId> and IReadOnlyList<EventForEventSourceId> append the events together as a single transaction:

using Cratis.Chronicle.Events;
using Cratis.Chronicle.EventSequences;
using Cratis.Chronicle.Reactors;
[EventType]
public record FanOutStockDecreased(Isbn Isbn, int Quantity);
public class ReservationFanOutReactor : IReactor
{
public IEnumerable<EventForEventSourceId> BookReserved(BookReserved @event, EventContext context) =>
[
new(@event.MemberId, new MemberActivityRecorded(@event.Isbn)),
new(@event.Isbn, new FanOutStockDecreased(@event.Isbn, 1)),
];
}

View C# snippet source on GitHub

Each EventForEventSourceId can carry its own event stream type and id, source type, subject, occurred time, tags and causation alongside the source id:

using Cratis.Chronicle.Events;
using Cratis.Chronicle.EventSequences;
using Cratis.Chronicle.Reactors;
public class ExplicitMetadataReactor : IReactor
{
public EventForEventSourceId BookReserved(BookReserved @event, EventContext context) =>
new(@event.MemberId, new MemberActivityRecorded(@event.Isbn))
{
EventStreamType = new EventStreamType("members"),
Subject = new Subject(@event.MemberId.Value),
};
}

View C# snippet source on GitHub

In C#, a bare event uses the reactor’s resolved metadata from its [EventStreamType]/[EventSourceType] attributes and ICanProvide* interfaces. An EventForEventSourceId uses its own values instead; reactor metadata does not fill its unset fields. Those fields take append defaults, such as EventStreamType.All, and an omitted Subject is resolved from the event.

In C#, mix both forms in an IEnumerable<object>, object[], List<object> or IReadOnlyList<object>. Each bare event uses the reactor’s resolved metadata, including its event source id, while each EventForEventSourceId keeps its own. They append together as one transaction:

using Cratis.Chronicle.Events;
using Cratis.Chronicle.EventSequences;
using Cratis.Chronicle.Reactors;
[EventType]
public record ActivityLogged(Isbn Isbn);
public class MixedSideEffectsReactor : IReactor
{
public IEnumerable<object> BookReserved(BookReserved @event, EventContext context) =>
[
new ActivityLogged(@event.Isbn),
new EventForEventSourceId(@event.MemberId, new MemberActivityRecorded(@event.Isbn)),
];
}

View C# snippet source on GitHub

If your decision is valid only against the event-log state the reactor read, use concurrency scopes to reject an append when that state has changed. In C#, return EventsWithConcurrencyScopes to submit an ordered list of EventForEventSourceId values and its scopes through one AppendMany call:

using Cratis.Chronicle.Events;
using Cratis.Chronicle.EventSequences;
using Cratis.Chronicle.EventSequences.Concurrency;
using Cratis.Chronicle.Reactors;
[EventType]
public record ReservationConfirmed(Isbn Isbn);
public class ReservationConfirmationReactor : IReactor
{
public EventsWithConcurrencyScopes BookReserved(BookReserved @event, EventContext context) =>
new(
[new EventForEventSourceId(context.EventSourceId, new ReservationConfirmed(@event.Isbn))],
new Dictionary<EventSourceId, ConcurrencyScope>
{
[context.EventSourceId] = new(
context.SequenceNumber,
EventSourceId: context.EventSourceId),
});
}

View C# snippet source on GitHub

Here the reactor appends only if no later event for the triggering source has appeared since BookReserved. Chronicle materializes the events and copies the scope dictionary when you create the result, then submits both together. A failed constraint, concurrency check, or append fails the reactor partition; Chronicle never splits the return into partial appends.

A scope entry with ConcurrencyScope.NotSet, or a missing entry for an event source id in the batch, asks the configured concurrency strategy to resolve that source’s scope. Use ConcurrencyScope.None when you explicitly want no check for a key. Chronicle passes every other scope through unchanged.

The event list preserves the order you supplied to the append operation. That does not impose a global processing order on observers: events targeting different source partitions can be observed independently. The scope dictionary also holds one scope per EventSourceId key; it cannot represent multiple independent scopes under the same key.

In C#, the built-in result handlers derive an idempotency key from the delivery identity, the reactor’s effect epoch and each returned event’s position. On a kernel that supports idempotent appends, repeating those keys with the same output does not append another copy. This applies when recovery, catch-up or replay repeats the same delivery identity; it does not guarantee a single handler invocation.

If an EventForEventSourceId already has an IdempotencyKey, Chronicle keeps it and derives keys only for events without one. Use delivery.IdempotencyKeyFor("name") for a named effect. Keep the order of returned events stable because their positions are part of the derived keys.

A kernel that does not advertise idempotent appends receives returned events without derived keys, and Chronicle logs one warning per reactor. A key you set yourself instead throws IdempotentAppendsNotSupported; it is not silently dropped. Automatic duplicate protection therefore depends on the kernel capability.

Changed content under an existing key causes a conflict and fails the partition. Derive output from the triggering event and stable state: a fresh Guid, the current time or a changed lookup result can cause unintended conflicts. If changed output is intentional, review the effect epoch before allowing new appends. Use [OnceOnly] if replay should skip the handler; it does not repair an ordinary failed delivery.

A payment, email or webhook inside the handler is outside this protection and can run again. Use a receiver’s idempotency support or an application-owned receipt, with the transaction and failure-window handling in Delivery identity.

To exercise returned-event appends in Cratis.Chronicle.Testing, supply the real side-effect handlers to ReactorScenario. By default, the scenario records returned events instead of appending them.

In C#, set metadata on the reactor type for bare returned events. An EventForEventSourceId keeps its own metadata instead of inheriting these values.

Implement this interface to supply a custom EventSourceId for all side-effect events from this reactor:

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Reactors;
public class WarehouseEventSourceReactor(string warehouseId) : IReactor, ICanProvideEventSourceId
{
public EventSourceId GetEventSourceId() => warehouseId;
[OnceOnly]
public StockDecreased BookReserved(SideEffectsBookReserved @event, EventContext context) =>
new(@event.Isbn, 1);
}

View C# snippet source on GitHub

Implement this interface to attach a Subject (e.g. a user or principal) to appended events:

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Reactors;
public class OrderReactor(string userId) : IReactor, ICanProvideSubject
{
public Subject GetSubject() => new(userId);
}

View C# snippet source on GitHub

Implement this interface to specify a runtime EventStreamId:

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Reactors;
public class TenantReactor(string tenantId) : IReactor, ICanProvideEventStreamId
{
public EventStreamId GetEventStreamId() => tenantId;
}

View C# snippet source on GitHub

[EventStreamType] and [EventSourceType] Attributes

Section titled “[EventStreamType] and [EventSourceType] Attributes”

Apply these attributes to the reactor class for a compile-time stream or source type:

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Reactors;
[EventStreamType("warehouse")]
[EventSourceType("product")]
public class WarehouseMetadataReactor : IReactor
{
[OnceOnly]
public StockDecreased BookReserved(SideEffectsBookReserved @event, EventContext context) =>
new(@event.Isbn, 1);
}

View C# snippet source on GitHub

Metadata Priority
EventSourceId ICanProvideEventSourceId -> eventContext.EventSourceId
EventStreamId ICanProvideEventStreamId -> [EventStreamId] attribute -> null
EventStreamType [EventStreamType] attribute -> null
EventSourceType [EventSourceType] attribute -> null
Subject ICanProvideSubject -> null

In C#, register a custom IReactorSideEffectHandler to process a return type beyond the built-in event forms:

using Cratis.Chronicle;
using Cratis.Chronicle.Reactors.SideEffects;
using Cratis.Monads;
using Microsoft.Extensions.DependencyInjection;
public record MySpecialResult;
public class MyHandler : IReactorSideEffectHandler
{
public bool CanHandleReturnType(Type type) => type == typeof(MySpecialResult);
public bool CanHandle(ReactorContext reactorContext, object value) =>
value is MySpecialResult;
public bool CanHandle(ReactorContext reactorContext, IEventStore eventStore, object value) =>
CanHandle(reactorContext, value);
public Task<Result<ReactorSideEffectFailure>> Handle(
ReactorContext reactorContext,
IEventStore eventStore,
object value)
{
return Task.FromResult(Result.Success<ReactorSideEffectFailure>());
}
}
public static class ReactorSideEffectRegistration
{
public static void Add(IServiceCollection services)
{
services.AddSingleton<IReactorSideEffectHandler, MyHandler>();
}
}

View C# snippet source on GitHub

Chronicle registers its built-in handlers and reactor metadata providers when you call AddCratisChronicle, including in standalone hosts. Register custom handlers under IReactorSideEffectHandler or their concrete type in the host’s service collection. Handlers discovered from other loaded libraries only participate when registered; merely loading an assembly does not activate its integration.

To return your custom side effect synchronously, implement CanHandleReturnType(Type) on the handler to claim its declared type. Mark the return type with [ReactorSideEffect] from Cratis.Chronicle.Reactors.SideEffects so analyzer CHR0054 accepts it. The marker may be applied to classes, structs, or interfaces; types deriving from a marked base class or implementing a marked interface are also accepted. It only informs the analyzer: it does not register a handler or make the type supported at runtime.

Existing handlers default to false and can still handle asynchronous Task<T> results without a marker. A handler can also claim a declared IEnumerable<T> return type; it must process the collection at invocation time. Arrays and IEnumerable<T> implementations of marked types are accepted by the analyzer, but the handler must claim the declared collection type, not only its elements. Returning a type that no handler claims synchronously is rejected during registration.

In C#, the IEnumerable<T> entries below also accept T[], List<T>, and other types implementing IEnumerable<T> (such as IReadOnlyList<T>), including when wrapped in Task<TSequence>. Multidimensional arrays are not supported.

Return type Handler invoked
TEvent EventResultHandler — appends single event to the triggering/reactor event source id
Task<TEvent> EventResultHandler
IEnumerable<TEvent> EventsResultHandler — appends each event
Task<IEnumerable<TEvent>> EventsResultHandler
EventForEventSourceId EventForEventSourceIdResultHandler — appends to the event source id carried by the value
Task<EventForEventSourceId> EventForEventSourceIdResultHandler
IEnumerable<EventForEventSourceId> EventsForEventSourceIdResultHandler — appends all as one transaction
Task<IEnumerable<EventForEventSourceId>> EventsForEventSourceIdResultHandler
EventsWithConcurrencyScopes EventsWithConcurrencyScopesResultHandler — appends its ordered events and scopes as one transaction
Task<EventsWithConcurrencyScopes> EventsWithConcurrencyScopesResultHandler
IEnumerable<object> mixing events and EventForEventSourceId MixedSideEffectsResultHandler — bare events use reactor metadata, each EventForEventSourceId keeps its own; all appended as one transaction
Custom T or IEnumerable<T> claimed by a registered handler The claiming IReactorSideEffectHandler processes the return value
void / Task No side effects appended

If a returned-event append fails, Chronicle marks the reactor partition as failed. In C#, a non-null return value that no side-effect handler claims also fails the partition instead of being discarded and acknowledged. Register a handler for that type, or return a supported event, before recovering the partition. Check Delivery identity first if the handler also makes an external call: recovery can invoke it again.