Skip to content

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);
}

View C# snippet source on GitHub

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.

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.

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);
}

View C# snippet source on GitHub

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.

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

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.

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);
}

View C# snippet source on GitHub

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.