Skip to content

Returning Side Effects from Reactor Handler Methods

Reactor handler methods can return side-effect events directly instead of taking a dependency on IEventLog. The framework automatically appends the returned events to the correct sequence after the handler completes.

Important: Side-effect appends are not fire-and-forget. If a returned event fails to append — a constraint violation, a concurrency conflict, or an error — the reactor’s partition fails with the failure details and is retried per the observer’s retry policy. Failures never pass silently. See Error handling.

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

The returned event is appended to the event log using the EventSourceId from the incoming EventContext. No IEventLog injection required.

The handlers are marked [OnceOnly] because a returned event is a new fact: without it, replaying the reactor appends the same follow-up event again. Analyzer CHR0022 reports an event-returning handler that is not marked. [OnceOnly] does not cover a retry after the handler failed; 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

Everything above lands the returned event on the triggering event’s EventSourceId — optionally redirected once for the whole reactor via ICanProvideEventSourceId. That covers most reactors. But automation and translation reactors often need to write to a different entity than the one that triggered them — or to several at once.

Picture a library. A member reserves a book, and that reservation is a fact about 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

When it happens you want to record activity on the member — a different event source altogether. Return an EventForEventSourceId and pick the target EventSourceId yourself:

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 that triggered the reactor — so it shows up on the member’s stream, ready for a member-activity projection to pick up.

A single reservation usually ripples to more than one entity: the member gains activity, and the book loses stock. In C#, return IEnumerable<EventForEventSourceId>, EventForEventSourceId[], List<EventForEventSourceId>, or IReadOnlyList<EventForEventSourceId> to fan out to several event source ids in one go — they are appended 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 is self-describing: alongside the source id it carries the event stream type and id, source type, subject, occurred time, tags and causation. Set only the ones you need — the rest fall back to sensible defaults:

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

Two modes: a bare event uses the reactor’s resolved metadata — its [EventStreamType]/[EventSourceType] attributes and ICanProvide* interfaces. An EventForEventSourceId is the explicit mode: it is self-describing and uses only the values on it, so the reactor’s metadata does not apply (an unset field takes the append default such as EventStreamType.All, and an omitted Subject is resolved from the event). Reach for a bare event when you want “use my reactor’s config”, and an EventForEventSourceId when you want “I’ll specify exactly where and how”.

In C#, you can also mix the two in a single IEnumerable<object>, object[], List<object>, or IReadOnlyList<object> return — each bare event uses the reactor’s resolved metadata and the triggering event source id, while each EventForEventSourceId keeps its own. They are appended 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

Returning events is convenient, but sometimes the decision is only valid against the exact event-log state the reactor read. Return EventsWithConcurrencyScopes to submit an ordered list of EventForEventSourceId values and its concurrency 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 append each returned event with an idempotency key that Chronicle derives from the delivery identity, the reactor’s effect epoch and the event’s position in the returned value. When the same delivery comes back, the kernel recognizes the keys and does not append the events a second time. This covers redelivery after a failed partition recovers, catch-up and replay: a returned event lands once per delivery.

What this does not cover is anything outside the event log. A payment call, an email or a webhook made inside the handler still runs again on every redelivery. Guard those with a receipt keyed by ReactorDelivery, as described in Delivery identity.

  • A key you set yourself is kept. If an EventForEventSourceId already carries an IdempotencyKey, Chronicle leaves it alone and keys only the events that have none. Use delivery.IdempotencyKeyFor("name") to derive a stable key for a named effect.
  • Older kernels append unkeyed. Against a kernel that does not advertise idempotent appends, returned events are appended without keys and Chronicle logs one warning per reactor. A key you set yourself on such a kernel throws IdempotentAppendsNotSupported, because silently dropping it would remove the protection you asked for.
  • The in-process testing package advertises the capability. ReactorScenario records returned events by default instead of appending them. When you give it the real side-effect handlers, Cratis.Chronicle.Testing appends them with keys, like a current kernel does, so redelivering an occurrence does not append the events again.
  • Changed output is refused, not overwritten. If the handler returns something different for a delivery that was already appended, the kernel reports a conflict and the partition fails. The failure message names the remedy: raise the effect epoch or mark the handler [OnceOnly].
  • Build returned events from stable inputs. Derive the returned events from the triggering event and from state that does not change between deliveries. A payload carrying a fresh Guid, the current time or the result of a lookup that has since changed counts as changed output when the delivery comes back, so the partition fails instead of appending a duplicate. Take such values from the triggering event, or derive them from the delivery identity.

Set metadata once on the reactor type so every returned event inherits it automatically.

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

MetadataPriority
EventSourceIdICanProvideEventSourceId -> eventContext.EventSourceId
EventStreamIdICanProvideEventStreamId -> [EventStreamId] attribute -> null
EventStreamType[EventStreamType] attribute -> null
EventSourceType[EventSourceType] attribute -> null
SubjectICanProvideSubject -> null

Extend the pipeline by registering a custom IReactorSideEffectHandler:

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 typeHandler invoked
TEventEventResultHandler — appends single event to the triggering/reactor event source id
Task<TEvent>EventResultHandler
IEnumerable<TEvent>EventsResultHandler — appends each event
Task<IEnumerable<TEvent>>EventsResultHandler
EventForEventSourceIdEventForEventSourceIdResultHandler — 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
EventsWithConcurrencyScopesEventsWithConcurrencyScopesResultHandler — appends its ordered events and scopes as one transaction
Task<EventsWithConcurrencyScopes>EventsWithConcurrencyScopesResultHandler
IEnumerable<object> mixing events and EventForEventSourceIdMixedSideEffectsResultHandler — bare events use reactor metadata, each EventForEventSourceId keeps its own; all appended as one transaction
Custom T or IEnumerable<T> claimed by a registered handlerThe claiming IReactorSideEffectHandler processes the return value
void / TaskNo side effects appended

If a side-effect append fails, Chronicle marks the reactor partition as failed. 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 the returned type (or return a supported event), then retry or rewind the observer to continue processing.