Repository navigation
Getting Started
This guide walks you through installing the packages and wiring up a complete event sourcing stack — from handling your first command to projecting events into a read model.
Install the core package and a storage integration. Pick either KurrentDB or MSSP.
dotnet add package Aggregates
dotnet add package Aggregates.MSSP # or Aggregates.KurrentDB
For sagas, policies, or projections add the matching extension packages:
dotnet add package Aggregates.Sagas
dotnet add package Aggregates.Sagas.MSSP # or Aggregates.Sagas.KurrentDB
dotnet add package Aggregates.Policies
dotnet add package Aggregates.Policies.MSSP
dotnet add package Aggregates.Projections
dotnet add package Aggregates.Projections.MSSP
dotnet add package Aggregates.Projections.Sql # optional: SQL commit helper (plus your ADO.NET provider)
dotnet add package Aggregates.Analyzers # optional: reports events without [EventContract]
Implement IState<TState, TEvent> on your state object. Initial is the empty starting state. Apply is a pure function that produces the next state from the current one and an event.
record ShoppingCartState(ImmutableDictionary<string, int> Items)
: IState<ShoppingCartState, IShoppingCartEvent> {
public static ShoppingCartState Initial =>
new(ImmutableDictionary<string, int>.Empty);
public ShoppingCartState Apply(IShoppingCartEvent @event) => @event switch {
ItemAdded e => this with { Items = Items.SetItem(e.ItemId,
Items.GetValueOrDefault(e.ItemId) + e.Quantity) },
ItemRemoved e => this with { Items = Items.SetItem(e.ItemId,
Items[e.ItemId] - e.Quantity) },
_ => this
};
}Events are plain records. Decorate them with [EventContract] to control the stored type name and enable schema evolution:
[EventContract("ItemAdded", namespace: "ShoppingCart")]
record ItemAdded(string ItemId, int Quantity) : IShoppingCartEvent;
[EventContract("ItemRemoved", namespace: "ShoppingCart")]
record ItemRemoved(string ItemId, int Quantity) : IShoppingCartEvent;The stored type name becomes ShoppingCart.ItemAdded@v1. Omitting the attribute causes the library to fall back to the .NET type name.
Implement ICommand<TState, TEvent>. The Id property identifies the target aggregate. ProgressAsync validates the state and yields the resulting events:
record AddItem(AggregateIdentifier Id, string ItemId, int Quantity)
: ICommand<ShoppingCartState, IShoppingCartEvent> {
public async IAsyncEnumerable<IShoppingCartEvent> ProgressAsync(
ShoppingCartState state,
[EnumeratorCancellation] CancellationToken cancellationToken = default) {
if (Quantity <= 0) throw new ArgumentOutOfRangeException(nameof(Quantity));
yield return new ItemAdded(ItemId, Quantity);
}
}Inject ICommandHandler<TCommand> wherever you need it. The library auto-registers a handler for each command discovered by ScanAssemblies:
class ShoppingCartController(ICommandHandler<AddItem> handler) : ControllerBase {
[HttpPost("{id:guid}")]
public async Task<IActionResult> Post(Guid id, [FromBody] AddItemRequest req, CancellationToken ct) {
await handler.HandleAsync(new AddItem(id.ToString(), req.ItemId, req.Quantity), ct);
return Ok();
}
}To register an explicit set of commands instead of everything in an assembly, use ScanTypes(typeof(AddItem), typeof(RemoveItem)). AddSagas, AddPolicies and AddProjections offer the same choice.
Use EventTypeRegistry to translate between CLR types and the stable event names stored in the event store. Build it once at startup by scanning the assembly (or assemblies) that contain your event records:
var registry = EventTypeRegistry.FromAssemblies(typeof(ItemAdded).Assembly);Then pass it to the storage integration options:
// MSSP
services
.AddAggregates(o => o.ScanAssemblies(typeof(AddItem).Assembly))
.AddMssp(o => {
o.Serialize = evt => new EventData(
registry.GetTypeName(evt),
JsonSerializer.SerializeToUtf8Bytes(evt, evt.GetType()));
o.Deserialize = (typeName, data) =>
registry.TryGetType(typeName, out var clrType)
? JsonSerializer.Deserialize(data.Span, clrType)
: null;
});
// KurrentDB
services
.AddAggregates(o => o.ScanAssemblies(typeof(AddItem).Assembly))
.AddKurrentDb(o => {
o.Serialize = evt => new SerializedEvent(
registry.GetTypeName(evt),
JsonSerializer.SerializeToUtf8Bytes(evt, evt.GetType()));
o.Deserialize = (typeName, data) =>
registry.TryGetType(typeName, out var clrType)
? JsonSerializer.Deserialize(data.Span, clrType)
: null;
});AddMssp / AddKurrentDb use the IMsspClient / KurrentDBClient from the container, so register that client too. For an embedded MSSP store in the same process (package MSSP.Engine):
using MSSP.Engine;
services.AddMssp(o => o.DataDirectory = "./mssp-data");The order of the registrations doesn't matter: the embedded store opens before any projection, policy or saga starts, and closes after the last one has stopped. For a remote MSSP server or a cluster, see the MSSP wiki.
TryGetType returns false for unknown type names — events from another service, or event types that have been removed. The null returned from the Deserialize delegate signals the infrastructure to skip that event.
Also register the registry in the container. Sagas, policies and projections then receive only the event types they handle: the event store filters the rest out before they are sent or deserialised.
services.AddSingleton(registry);Without it, every subscription reads and deserialises every event in the store. See Event-type filter.
When an event's shape changes, add a new version and an upgrader from the old one:
- Rename the current version to
…V{n}. Its contract, the name and version in[EventContract], stays as it is: that is what the store holds. - Put
eventUpgrader: typeof(…V{n}ToV{n+1})on it, and write that upgrader. - Add the new version under the original class name, with
version: n + 1.
// Old version (v1): still in the event store, upgraded when read
[EventContract("ItemAdded", version: 1, eventUpgrader: typeof(ItemAddedV1ToV2), @namespace: "ShoppingCart")]
record ItemAddedV1(string ItemId, int Quantity);
class ItemAddedV1ToV2 : IUpgradeEvent<ItemAddedV1, ItemAdded> {
public ItemAdded Upgrade(ItemAddedV1 old) =>
new(old.ItemId, old.Quantity, Unit: "pcs"); // new field with default
}
// Current version (v2)
[EventContract("ItemAdded", version: 2, @namespace: "ShoppingCart")]
record ItemAdded(string ItemId, int Quantity, string Unit) : IShoppingCartEvent;The upgrader sits on the version it upgrades from. Keep the old version in the EventTypeRegistry, so that Deserialize still knows ShoppingCart.ItemAdded@v1.
The storage integration upgrades every event its Deserialize returns: the upgrader on the event's type, then the one on the result's type, until a type has none. Repositories, projections, policies and sagas therefore only see ItemAdded. A v3 later gets an upgrader on ItemAddedV2, and a v1 event goes through both.
Building the EventTypeRegistry checks every upgrader: it must implement IUpgradeEvent<TOld, TNew> once, with TOld the type it sits on. Otherwise the registry throws at startup and lists each misconfigured upgrader.
A saga is a stateful process manager. It persists its own state in the event store and reacts to events by dispatching commands.
Same IState<TSagaState, TEvent> pattern as aggregates:
record OrderFulfillmentState(bool IsShipped)
: IState<OrderFulfillmentState, IOrderEvent> {
public static OrderFulfillmentState Initial => new(false);
public OrderFulfillmentState Apply(IOrderEvent @event) => @event switch {
OrderShipped => this with { IsShipped = true },
_ => this
};
}[SagaContract("OrderFulfillment", @namespace: "Orders")]
class OrderFulfillmentSaga : ISaga<OrderFulfillmentState, IOrderEvent> {
public IEnumerable<AggregateIdentifier> Correlate(IOrderEvent @event, EventMetadata metadata) =>
[new AggregateIdentifier($"order-fulfillment-{@event.OrderId}")];
public async IAsyncEnumerable<ICommand> ReactAsync(
OrderFulfillmentState state,
IOrderEvent @event,
[EnumeratorCancellation] CancellationToken cancellationToken = default) {
if (@event is OrderPlaced placed && !state.IsShipped)
yield return new ShipOrder(placed.OrderId);
}
}Correlate maps an incoming event to the saga instance(s) that handle it. The ids it returns are the names of their saga streams, so give each saga its own prefix: two sagas that return the same id share a stream. Return [] when no instance reacts to the event. Correlate is called once per event, on a saga resolved from a fresh DI scope, so it can use the saga's constructor dependencies. Derive the ids from the event and its metadata only, so that a redelivered or replayed event reaches the same instances. When the ids are carried in metadata rather than in the event:
public IEnumerable<AggregateIdentifier> Correlate(IOrderEvent @event, EventMetadata metadata) =>
metadata.TryGetValue("OrderFulfillmentId", out var value) && value is object?[] ids
? ids.OfType<string>().Select(id => new AggregateIdentifier(id))
: [];state is the saga's state before the event; the event is applied afterwards. A saga that collects events and acts on the last one (and resets its state there) therefore still sees what it collected. For the state after the event, use state.Apply(@event).
[SagaContract] assigns a stable identity to the saga's subscription: it names its checkpoint. The saga's state streams are named by the ids Correlate returns. Use startFromEnd: true to skip existing history on first run. A new contract version continues from the previous version's checkpoint; see Where a subscription starts.
services
.AddAggregates(o => o.ScanAssemblies(typeof(ShipOrder).Assembly))
.AddMssp(o => { /* serialization */ });
services
.AddAggregates()
.AddSagas(o => o.ScanAssemblies(typeof(OrderFulfillmentSaga).Assembly))
.AddMssp();Every saga in the scanned assemblies gets a subscription. To run only some of them in a host, use ScanTypes(typeof(OrderFulfillmentSaga), ...) instead.
A saga can defer a command with command.DeferUntil(due). Here, an order that must be paid within three days of being placed. If it isn't, it is cancelled:
[SagaContract("OrderPaymentDeadline", @namespace: "Sales")]
class OrderPaymentDeadlineSaga(SalesClock clock) : ISaga<OrderPaymentDeadlineState, IOrderEvent> {
public IEnumerable<AggregateIdentifier> Correlate(IOrderEvent @event, EventMetadata metadata) =>
[new AggregateIdentifier($"order-payment-deadline-{@event.OrderId}")];
public async IAsyncEnumerable<ICommand> ReactAsync(
OrderPaymentDeadlineState state,
IOrderEvent @event,
[EnumeratorCancellation] CancellationToken cancellationToken = default) {
if (@event is OrderPlaced placed) {
var deadline = placed.PlacedOn.AddDays(3);
yield return new CancelUnpaidOrder(placed.OrderId, deadline).DeferUntil(clock.StartOfDay(deadline));
}
}
}When the due time has passed, the command runs like any other. It can be stale by then: the order was paid, or its payment deadline moved and the command was deferred again. The command decides, from the state of its aggregate:
[EventContract("CancelUnpaidOrder", @namespace: "Sales")] // stored until it is due: give it a stable name
record CancelUnpaidOrder(AggregateIdentifier Id, DateOnly Deadline) : ICommand<OrderState, IOrderEvent> {
public async IAsyncEnumerable<IOrderEvent> ProgressAsync(
OrderState state,
[EnumeratorCancellation] CancellationToken cancellationToken = default) {
if (!state.Paid && !state.Cancelled && state.PaymentDeadline == Deadline)
yield return new OrderCancelled(Id.Value);
}
}- A due time in the past runs right away (a bill planned late).
- A deferred command runs at least once, so the command must be idempotent; the check above does that too.
- The command waits in the store, so the serializer must know its type. Converting "the due date in the user's time zone" to an instant is the application's job.
Nothing else is needed: the saga's scheduler starts by itself when the saga defers its first command. Policies can defer commands the same way. See Deferred commands for how they are stored, restarts, and what happens when a command type changes.
A deferred command is chosen when the saga defers it. Sometimes only the saga can decide at the due time what to do. Take a payment that must be settled 14 days after its due date: nothing paid → ReportMissingPayment, partially paid → SendPartialPaymentNotice, fully paid → nothing. The saga requests a deadline with a payload of its own, and receives that payload back at the due time, together with its current state. To receive deadlines, it implements ISaga<TSagaState, TEvent, TDeadline> instead of ISaga<TSagaState, TEvent>:
interface IPaymentDeadline;
[EventContract("PaymentDue", @namespace: "Billing")] // stored until it is due: give it a stable name
record PaymentDue(string PaymentId, DateTimeOffset Due) : IPaymentDeadline;
[SagaContract("PaymentFollowUp", @namespace: "Billing")]
class PaymentFollowUpSaga : ISaga<PaymentState, IPaymentEvent, IPaymentDeadline> {
public IEnumerable<AggregateIdentifier> Correlate(IPaymentEvent @event, EventMetadata metadata) =>
[new AggregateIdentifier($"payment-follow-up-{@event.PaymentId}")];
public async IAsyncEnumerable<ICommand> ReactAsync(
PaymentState state,
IPaymentEvent @event,
[EnumeratorCancellation] CancellationToken cancellationToken = default) {
if (@event is PaymentPlanned planned)
yield return Deadline.At(planned.Due.AddDays(14), new PaymentDue(planned.PaymentId, planned.Due));
}
public async IAsyncEnumerable<ICommand> ReactToDeadlineAsync(
PaymentState state,
IPaymentDeadline deadline,
[EnumeratorCancellation] CancellationToken cancellationToken = default) {
// Stale when the due date moved since the request.
if (deadline is not PaymentDue due || state.Due != due.Due)
yield break;
if (state.Paid == 0)
yield return new ReportMissingPayment(due.PaymentId, due.Due);
else if (state.Paid < state.Amount)
yield return new SendPartialPaymentNotice(due.PaymentId, due.Due);
}
}-
The deadline doesn't change the state.
Applyisn't called for it. The saga learns what happened from the events of the commands it sends. A state change driven by time ("expired") belongs in an aggregate. - No cancel. A deadline can be stale by the time it is delivered: recognise that from its payload and the state, as above.
- At least once. A deadline can be delivered twice. A reaction that requests new deadlines (an escalation) doesn't store them twice, but the commands it sends must be idempotent.
-
Payload types. Use a marker interface as
TDeadlineto receive several kinds. The payload waits in the store, so the serializer must know its type.
As for deferred commands, the scheduler starts by itself on the first deadline. See Saga deadlines for when to use which, redelivery and failures.
A policy is stateless — it reacts to an event and dispatches commands with no memory between invocations.
[PolicyContract("SendWelcomeEmail", namespace: "Users")]
class SendWelcomeEmailPolicy : IPolicy<UserRegistered> {
public async IAsyncEnumerable<ICommand> ReactAsync(
UserRegistered @event,
[EnumeratorCancellation] CancellationToken cancellationToken = default) {
yield return new SendEmail(@event.UserId, "Welcome!");
}
}services
.AddAggregates(o => o.ScanAssemblies(typeof(SendEmail).Assembly))
.AddMssp(o => { /* serialization */ });
services
.AddAggregates()
.AddPolicies(o => o.ScanAssemblies(typeof(SendWelcomeEmailPolicy).Assembly))
.AddMssp();A subscription hosted service is registered automatically for every scanned policy.
A policy can defer a command too, without any state. Here, a user who hasn't confirmed their email address two days after registering gets a reminder:
[PolicyContract("ConfirmationReminder", namespace: "Users")]
class ConfirmationReminderPolicy : IPolicy<UserRegistered> {
public async IAsyncEnumerable<ICommand> ReactAsync(
UserRegistered @event,
[EnumeratorCancellation] CancellationToken cancellationToken = default) {
yield return new RemindUnconfirmedUser(@event.UserId, @event.RegisteredOn).DeferUntil(@event.RegisteredOn.AddDays(2));
}
}As for a saga, the command decides when it runs whether it still applies (the user confirmed in the meantime). The deferred commands of one reaction are stored after the other commands it yields were dispatched, once per event: a retry or a restart doesn't store them twice. See Deferred commands of a policy.
A projection reads the event stream and writes to an external read model (SQL database, search index, etc.).
[ProjectionContract("Orders", namespace: "ReadModels")]
class OrdersProjection(IDbConnectionFactory db) : IProjection<IOrdersEvent> {
public ValueTask<ICommit> ProjectAsync(
IOrdersEvent @event,
EventMetadata metadata,
CancellationToken cancellationToken = default) =>
ValueTask.FromResult<ICommit>(@event switch {
OrderPlaced e => Commit.Create().UseSql(db)
.Query("INSERT INTO orders (id, date) VALUES (@Id, @Date)",
new { e.Id, e.Date }),
OrderShipped e => Commit.Create().UseSql(db)
.Query("UPDATE orders SET shipped = 1 WHERE id = @Id",
new { e.Id }),
_ => Commit.Create()
});
}Commit.Create() starts an empty commit chain. .UseSql(db).Query(...) (from Aggregates.Projections.Sql) appends a SQL statement. The infrastructure calls CommitAsync after ProjectAsync returns.
services
.AddProjections(o => o.ScanAssemblies(typeof(OrdersProjection).Assembly))
.AddMssp();A subscription hosted service is registered for every scanned projection.
After a crash, a projection gets up to MaxBatchSize (100) events again, because its checkpoint is written in batches. With RecordSqlPositions, every UseSql transaction records the event's position together with its statements and skips them when the event comes again:
services
.AddProjections(o => o.ScanAssemblies(typeof(OrdersProjection).Assembly))
.RecordSqlPositions() // or: o => { o.Schema = "projections"; o.Table = "Positions"; }
.AddMssp();The table ([dbo].[ProjectionPositions] by default) is created in each database on first use. Only UseSql writes are covered; other commits in the chain, and replayed parked events, still run at least once. See Exactly-once in SQL.
A projection, policy or saga that keeps failing on an event parks it after its retries and continues with the next event. Once the cause is fixed, replay it with IParkedMessages, for example from an admin endpoint:
app.MapGet("/admin/parked/{id}", async (string id, IParkedMessages parked) =>
await parked.ListAsync(id));
app.MapPost("/admin/parked/{id}/replay", async (string id, IParkedMessages parked) =>
(await parked.ReplayAllAsync(id)).Select(r => new { r.Message.Id, r.Succeeded, Error = r.Error?.Message }));
app.MapPost("/admin/parked/{id}/{messageId}/dismiss", async (string id, string messageId, IParkedMessages parked) =>
await parked.DismissAsync(id, messageId));The id is the subscription id (ReadModels.Orders@v1), or scheduled-{subscription id} for deferred commands and deadlines. ReplayAllAsync stops at the first message that still fails; that message stays parked.
A handler that must handle events in order, such as an outbox, can block instead of parking: it retries the failing event until it succeeds and handles nothing else until then.
[ProjectionContract("Outbox", namespace: "Shipping", onError: SubscriptionErrorMode.Block)]
class ShippingOutbox(IOutboxClient client) : IProjection<IShipmentEvent> { … }See Replaying parked messages and Blocking instead of parking.
Add the subscriptions and schedulers of a host to your ASP.NET Core health checks:
builder.Services.AddHealthChecks()
.AddCheck<SubscriptionHealthCheck>("aggregates");
app.MapHealthChecks("/health");The check is unhealthy when a subscription or scheduler stopped, degraded when one is retrying after a failure or blocked on an event, and healthy otherwise. See Health.