Cratis Chronicle reactors — handle events in batches
A batch method handles the matching events from a page of Cratis Chronicle events in one call. Use it when a downstream system accepts bulk work, such as updating a search index with one request instead of a request per event. You can still report failures or delayed retries for individual partitions.
A page is a delivery containing events for one or more partitions, each identified by an event source id. A batch method receives only the event types it observes, in sequence order, and runs once for a page that contains matching events. Per-event methods continue to run once per event, partition by partition.
using Cratis.Chronicle.Events;using Cratis.Chronicle.Observation;using Cratis.Chronicle.Reactors;
[EventType]public record UserRegistered(string Name);
[EventType]public record UserRenamed(string NewName);
[EventType]public record UserEmailChanged(string Email);
public record UserDocument(EventSourceId Id, string Name);
public record BulkUpsertFailure(EventSourceId EventSourceId, Exception Exception);
public record BulkUpsertThrottled(EventSourceId EventSourceId, TimeSpan RetryAfter);
public record BulkUpsertResponse(IEnumerable<BulkUpsertFailure> Failures, IEnumerable<BulkUpsertThrottled> Throttled);
public class UnknownUserEvent(object @event) : Exception($"Unknown user event: {@event}");
public interface ISearchIndex{ Task<BulkUpsertResponse> BulkUpsert(IEnumerable<UserDocument> documents, CancellationToken cancellationToken);}
public interface IEmailConfirmations{ Task Send(EventSourceId accountId, string email);}
public class Users(ISearchIndex index, IEmailConfirmations confirmations) : IReactor{ [Observes<UserRegistered>] [Observes<UserRenamed>] public async Task Index(EventBatch batch, BatchContext context) { var documents = batch.Select(e => e.Event switch { UserRegistered registered => new UserDocument(e.Context.EventSourceId, registered.Name), UserRenamed renamed => new UserDocument(e.Context.EventSourceId, renamed.NewName), _ => throw new UnknownUserEvent(e.Event) });
var response = await index.BulkUpsert(documents, context.CancellationToken);
foreach (var failure in response.Failures) { batch.Fail(failure.EventSourceId, failure.Exception); }
foreach (var throttled in response.Throttled) { batch.Defer(throttled.EventSourceId, throttled.RetryAfter); } }
public Task EmailChanged(UserEmailChanged @event, EventContext context) => confirmations.Send(context.EventSourceId, @event.Email);}import io.cratis.chronicle.events.EventContextimport io.cratis.chronicle.events.EventTypeimport io.cratis.chronicle.observation.BatchContextimport io.cratis.chronicle.observation.EventBatchimport io.cratis.chronicle.observation.Observesimport io.cratis.chronicle.observation.Reactorimport java.time.Duration
@EventTypedata class BatchUserRegistered(val name: String)
@EventTypedata class BatchUserRenamed(val newName: String)
@EventTypedata class BatchUserEmailChanged(val email: String)
data class BatchUserDocument(val id: String, val name: String)
data class BatchUpsertFailure(val eventSourceId: String, val error: Exception)
data class BatchUpsertThrottled(val eventSourceId: String, val retryAfter: Duration)
data class BatchUpsertResponse(val failures: List<BatchUpsertFailure>, val throttled: List<BatchUpsertThrottled>)
interface BatchSearchIndex { suspend fun bulkUpsert(documents: List<BatchUserDocument>): BatchUpsertResponse}
interface BatchEmailConfirmations { suspend fun send(accountId: String, email: String)}
@Reactorclass BatchUsers(private val index: BatchSearchIndex, private val confirmations: BatchEmailConfirmations) { @Observes(BatchUserRegistered::class) @Observes(BatchUserRenamed::class) suspend fun index(batch: EventBatch, context: BatchContext) { val documents = batch.map { e -> when (val event = e.event) { is BatchUserRegistered -> BatchUserDocument(e.context.eventSourceId, event.name) is BatchUserRenamed -> BatchUserDocument(e.context.eventSourceId, event.newName) else -> error("Unknown user event: $event") } }
val response = index.bulkUpsert(documents) response.failures.forEach { batch.fail(it.eventSourceId, it.error) } response.throttled.forEach { batch.defer(it.eventSourceId, it.retryAfter) } }
suspend fun emailChanged(event: BatchUserEmailChanged, context: EventContext) = confirmations.send(context.eventSourceId, event.email)}import io.cratis.chronicle.events.EventContext;import io.cratis.chronicle.events.EventType;import io.cratis.chronicle.observation.BatchContext;import io.cratis.chronicle.observation.EventAndContext;import io.cratis.chronicle.observation.EventBatch;import io.cratis.chronicle.observation.Observes;import io.cratis.chronicle.observation.Reactor;import java.time.Duration;import java.util.ArrayList;import java.util.List;
@EventTyperecord BatchUserRegistered(String name) {}
@EventTyperecord BatchUserRenamed(String newName) {}
@EventTyperecord BatchUserEmailChanged(String email) {}
record BatchUserDocument(String id, String name) {}
record BatchUpsertFailure(String eventSourceId, Exception error) {}
record BatchUpsertThrottled(String eventSourceId, Duration retryAfter) {}
record BatchUpsertResponse(List<BatchUpsertFailure> failures, List<BatchUpsertThrottled> throttled) {}
interface BatchSearchIndex { BatchUpsertResponse bulkUpsert(List<BatchUserDocument> documents);}
interface BatchEmailConfirmations { void send(String accountId, String email);}
@Reactorclass BatchUsers { private final BatchSearchIndex index; private final BatchEmailConfirmations confirmations;
BatchUsers(BatchSearchIndex index, BatchEmailConfirmations confirmations) { this.index = index; this.confirmations = confirmations; }
@Observes(BatchUserRegistered.class) @Observes(BatchUserRenamed.class) public void index(EventBatch batch, BatchContext context) { List<BatchUserDocument> documents = new ArrayList<>(); for (EventAndContext e : batch) { String id = e.getContext().getEventSourceId(); if (e.getEvent() instanceof BatchUserRegistered registered) { documents.add(new BatchUserDocument(id, registered.name())); } else if (e.getEvent() instanceof BatchUserRenamed renamed) { documents.add(new BatchUserDocument(id, renamed.newName())); } }
BatchUpsertResponse response = index.bulkUpsert(documents); response.failures().forEach(failure -> batch.fail(failure.eventSourceId(), failure.error())); response.throttled().forEach(throttled -> batch.defer(throttled.eventSourceId(), throttled.retryAfter())); }
public void emailChanged(BatchUserEmailChanged event, EventContext context) { confirmations.send(context.getEventSourceId(), event.email()); }}defmodule BatchUserRegistered do use Chronicle.Events.EventType, id: "batch-user-registered"
defstruct name: ""end
defmodule BatchUserRemoved do use Chronicle.Events.EventType, id: "batch-user-removed"
defstruct name: ""end
defmodule BatchUserEmailChanged do use Chronicle.Events.EventType, id: "batch-user-email-changed"
defstruct email: ""end
defmodule BatchUsersReactor do use Chronicle.Reactors.Reactor
alias Chronicle.Observers.EventBatch
# One call per page, with every BatchUserRegistered and BatchUserRemoved in it. @observes BatchUserRegistered @observes BatchUserRemoved def index(batch, _context) do operations = Enum.map(batch, fn {%BatchUserRegistered{name: name}, context} -> {:upsert, context.event_source_id, name} {%BatchUserRemoved{}, context} -> {:delete, context.event_source_id} end)
{failed, throttled} = bulk_index(operations)
batch = Enum.reduce(failed, batch, &EventBatch.fail(&2, &1, :index_failed)) Enum.reduce(throttled, batch, &EventBatch.defer(&2, &1, 5_000)) end
# A per-event handler for a type no batch function observes. @handles BatchUserEmailChanged
@impl true def handle(%BatchUserEmailChanged{}, _context), do: :ok
# Send the operations to the search index; return the event source ids that failed and the # ones the index asked to retry later. defp bulk_index(_operations), do: {[], []}end// Copyright (c) Cratis. All rights reserved.// Licensed under the MIT license. See LICENSE file in the project root for full license information.
import { BatchContext, EventBatch, EventContext, eventType, observes, reactor } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()class UserRegistered { @field(String) readonly name: string;
constructor(name: string = '') { this.name = name; }}
@eventType()class UserRenamed { @field(String) readonly newName: string;
constructor(newName: string = '') { this.newName = newName; }}
@eventType()class UserEmailChanged { @field(String) readonly email: string;
constructor(email: string = '') { this.email = email; }}
interface UserDocument { readonly id: string; readonly name: string;}
interface BulkUpsertResponse { readonly failures: readonly { readonly eventSourceId: string; readonly error: Error }[]; readonly throttled: readonly { readonly eventSourceId: string; readonly retryAfterMilliseconds: number }[];}
interface ISearchIndex { bulkUpsert(documents: readonly UserDocument[], signal: AbortSignal): Promise<BulkUpsertResponse>;}
interface IEmailConfirmations { send(accountId: string, email: string): Promise<void>;}
@reactor('users')class Users { constructor(private readonly index: ISearchIndex, private readonly confirmations: IEmailConfirmations) {}
@observes(UserRegistered) @observes(UserRenamed) async indexUsers(batch: EventBatch, context: BatchContext): Promise<void> { const documents = batch.events.map(entry => { if (entry.is(UserRegistered)) return { id: entry.context.eventSourceId, name: entry.event.name }; if (entry.is(UserRenamed)) return { id: entry.context.eventSourceId, name: entry.event.newName }; throw new Error(`Unknown user event: ${entry.context.eventType.id.value}`); });
const response = await this.index.bulkUpsert(documents, context.signal);
for (const failure of response.failures) { batch.fail(failure.eventSourceId, failure.error); }
for (const throttled of response.throttled) { batch.defer(throttled.eventSourceId, throttled.retryAfterMilliseconds); } }
async userEmailChanged(event: UserEmailChanged, context: EventContext): Promise<void> { await this.confirmations.send(context.eventSourceId, event.email); }}The methods named after an event type, such as userEmailChanged, stay per-event handlers. A method with
@observes is a batch method, and an event type reaches exactly one of them. Events in a batch carry their JSON
content; use entry.is(EventType) or batch.ofType(EventType) to narrow them. Construct the reactor with its
dependencies through your client artifact activator.
Here, Index receives UserRegistered and UserRenamed events together, while EmailChanged remains a per-event method. The bulk response identifies partitions that failed or need more time; Fail and Defer let the rest of the page succeed.
Declaring a batch method
Section titled “Declaring a batch method”A batch method takes an EventBatch as its first parameter and declares each event type it observes with
[Observes<TEvent>], once per type. It may also take a BatchContext, a CancellationToken, and services from the
service provider. The CancellationToken can be declared optional, as CancellationToken cancellationToken = default;
no other parameter can. Inside, pattern-match on the events.
Each event type assigned to a batch method must belong to that method alone. The analyzers in Cratis.Chronicle.CodeAnalysis report each of these mistakes when you build, and Chronicle refuses to register a reactor that has one:
| Mistake | Rule |
|---|---|
A method with [Observes<TEvent>] does not take an EventBatch |
CHR0070 |
A batch method has no [Observes<TEvent>] |
CHR0071 |
| An event type is observed by two batch methods, or by a batch method and a per-event method | CHR0072 |
A per-event method takes a BatchContext |
CHR0073 |
A batch method returns anything but Task or void |
CHR0074 |
A batch method takes a parameter Chronicle cannot supply, such as an EventContext |
CHR0076 |
A batch method can only receive the event types it observes, so a pattern on any other event type never matches. CHR0077 warns about such a pattern, which usually means an [Observes<TEvent>] is missing.
Returning events from a batch method is not supported. If the batch must produce events, append them through an event log supplied as a dependency.
Page size
Section titled “Page size”Chronicle decides when to send a page; the reactor’s bounds decide how big it can be. Declare them with [BatchSize] on the reactor:
using Cratis.Chronicle.Events;using Cratis.Chronicle.Observation;using Cratis.Chronicle.Reactors;
[EventType]public record ProductListed(string Name);
public interface IProductSearch{ Task Index(IEnumerable<string> names, CancellationToken cancellationToken);}
[BatchSize(MaxEvents = 50, MaxBytes = 1_048_576)]public class ProductSearchIndexer(IProductSearch search) : IReactor{ [Observes<ProductListed>] public Task Index(EventBatch batch, BatchContext context) => search.Index(batch.Select(e => ((ProductListed)e.Event).Name), context.CancellationToken);}| Property | Meaning | Default |
|---|---|---|
MaxEvents |
The most events in one page | 500 for a reactor with a batch method, 100 for a reactor with only per-event methods |
MaxBytes |
The most bytes of event content in one page, counted as the UTF-8 length of each event’s JSON content | 0, so the kernel’s maximum applies |
MaxDelayMilliseconds |
How long the kernel may wait to fill a live page. Accepted, but not applied yet | 0 |
The kernel honors MaxEvents and MaxBytes on every path: live, catch-up, replay and retry. It caps them with its own page maximums, maxEventsPerPage (1 000 by default) and maxBytesPerSubscriberCall (4 MiB by default), and a bound of zero takes the kernel’s maximum. A page is never larger than what the path hands over: during catch-up, replay and retry that is maxEventsPerSubscriberCall events (100 by default), so a declared bound above it takes effect there only once you raise it; see page bounds. An event larger than MaxBytes is sent alone in its own page, so it never stalls its partition.
The kernel does not yet apply MaxDelayMilliseconds: a live page holds what is already waiting, so under light load it holds one event. Chronicle refuses to register a reactor with a negative bound.
Each method sees its events in sequence order, and so in order within each partition. Two methods of the same reactor are not ordered relative to each other, even for the same partition. When two side effects must happen in a particular order, handle them in the same method.
The batch context
Section titled “The batch context”BatchContext describes the whole page, even when a method’s EventBatch contains only some of its events. It includes the observer, event store, namespace, event sequence, partitions, event count, and first and last sequence numbers. It also supplies a cancellation token and the deadline until which the kernel waits; a null deadline means it waits without a deadline.
Origin explains why Chronicle delivered the page:
| Origin | Meaning |
|---|---|
Live |
The events were appended now and delivered to an observer that is up to date |
CatchUp |
The events were read from storage for an observer that is behind |
Replay |
The events were read from storage for an observer that was rewound |
Retry |
The events were read from storage to recover a failed or deferred partition |
Reporting outcomes
Section titled “Reporting outcomes”Return normally without reporting a problem to mark every partition in the batch as successful. Throwing an exception fails every partition in that batch at its first event in the batch. Those partitions enter the normal failed partition recovery process.
For a partial result, report the affected partition on EventBatch:
| Call | Result |
|---|---|
Fail(partition, exception) |
Fails that partition from its first event in the batch |
Fail(eventContext, exception) |
Fails that event’s partition from that event; earlier events count as handled |
Defer(partition, retryAfter) |
Delivers that partition again from its first event in the batch after the delay |
Defer(eventContext, retryAfter) |
Delivers that event’s partition again from that event after the delay |
A deferral does not count as a failure toward quarantine. Use it when a downstream system asks you to back off. A kernel that does not deliver pages cannot defer a partition; the client fails the partition instead and says why.
When several methods report a problem for the same partition, Chronicle retries from the earliest event any of them reported. That can deliver events another method already handled. Keep side effects idempotent, meaning that repeating the same work does not repeat its effect, and use the delivery identity to recognize a redelivery.
Testing a batch reactor
Section titled “Testing a batch reactor”ReactorScenario from Cratis.Chronicle.Testing runs batch methods. The events of one Events(...) call reach each batch method as one live page; Given.Page(...) delivers events for several event sources as one page, in the order given. Per-event methods still receive the events no batch method observes, one at a time.
using Cratis.Chronicle.Events;using Cratis.Chronicle.Observation;using Cratis.Chronicle.Reactors;using Cratis.Chronicle.Testing.Reactors;using Cratis.Specifications;using Microsoft.Extensions.DependencyInjection;using NSubstitute;using Xunit;
[EventType]public record ParcelShipped(string TrackingNumber);
public class CarrierRejected(string trackingNumber) : Exception($"The carrier rejected parcel '{trackingNumber}'");
public interface ICarrier{ Task<IEnumerable<string>> Register(IEnumerable<string> trackingNumbers);}
public class ParcelTracking(ICarrier carrier) : IReactor{ [Observes<ParcelShipped>] public async Task Register(EventBatch batch, BatchContext context) { var rejected = await carrier.Register(batch.Select(e => ((ParcelShipped)e.Event).TrackingNumber)); foreach (var e in batch.Where(e => rejected.Contains(((ParcelShipped)e.Event).TrackingNumber))) { batch.Fail(e.Context, new CarrierRejected(((ParcelShipped)e.Event).TrackingNumber)); } }}
public class when_the_carrier_rejects_one_parcel : Specification{ readonly EventSourceId _accepted = EventSourceId.New(); readonly EventSourceId _rejected = EventSourceId.New(); readonly ICarrier _carrier = Substitute.For<ICarrier>(); ReactorScenario<ParcelTracking> _scenario = null!;
void Establish() { _carrier.Register(Arg.Any<IEnumerable<string>>()).Returns(["TRACK-2"]); _scenario = new(services => services.AddSingleton(_carrier)); }
Task Because() => _scenario.Given.Page( new(_accepted, new ParcelShipped("TRACK-1")), new(_rejected, new ParcelShipped("TRACK-2")));
[Fact] void should_register_both_parcels_in_one_call() => _carrier.Received(1).Register(Arg.Any<IEnumerable<string>>()); [Fact] void should_fail_the_rejected_parcel() => _scenario.ShouldHaveFailed(_rejected); [Fact] void should_fail_nothing_else() => _scenario.PartitionOutcomes.Count.ShouldEqual(1);}import { BatchContext, EventBatch, eventType, observes, reactor } from '@cratis/chronicle';import { ReactorScenario } from '@cratis/chronicle/testing';import { field } from '@cratis/fundamentals';
@eventType('parcel-shipped')class ParcelShipped { @field(String) readonly trackingNumber: string;
constructor(trackingNumber: string = '') { this.trackingNumber = trackingNumber; }}
const registered: string[][] = [];
@reactor('parcel-tracking')class ParcelTracking { @observes(ParcelShipped) async register(batch: EventBatch, _context: BatchContext): Promise<void> { const shipped = batch.ofType(ParcelShipped); registered.push(shipped.map(parcel => parcel.event.trackingNumber)); for (const parcel of shipped.filter(parcel => parcel.event.trackingNumber === 'TRACK-2')) { batch.fail(parcel.context, new Error(`The carrier rejected parcel '${parcel.event.trackingNumber}'`)); } }}
const parcelScenario = new ReactorScenario(ParcelTracking, { artifacts: { eventTypes: [ParcelShipped] }, constraints: 'disabled' });await parcelScenario.given.page( { eventSourceId: 'parcel-1', event: new ParcelShipped('TRACK-1') }, { eventSourceId: 'parcel-2', event: new ParcelShipped('TRACK-2') });
// Both parcels reached the batch method in one call: registered is [['TRACK-1', 'TRACK-2']].parcelScenario.shouldHaveFailed('parcel-2');// partitionOutcomes holds only the failed parcel.Partitions a batch method reports with Fail or Defer are listed in PartitionOutcomes, and ShouldHaveFailed and ShouldHaveDeferred assert on them. A batch method that throws fails its whole batch, and the scenario throws that exception from the call that delivered the events. For more on scenarios, see testing reactors.