Skip to content

Architecture

Wouter Naessens edited this page Nov 13, 2026 · 26 revisions

Architecture

This page describes the internal design of the Aggregates library — how events flow from a command through to the event store and back through subscriptions to sagas, policies, and projections.


Functional event sourcing

The library is built on two pure functions from functional event sourcing theory.

Apply — folds an event into the current state. Must always succeed; an event is an irrejectable fact.

(TState, TEvent) → TState

Progress — accepts the current state and a command, and produces events. Allowed to fail; this is where domain rules are enforced.

(TState, TCommand) → IAsyncEnumerable<TEvent>

These two functions are the only things you implement. Everything else — loading, versioning, concurrency control, retry, persistence — is handled by the library.


Command handling pipeline

When ICommandHandler<TCommand>.HandleAsync is called, the request flows through a fixed decorator chain before reaching your domain logic:

ICommandHandler<TCommand>
  └── LoggingCommandHandler           (structured log on entry/exit/error)
        └── RetryCommandHandler       (up to 3 retries on ConcurrencyException)
              └── MetadataAwareCommandHandler   (opens MetadataScope per attempt)
                    └── UnitOfWorkAwareCommandHandler
                          └── CommandHandler<TCommand, TState, TEvent>
                                ├── IRepository<TState, TEvent>.LoadAsync   (loads aggregate)
                                ├── EntityRoot.AcceptAsync                  (runs ProgressAsync)
                                └── CommitDelegate                          (persists via storage integration)

All decorators are registered automatically by AddAggregates. You inject ICommandHandler<TCommand> and the full chain is wired for you.

Unit of work

UnitOfWorkAwareCommandHandler creates a UnitOfWorkScope per command. The scope tracks exactly one changed aggregate — the one targeted by the command — and passes the command's cancellation token to the CommitDelegate. On successful commit, the scope is disposed and the unit of work is cleared. On failure (including concurrency conflicts), the scope is also disposed so the next retry starts clean.

RetryCommandHandler catches ConcurrencyException and retries the full inner handler, including a fresh load from the store, up to three times. This is safe because each attempt rebuilds state from scratch.

Optimistic concurrency

Every aggregate has a Version — the revision at which it was loaded from the store. When the commit handler appends events, it passes that version as the expected revision. If another writer modified the aggregate in the meantime, the store rejects the write and throws ConcurrencyException, triggering a retry.

Metadata

MetadataAwareCommandHandler opens a MetadataScope for each command attempt (including retries — each attempt gets a fresh scope). A scope opened without arguments starts with a copy of the entries of the ambient scope, so correlation or causation identifiers propagated by a saga or policy, or added by the host around the command, are inherited automatically; what the command adds doesn't reach the outer scope.

During EntityRoot.AcceptAsync, the MetadataAttribute instances on the state type are evaluated after each event is applied, and those on the command type once, after the last event (also when the command produces none); their values are written into the active scope, so for the same key with MetadataMultiplicity.Single the command's value wins. The storage integration's commit handler reads MetadataScope.Current at commit time and serialises the accumulated snapshot alongside every event it writes.

Sagas and policies seed their own MetadataScope from the Metadata field of the incoming SubscriptionMessage before calling their handlers. Commands dispatched inside a handler therefore inherit the triggering event's metadata (e.g. a correlation identifier) automatically. A seeded scope starts with the seed only: a replay of a parked message started from a request, or a deferred command, never picks up the metadata of the host around it.


Event contracts and schema evolution

Events are mapped to event store type names via [EventContract]:

[EventContract("ItemAdded", version: 1, eventUpgrader: typeof(ItemAddedV1ToV2), @namespace: "Orders")]
record ItemAddedV1(string ItemId, int Quantity);

[EventContract("ItemAdded", version: 2, @namespace: "Orders")]
record ItemAdded(string ItemId, int Quantity, string Unit);

The stored type names are Orders.ItemAdded@v1 and Orders.ItemAdded@v2. The application's Deserialize turns a stored event into its .NET type, usually through EventTypeRegistry. The storage integration then applies EventContractAttribute.Upgrade: as long as the event's type has an upgrader, it runs it and continues with the result. So the upgrader sits on the old version, and its TOld is that type.

AddKurrentDb and AddMssp wrap Deserialize with this upgrade, so every read path gets it: repositories, subscriptions, saga repositories, the replay of parked messages and the scheduler. Application code only sees the last version.

EventTypeRegistry.FromTypes (and FromAssemblies) checks each upgrader at startup: it must implement IUpgradeEvent<TOld, TNew> exactly once, with a TOld that accepts the type it sits on, because Upgrade uses the upgrader's first IUpgradeEvent; and it must have a public parameterless constructor, because the upgrader is created with Activator on its first use (there is no dependency injection for upgraders). Without a registry there is no startup check, and a misconfigured upgrader fails when the event is read: a subscription parks the event, a command fails. The registry doesn't check whether a chain reaches the last version, nor whether upgraders form a cycle.


Subscription infrastructure

Sagas, policies, and projections all share the same subscription infrastructure, provided by Aggregates.Subscriptions.

ISubscriptionFactory.Subscribe(SubscriptionRequest(FromPosition, StartFromEnd, EventTypes, ProgressInterval))
    └── ISubscription (IAsyncEnumerable<SubscriptionMessage>)
          └── SubscriptionMessage(Event: object?, CommitPosition: ulong, Source: EventReference, Metadata: EventMetadata)
                                  { DeserializationError: Exception?, IsProgress: bool }

Each subscription hosted service runs a shared SubscriptionLoop, which:

  1. Reads the last stored checkpoint from ICheckpointStore.
  2. Opens a subscription from that position via ISubscriptionFactory.
  3. For each message, either parks it right away when it could not be deserialised (see Deserialisation failures), or hands it to the hosted service, which dispatches it to the handler via SubscriptionRetryPolicy.
  4. Records the message's position as processed — regardless of whether handling succeeded or the message was parked. Checkpoints are written in batches; see Checkpointing.
  5. Subscribes again when the subscription fails or ends; see Resubscribing.

The checkpoint stream is kept separate from the event stream (e.g. checkpoint-{subscriptionId} in KurrentDB and MSSP).

The storage integration package provides both ICheckpointStore and ISubscriptionFactory. The core packages contain the hosted services and the loop; integrations register only the transport-specific implementations.

One subscription per handler class

Every projection, policy and saga class gets one hosted service with its own subscription:

  • A class implements IProjection<TEvent>, IPolicy<TEvent> or ISaga<TSagaState, TEvent> once. To handle several event types, use a marker interface (or object) as TEvent; events of all those types then arrive in the order they were stored. A class that implements its interface more than once fails at registration with an InvalidOperationException.
  • Several classes may handle the same event type. Each gets its own subscription and runs independently of the others.
  • The subscription id is the string form of the class's contract attribute, {namespace}.{name}@v{version} (e.g. Orders.OrderSummary@v1), or the class's full type name when it has none. It names the checkpoint stream (checkpoint-{id}) and the parked-message stream (parked-{id}), and it equals the persistent subscription group name of 0.x.
  • Ids are unique per host, across projections, policies and sagas: a second class with the same id fails at registration. Run a subscription in one host only. Two hosts with the same id on the same store each process every event and overwrite each other's checkpoint.
  • Each subscription is described by a SubscriptionRegistration singleton, so IEnumerable<SubscriptionRegistration> lists the subscriptions of a host.

A slow handler only holds up its own subscription.

Where a subscription starts

When the subscription loop starts, it picks the first of:

  1. Its own checkpoint (checkpoint-{id}).
  2. The checkpoint of its nearest predecessor that has one. The predecessors come from continueFrom on the contract (SubscriptionRegistration.Predecessors). Without continueFrom, Orders.OrderSummary@v3 has @v2 and @v1 as predecessors, nearest first; with continueFrom: "Legacy.Summary@v5" it has exactly that one; with continueFrom: ContinueFrom.None ("") it has none. The loop writes the adopted position as the subscription's own first checkpoint before it subscribes, so later starts no longer depend on the predecessor. A predecessor's checkpoint wins over startFromEnd.
  3. The end of the store with startFromEnd: true, otherwise the beginning. On KurrentDB the loop asks the store for its last position and writes it as the subscription's first checkpoint before it subscribes, so a restart before the first event continues from that position instead of from the new end. MSSP can't tell its end position yet; there the subscription starts from the end as it subscribes.

Requiring a checkpoint. Step 3 is right for a new environment, a new contract or a deliberate replay, and wrong when the position exists but isn't there yet: 0.x positions that weren't imported, a checkpoint store that was cleaned up, a typo in continueFrom. With SubscriptionCheckpointOptions.RequireCheckpoint on, a subscription without its own or a predecessor's checkpoint fails before it subscribes instead, also with startFromEnd. The failure is not transient: the loop logs it as critical and the hosted service ends, so under the default BackgroundServiceExceptionBehavior.StopHost the host stops. Nothing is processed and nothing is written, so an import can still write the checkpoint afterwards. The exception names the id, its predecessors and where it would have started.

A deliberate start without a checkpoint stays possible without a code change: list the id in AllowedWithoutCheckpoint. Binding the options from configuration makes that a configuration change:

// Before AddProjections / AddPolicies / AddSagas, which only add their defaults when absent.
services.AddSingleton(builder.Configuration.GetSection("Aggregates:Checkpoints").Get<SubscriptionCheckpointOptions>() ?? new());
{ "Aggregates": { "Checkpoints": { "RequireCheckpoint": true, "AllowedWithoutCheckpoint": [ "Shop.InvoiceSummary@v1" ] } } }
  • Remove an id from the list once checkpoint-{id} exists. A subscription writes its first checkpoint after its first event (on KurrentDB also after MaxFilteredEvents skipped events, and right away with startFromEnd), so a filtered subscription on MSSP can stay without one for a while; removed too early, it fails again at its next start.
  • An id that stays listed is harmless while its checkpoint exists, but no longer protected if that checkpoint disappears.
  • The option doesn't apply to the scheduler of deferred commands and saga deadlines: without a checkpoint it reads every request again, but it records each delivery, so it executes none twice.

What follows from that:

  • A contract version bump continues where the old version stopped; it doesn't replay. To replay, set continueFrom: ContinueFrom.None on the new version.
  • An environment that never ran @v2 continues from @v1. The loop logs a warning that names the skipped versions: if a skipped version replayed on purpose, that replay didn't happen there. Set continueFrom explicitly for that release if it matters.
  • When no predecessor has a checkpoint (a new store, or a different ICheckpointStore than the old version used), the loop logs a warning and starts from the beginning or the end, or, with RequireCheckpoint, stops.
  • The old version's checkpoint and parked messages (parked-{old id}) are kept; nothing is deleted.
  • Two versions of one contract in the same host fail at registration, because both would process the same events. Across hosts this can't be detected: stop the old version before starting the new one.
  • The chain follows the contract's own name and namespace. After a rename, set continueFrom to the old id.
  • A saga keeps its state across a bump: the saga stream is the saga id, not the contract. A saga that replays with the same saga ids doesn't react again to events already linked in its streams; give it other saga ids to rebuild its reactions.
  • Adding an event type to a handler's marker interface doesn't replay history for that type, also not with a version bump. Use continueFrom: ContinueFrom.None to replay.
  • The event-type filter is computed again at every start, from the handler's TEvent and the EventTypeRegistry. Changing the event types a handler accepts needs no version bump: the next start subscribes with the new filter, from the checkpoint. A bump only decides where the subscription starts and under which id its checkpoint is kept. (0.x fixed the filter in the persistent subscription group, so a change there did need a new version.)
  • A position imported from a 0.x persistent subscription group is the subscription's own checkpoint (checkpoint-{group name}), or a predecessor's when 1.0 runs a higher contract version. See Importing 0.x subscription positions.

Event-type filter

When an EventTypeRegistry is registered in the service collection, every subscription asks the store for only the event types its handler can receive. The store skips the rest: they are not sent, not deserialised and not handled.

services.AddSingleton(EventTypeRegistry.FromAssemblies(typeof(OrderPlaced).Assembly));
  • Which types. EventTypeRegistry.GetTypeNames(TEvent): the stored names of every concrete type in the registry's assemblies that is assignable to TEvent, plus every older version that an upgrader turns into such a type, directly or through a chain of upgraders (see Event contracts and schema evolution). Types without [EventContract] are included under their short type name, which is how GetTypeName stores them.
  • No filter for a handler of object, and for every subscription when no registry is registered. Those subscriptions receive every event type, as before.
  • No known type. When the registry knows no type a handler can receive, the loop logs a warning and subscribes without a filter, so nothing is skipped by mistake.
  • Names must match. The filter uses the registry's names, so Serialize must store events under those names (registry.GetTypeName(type)). When an event is stored under another name, the commit handler logs a warning once per type: subscriptions won't receive those events. Remove the registry from the service collection to turn filtering off.
  • Per transport. KurrentDB filters with EventTypeFilter.RegularExpression; MSSP with its event type pattern filter. Both exclude $ event types as before.

Progress while filtered

A subscription whose events are rare would otherwise keep an old checkpoint while the store moves on, and start far behind after a restart. On KurrentDB the store reports its position each time it has skipped about SubscriptionCheckpointOptions.MaxFilteredEvents events (default: 4096, rounded up to a multiple of 32). The loop writes that position as the checkpoint right away; the handler sees nothing. MSSP doesn't report progress yet.

Every checkpoint written is itself an event in the store that the other subscriptions skip. Keep MaxFilteredEvents well above the number of subscriptions on the store (in all hosts together); otherwise the subscriptions keep each other's progress reports going.

Reserved $ event types

Subscriptions never deliver events whose type starts with $. The library's own bookkeeping uses that prefix — checkpoints are stored as $aggregates-checkpoint events, parked messages as $aggregates-parked events (closed by $aggregates-parked-replayed and $aggregates-parked-dismissed), deferred commands and saga deadlines as $aggregates-scheduled-command, $aggregates-scheduled-deadline, $aggregates-scheduled-delivered and $aggregates-scheduled-marker events — so writing them does not feed back into the subscriptions that produce them. On KurrentDB this is the standard ExcludeSystemEvents filter; on MSSP the subscription uses an event type pattern filter that is evaluated by the store.

Don't give your own events a type name starting with $: they would never reach a saga, policy, or projection.

Checkpointing

A subscription records the position of every processed message in memory and writes it to ICheckpointStore when either threshold of SubscriptionCheckpointOptions is reached:

  • MaxBatchSize messages have been processed since the last write (default: 100), or
  • the oldest unwritten position is older than MaxInterval (default: 5 s).

The pending position is also written when the subscription stops, with its own 5 s timeout because the stopping token is already cancelled by then. A position is only recorded after its message has been handled or parked, so a message that fails outside the retry policy is never checkpointed.

Delivery is at-least-once: after a crash, at most MaxBatchSize messages are delivered again. Handlers must be idempotent; SQL projections can be made exactly-once instead (see Exactly-once in SQL). A reconnect within the same process delivers nothing again: the loop resumes after the last processed message, not after the stored checkpoint.

The MaxInterval threshold is checked when a message arrives. A subscription that goes idle after a burst keeps its last position in memory until the next message or until it stops.

A filtered subscription also writes its position when the store reports progress, once per MaxFilteredEvents skipped events (see Progress while filtered).

Register a custom SubscriptionCheckpointOptions singleton before calling AddSagas / AddPolicies / AddProjections to override the defaults:

services.AddSingleton(new SubscriptionCheckpointOptions {
    MaxBatchSize      = 500,
    MaxInterval       = TimeSpan.FromSeconds(10),
    MaxFilteredEvents = 8192
});

Retention

Transport Checkpoint stream retention
KurrentDB $maxCount is set to 1 on checkpoint-{subscriptionId} the first time a checkpoint is stored, so only the latest checkpoint is kept.
MSSP No stream retention yet. checkpoint-{subscriptionId} grows by one event per batch (roughly one per MaxBatchSize messages).

Parked-message streams are never truncated: a replayed or dismissed message stays in the stream, closed by a later entry.


Subscription error handling

When a handler throws an exception, the subscription does not stop. Instead, SubscriptionRetryPolicy applies a retry strategy before giving up:

  1. Retry with exponential backoff — the handler is called up to MaxRetries times (default: 5). The delay between attempts starts at InitialDelay (default: 1 s) and grows by BackoffMultiplier (default: 2×) per attempt, capped at MaxDelay (default: 30 s). A small random jitter (±10 %) is added to prevent thundering-herd effects on burst failures.

  2. Park on final failure — when all retries are exhausted, IParkedMessageSink.ParkAsync is called. The default implementation (LoggingParkedMessageSink) logs a warning but does not persist the message. The storage integration packages register a persistent sink that appends a $aggregates-parked event to a parked-{subscriptionId} stream.

  3. Checkpoint advances — after parking, the hosted service records the position as normal. The subscription continues from the next event; the failing message is not replayed automatically. Replay or dismiss it with IParkedMessages, or let the subscription block instead of parking.

OperationCanceledException is never retried or parked — it propagates immediately to support graceful shutdown.

handler throws
    └── SubscriptionRetryPolicy
          ├── attempt < MaxRetries  →  wait Backoff(attempt)  →  retry
          └── attempt = MaxRetries  →  IParkedMessageSink.ParkAsync  →  continue

Configuration

Register a custom SubscriptionErrorHandlingOptions singleton before calling AddSagas / AddPolicies / AddProjections to override the defaults:

services.AddSingleton(new SubscriptionErrorHandlingOptions {
    MaxRetries    = 3,
    InitialDelay  = TimeSpan.FromMilliseconds(500),
    MaxDelay      = TimeSpan.FromSeconds(10),
    BackoffMultiplier = 2.0
});

Resubscribing

A failure outside the handler — a dropped connection, a server restart, an unavailable checkpoint store — does not stop the host. The subscription loop logs it, waits, and subscribes again. A subscription that ends without an error (for example when a remote MSSP server shuts down) is treated the same way.

  • Where it resumes. After the last processed message, which can be ahead of the stored checkpoint. Before the first message, after the stored checkpoint.
  • How long it waits. SubscriptionResubscribeOptions: starts at InitialDelay (1 s), grows by BackoffMultiplier (2×) per consecutive failure, capped at MaxDelay (30 s), with ±10 % jitter. The backoff starts over once a message has been processed. There is no maximum number of attempts.
  • What is logged. Every failure as a warning (an error from the 5th consecutive failure on) with the subscription id, the position, the attempt and the delay; the first message after a resubscribe as information.

Whether a failure is transient is decided by ISubscriptionFactory.IsTransient. Only failures that need a configuration change stop the subscription:

Transport Not transient
KurrentDB AccessDeniedException, NotAuthenticatedException, and an RpcException with status PermissionDenied, Unauthenticated, InvalidArgument, Unimplemented or FailedPrecondition
MSSP An RpcException from a remote server with one of the statuses above

Everything else is transient, including errors from the checkpoint store and the parked-message sink. A failure that is not transient is logged as critical and rethrown; what happens to the host then follows HostOptions.BackgroundServiceExceptionBehavior (by default the host stops; with Ignore the health check reports the stopped subscription). A custom ISubscriptionFactory treats every failure as transient unless it overrides IsTransient.

The last processed position is written when the loop ends. A failure to write it is logged and never replaces the exception that ended the loop.

Register a custom SubscriptionResubscribeOptions singleton before calling AddSagas / AddPolicies / AddProjections to override the defaults:

services.AddSingleton(new SubscriptionResubscribeOptions {
    InitialDelay = TimeSpan.FromMilliseconds(500),
    MaxDelay     = TimeSpan.FromMinutes(1)
});

A subscription with startFromEnd and no checkpoint yet doesn't skip events appended during an outage before its first message: on KurrentDB its start position is written as a checkpoint before it subscribes (see Where a subscription starts). Limitation on MSSP: there such a subscription starts from the end again after a failure or restart before its first message, so events appended in between are skipped.

Detecting a half-open connection relies on the transport's keepalive (KurrentDB: the client's gRPC keepalive settings; remote MSSP: the gRPC channel options).

Deserialisation failures

When Deserialize or DeserializeMetadata throws, the subscription does not stop. The message arrives with Event = null and the exception in DeserializationError, and the loop parks it right away — without retries, because deserialisation gives the same result every time — and continues with the next event.

Every subscription deserialises every event it receives, so an event that fails to deserialise is parked once per subscription that receives its type, each in its own parked-{subscriptionId} stream. With the event-type filter that is only the subscriptions whose handler can handle the type; without it, every subscription.

Unknown event types

Deserialize returning null means "unknown type, skip it": the event is not handled, not parked, and its position is recorded. Return null for event types your application doesn't know, rather than throwing; throwing parks the event. With the event-type filter types the registry doesn't know don't reach a filtered subscription at all.

That holds for subscriptions, which read $all with the events of other services. In the stream of an aggregate or saga it is the other way around: everything there was written by the application itself, so an event Deserialize doesn't know (or that isn't a TEvent) fails the load with an InvalidOperationException, as does a stream that misses events. Events are append-only: keep every old event version in the code and in the registry, with an upgrader to the current one.

Parked messages

Parked messages are persisted as $aggregates-parked events in a dedicated stream: parked-{subscription id} (e.g. parked-Orders.OrderFulfillment@v1) for a subscription, parked-scheduled-{subscription id} for the deferred commands and deadlines of its scheduler. Each event's JSON payload contains:

Field Content
CommitPosition The position of the message in the store.
Stream, Revision Where the event is stored (for the scheduler: the request). Used by a replay to read it back.
EventType The full CLR type name of the deserialized event; absent when it could not be deserialized.
ExceptionType, Message, StackTrace The exception of the last attempt.

A parked message is closed by an entry in the same stream: $aggregates-parked-replayed after a successful replay, $aggregates-parked-dismissed after a dismissal. Its data is the parked message in link format ({revision}@parked-{id}). A message without such an entry is open. Parked-message streams are never truncated.

Replaying parked messages

IParkedMessages lists, replays and dismisses the open parked messages of a subscription id. AddProjections, AddPolicies and AddSagas register it; it reads and writes through the storage integration (AddKurrentDb() or AddMssp() on their builder).

var parked = services.GetRequiredService<IParkedMessages>();

var messages = await parked.ListAsync("Shipping.Outbox@v1");   // open messages, oldest first
var result = await parked.ReplayAsync("Shipping.Outbox@v1", messages[0].Id);
if (!result.Succeeded) logger.LogWarning(result.Error, "Still failing");

await parked.ReplayAllAsync("Shipping.Outbox@v1");              // stops at the first failure
await parked.DismissAsync("Shipping.Outbox@v1", messages[1].Id); // close without handling
  • What a replay does. It reads the event back from the store (Stream, Revision), deserializes it again, and hands it to the same handler chain as the subscription: a new scope, the logging decorator, the metadata of the event. A parked deferred command is dispatched with ICommandDispatcher, with the metadata of its request; a parked deadline is delivered to its saga.
  • Where it runs. In the calling host, next to the live subscription, which keeps running. The replayed event is handled after the events that followed it: don't depend on the order between a parked event and later ones. Don't replay the same id from two places at once.
  • Retries. The same MaxRetries and backoff as the subscription. When the last attempt fails, nothing is parked again: the message stays open and the result holds the error (Succeeded is false). A successful replay writes $aggregates-parked-replayed.
  • Failures without retries. A replay fails right away, without calling the handler, when the parked message doesn't tell which event it refers to, when the event no longer exists, when it can't be deserialized (or Deserialize returns null), when the handler no longer accepts its type, or when no subscription in this host handles the id. Such a message can still be dismissed.
  • Which subscription. The one whose id is the parked id, or the one that has it as a predecessor: after a version bump, Orders.OrderSummary@v2 replays the messages parked under Orders.OrderSummary@v1. When two subscriptions in the host qualify, the replay fails and names them. For scheduled-{id}, the scheduler of that subscription or of its successor.
  • Sagas. A replayed event is resolved again, to every saga it resolves to. A saga that already handled the event skips it (see Saga streams hold links).
  • ReplayAllAsync replays the open messages oldest first and stops at the first failure, because later messages may depend on it.
  • Listing and dismissing work for any id, also one no subscription in the host handles. Replaying or dismissing a message that is not open throws an InvalidOperationException.
  • Without a storage integration every method throws an InvalidOperationException.

IParkedMessages only knows the ids you give it; it doesn't list the ids that have parked messages. The ids of a host are in IEnumerable<SubscriptionRegistration>, together with their Predecessors.

Blocking instead of parking

Some handlers must handle events in order: an outbox that sends every change to another system, for example. Parking an event and continuing would send later changes before the parked one. Set onError: SubscriptionErrorMode.Block on the contract:

[ProjectionContract("Outbox", @namespace: "Shipping", onError: SubscriptionErrorMode.Block)]
public sealed class ShippingOutbox : IProjection<IShipmentEvent> { … }

PolicyContract and SagaContract take the same parameter. The default is SubscriptionErrorMode.Park.

  • What it does. A blocking subscription never parks. It retries the failing event with the backoff of SubscriptionErrorHandlingOptions (capped at MaxDelay) until it succeeds, and handles no later event until then. Its checkpoint stays before the event, so a restart retries it too. When the other system is down for an hour, everything continues by itself, in order, once it is back.
  • Undeserializable events. The loop doesn't park them either: it stops before the event and subscribes again after the resubscribe backoff. The event is deserialized again each time; that succeeds after a fix, in practice after a deploy.
  • Logging. Next to the warning the handler chain logs for every failed attempt, the retry policy logs an error once when it starts blocking (after MaxRetries attempts) and an information message once the event succeeds. An undeserializable event logs an error at every resubscribe.
  • Only the event subscription. The scheduler of a saga or policy keeps parking its deferred commands and deadlines: one blocking command would hold up every later request.
  • Stopping the host cancels the retries, as usual.

A blocking subscription that keeps failing falls behind; the health check reports it as blocked.

Health

Every subscription and every scheduler of a host reports its state to SubscriptionMonitor, a singleton that AddProjections, AddPolicies and AddSagas register. SubscriptionHealthCheck turns those states into one ASP.NET Core health check:

builder.Services.AddHealthChecks()
    .AddCheck<SubscriptionHealthCheck>("aggregates");
State Who Meaning Health
Running both Subscribed and handling messages; for a scheduler, reading and executing its requests. healthy
Waiting scheduler Its saga or policy never deferred a command or requested a deadline, so it doesn't read the store yet. healthy
Retrying both A transient failure, or a subscription that ended unexpectedly; it tries again with backoff. degraded
Blocked subscription A blocking subscription whose event still fails after MaxRetries attempts, or can't be deserialized. degraded
Stopped both It ended: after a failure that is not transient, because the other half of its hosted service ended, or because the host stops. unhealthy

The check is unhealthy when one subscription or scheduler stopped, degraded when one is retrying or blocked, and healthy otherwise. Its description names the ids that need attention; its data holds one line per id, such as Blocked since 2026-10-20T08:00:00.0000000+00:00 at position 42 (attempt 7): Timeout.

  • When retrying ends. A subscription is running again once a message arrives after the failure; the transport doesn't confirm a new subscription before that. On a quiet store it stays retrying, so degraded, until the next event. A scheduler is running again once the failed action succeeds or its feed reads an entry. ASP.NET Core answers a degraded check with HTTP 200 by default.
  • Since, position, attempts. Since is when the state began; a repeated failure doesn't move it. The position is the one at the latest change (the last processed position, or the event it blocks on), not updated for every message. There is no lag: MSSP doesn't report the end of the store yet.
  • Stopped together. A policy or saga runs its subscription and its scheduler in one hosted service. When one stops after a failure, the other reports stopped without an error.
  • Keeping the host up. Under the default BackgroundServiceExceptionBehavior.StopHost a stopped subscription stops the host. With Ignore, the host keeps running and the health check reports the stopped subscription as unhealthy.
  • Shutdown and startup. While the host stops, every subscription and scheduler reports stopped. Hosted services start in the background, so right after the host starts the check may list none yet.
  • Other thresholds. SubscriptionMonitor.GetStatuses() returns every state with its Since and Attempts; write your own IHealthCheck on it to report, for example, blocked as unhealthy after ten minutes.
  • Parked messages don't count: a parked message means the subscription continued. List them with IParkedMessages.

Sagas

A saga is a stateful process manager. It maintains its own state in the event store (just like an aggregate) and reacts to incoming events by dispatching commands.

event stream (all events)
    └── SagaSubscriptionService
          ├── ISaga.Correlate(event, metadata)  (a saga from a fresh scope)  → IEnumerable<AggregateIdentifier>
          ├── ISagaRepository.LoadAsync(sagaId)
          ├── ISaga.ReactAsync(state before the event, event)  → IAsyncEnumerable<ICommand>
          ├── ICommandDispatcher.DispatchAsync(command)
          └── SagaCommitDelegate  (appends a link to the event, and any deferred command or deadline, to the saga stream)

scheduled entries ($aggregates-scheduled*, all streams)
    └── Scheduler  (one per saga that ever deferred a command or requested a deadline)
          ├── when due, a deferred command: ICommandDispatcher.DispatchAsync(command)
          └── when due, a deadline: the saga
                ├── ISagaRepository.LoadAsync(sagaId = the stream of the request)
                ├── ISaga<,,>.ReactToDeadlineAsync(state, deadline)  → IAsyncEnumerable<ICommand>
                ├── ICommandDispatcher.DispatchAsync(command)
                └── SagaCommitDelegate  (only new requests; nothing for the deadline itself)

Each saga determines with its own Correlate which saga instance(s) receive a given event. A single event can target multiple saga instances (e.g., one per participant in a workflow), or none ([]). Correlate is part of ISaga, so every saga has one, and every scanned saga gets a subscription.

  • Once per event, in its own scope. The subscription resolves the saga from a fresh DI scope and calls Correlate once per event, before any instance handles it. A failure is retried and then parked (or blocked, with SubscriptionErrorMode.Block), like a failing reaction; no instance handles the event then.
  • From the event and its metadata only. A redelivered or replayed event must reach the same instances, so Correlate doesn't look anything up. An id that only a lookup can tell is written into the event's metadata when it is committed.
  • The id is the stream name. Two sagas that return the same identifier share a stream and read each other's links, so give each saga its own prefix or metadata key.

Saga streams hold links

A saga stream doesn't store the events the saga handled, but links to them: events of type $> with data "{revision}@{stream}" (e.g. "3@order-42"), the format 0.x used, so 0.x saga streams are read without conversion. Each SubscriptionMessage carries the stored position of its event as Source (an EventReference); the saga records that reference as its change, and the commit writes it as a link.

  • No feedback. A link has a $ type, so no subscription delivers it (see Reserved $ event types). An event reaches each projection, policy and saga exactly once, however many sagas link to it.
  • Reading. The saga repository resolves every link to the event it points to, and rebuilds the state from those events. KurrentDB resolves links on the server (resolveLinkTos). MSSP has no link events, so the MSSP repository resolves them on the client: one read per link, at most 8 in parallel, in stream order.
  • Version. The saga's version counts every link, also one that can no longer be resolved (its event was deleted or scavenged). Such a link leaves the state untouched, so retention on aggregate streams affects the sagas that link to them.
  • One reaction per event. A saga ignores an event its stream already links to: no state change, no reaction, nothing committed. A redelivery after a crash between the saga commit and the checkpoint is therefore harmless. Commands are dispatched before the saga stream is committed, so a failure in between does lead to a second reaction (see Commands run at least once).
  • Only links, deferred commands and deadlines. A saga stream that holds anything but links, deferred commands and deadlines is rejected with an InvalidOperationException ("… is not a saga stream"), and the event is parked. That catches a Correlate that returns an aggregate id: the saga reads the aggregate stream first and fails before writing to it.

Commands run at least once

A saga dispatches the commands it yields while it handles the event. Each one goes through the normal command pipeline, which commits it right away; the saga stream is committed after that. When that commit fails, nothing undoes the commands, and the next attempt sends them again:

  • A concurrency conflict. The saga's scheduler delivers a deadline to a saga instance while its subscription handles an event for the same instance, and both append to the saga stream. The handler chain reloads the saga and runs the reaction again.
  • A store failure on the append of the saga stream: the retry policy handles the event again.
  • A crash between the commands and the commit: the event is delivered again, and the saga stream doesn't link to it yet.

A policy has the same gap without a stream of its own. When a reaction yields A and B and B fails, the retry sends A again; a crash before the checkpoint repeats the whole reaction. Deferred commands and deadlines run at least once as well (a crash between the command and its delivered entry).

So every command a saga or policy sends must be idempotent:

  • Decide from the aggregate's state. The command checks whether it still applies: close a paid bill only when it isn't closed yet, send a reminder only when none was sent for that due date. A second dispatch then produces no events.
  • Derive ids from the trigger. A command that creates something outside the store (a print task, a message to another system) takes its id from data of the event or the saga state (the order id and the step, for example), not from a new Guid, so the other side recognises a repeat.

Storing the commands in the saga stream first and running them afterwards (an outbox) would make the window smaller, but not close it: delivery stays at least once, and every command would need a stable serialized form. The library doesn't do that.

Deferred commands of a saga

A saga can defer a command: it yields command.DeferUntil(due) from ReactAsync among its other commands. The request is stored in the saga stream, in the same append as the link to its trigger event, so there is no deferred command without the state and no state without its deferred commands. It counts for the saga's version and doesn't change its state. The saga itself doesn't receive anything when the command runs; it sees the events the command produces. See Deferred commands for the scheduler, which sagas and policies share.

Saga deadlines

A deferred command is fixed when the saga defers it, and its aggregate decides at the due time whether it still applies. That covers every decision that lives in one aggregate. A deadline is for the decisions only the saga can make at the due time: the decision combines facts from several aggregates, which only meet in the saga's state, or the command is chosen only then. The saga requests a deadline with a payload of its own, and at the due time that payload comes back to the same saga instance, with its state at that moment.

Use When
command.DeferUntil(due) The command is known now; its aggregate can tell at due whether it still applies.
Deadline.At(due, payload) The saga decides at due, from its state, which command to send, if any.
public sealed class PaymentSaga : ISaga<PaymentState, IPaymentEvent, IPaymentDeadline> {
    public IEnumerable<AggregateIdentifier> Correlate(IPaymentEvent @event, EventMetadata metadata) =>
        [new AggregateIdentifier($"payment-{@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) {
        // A deadline whose due date no longer matches the state is stale: ignore it.
        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);
    }
}
  • Receiving. A saga that requests deadlines implements ISaga<TSagaState, TEvent, TDeadline> instead of ISaga<TSagaState, TEvent>. It inherits from it, so it is a saga in every other respect: the same registration, Correlate and subscription. TDeadline is the type of the payloads; to receive several kinds, use a marker interface or base type of your own (as for TEvent) and pattern matching. A class implements it once: two deadline interfaces fail at AddSagas. Requesting a deadline from a saga without it, or with a payload that isn't a TDeadline, fails the reaction right away (retried, then the event is parked) instead of months later.
  • A deadline doesn't change the state. Apply is not called, and nothing is stored for the deadline itself: a reaction that only yields commands writes nothing to the saga stream. A saga's state is rebuilt from links to events, and every such event came from a command; a deadline that changed the state would be the first state no command produced. The saga learns what happened from the events of the commands it sends, like after any other reaction.
  • Consequences. A state change driven by time ("expired") needs an aggregate that records it through a command. The state the saga sees is its current state, which can lag behind the aggregates: its subscription may not have processed every event yet. The commands it sends are checked by their aggregates, as always.
  • Requesting. Deadline.At(due, payload) is yielded among the commands, from ReactAsync or from ReactToDeadlineAsync (escalation chains). It is stored in the saga stream as $aggregates-scheduled-deadline, in the same append as the link to the trigger, with the same JSON as a deferred command; the payload goes through Serialize/Deserialize, so give its type a stable name. It counts for the saga's version and doesn't change the state. A saga instance can have any number of open deadlines; there is no cancel: the saga recognises a stale one from its payload and its state.
  • Delivery. The scheduler of the saga delivers a due deadline through the saga's own handler chain (logging, retries on a concurrency conflict, the unit of work), with the metadata of the request. The saga instance is the stream that holds the request: Correlate is not called. If that stream no longer exists, the deadline is skipped with a warning. Delivery is at least once and can be late.
  • Redelivery. The requests a deadline's reaction stores carry that deadline as "cause" ("{revision}@{stream}" of the request). When the same deadline is delivered again (a crash before its delivered entry), the saga finds that cause in its stream and doesn't react again, so an escalation chain doesn't double. A reaction that stored no requests has nothing to recognise it by, and sends its commands again. As for events, commands are dispatched before the saga stream is committed, so a failure in between also leads to a second reaction (Commands run at least once).
  • Concurrency with events. The subscription and the scheduler can handle the same saga instance at the same time. A reaction that stores requests appends with the version it loaded; on a conflict the saga is reloaded and the reaction runs again. A reaction without requests writes nothing and has no version check.
  • Failures. A reaction that keeps failing is parked under parked-scheduled-{subscription id}, with the payload as the message's event. So is a payload that no longer deserializes, or one the saga can no longer receive (the class dropped ISaga<,,>, or TDeadline changed). Replay it with IParkedMessages under scheduled-{subscription id} once the cause is fixed: it is delivered to its saga again.
  • Contract versions and replays. A new version receives the open deadlines of its predecessors in its own ReactToDeadlineAsync, so their payloads must still fit. A saga that processes its history requests the deadlines of the past again; they are delivered right away and must be recognised as stale.
  • Not from a policy. A policy has no state to return to. A Deadline from a policy is dispatched as a command and fails (no handler); Deadline.At(...).DeferUntil(...) fails in a saga.

Policies

A policy is a stateless event reactor. It receives an event, produces zero or more commands, and has no persistent state of its own.

event stream (all events)
    └── PolicySubscriptionService
          ├── IPolicy<TEvent>.ReactAsync(event)  → IAsyncEnumerable<ICommand>
          ├── ICommandDispatcher.DispatchAsync(command)
          └── IScheduledStore.TryAppendRequestsAsync  (the deferred commands, after the others)

scheduled entries ($aggregates-scheduled*, all streams)
    └── Scheduler  (one per policy that ever deferred a command)
          └── when due: ICommandDispatcher.DispatchAsync(deferred command)

Because policies are stateless, they need no repository and no commit delegate — only a checkpoint to track their position in the stream.

Deferred commands of a policy

A policy can defer a command too: yield return new ReportMissingPayment(id, markedAt).DeferUntil(markedAt.AddDays(14));. It has no stream of its own, so its deferred commands go to a stream per event it reacted to:

  • After the other commands. The commands the policy yields are dispatched as they come; the deferred ones are collected and stored once the reaction is done, in one append. A reaction that fails stores nothing: when an immediate command keeps failing and the event is parked, nothing is deferred either.
  • Stored once per event. The stream is scheduled-requests-{subscription id}-{revision}@{stream} of the event, appended with "the stream must not exist yet". A second reaction to the same event (a retry after the append, or a restart before the checkpoint) finds the stream and stores nothing. This works the same on KurrentDB and MSSP, without event ids. The request carries the metadata of the event, as the saga's does.
  • Contract versions. The stream name holds the subscription id, so a new version that reacts again to events its predecessor already handled (after the predecessor's last checkpoint) stores their deferred commands again. Execution is at least once anyway, and the command's own checks reject the second one.

Deferred commands

A saga or a policy defers a command with command.DeferUntil(due) among the commands it yields from ReactAsync. The command runs when due has passed, through the normal command pipeline, with the metadata of the event that deferred it (so correlation is kept). How the request is stored differs: a saga stores it in its saga stream, a policy in a stream per event. Everything after that is shared.

if (@event is OrderPlaced placed) {
    var deadline = placed.PlacedOn.AddDays(3);
    yield return new CancelUnpaidOrder(placed.OrderId, deadline).DeferUntil(clock.StartOfDay(deadline));
}
  • Stale requests are the command's business. There is no cancel and no replace. A deferred command can outlive the reason it was deferred for (the order was paid, its payment deadline moved), so the command carries the data it applies to and its aggregate decides: CancelUnpaidOrder(orderId, deadline) produces nothing when the order is paid, already cancelled, or its deadline differs. The same check makes the command idempotent, which it must be: execution is at least once.
  • The stored request. An entry of type $aggregates-scheduled-command. Its data is JSON: the owner (the subscription id of the saga or policy), the due time, the command as the storage integration's Serialize stores it, and, when a deadline's reaction deferred it, that deadline as cause.
  • Commands are stored. A deferred command waits in the store, possibly for months, so Serialize and Deserialize must know its type under a stable name (for example an [EventContract] on the command). The scheduler deserializes every open request when it starts: a command that no longer deserializes (renamed type, changed field type, Deserialize returning null) is logged as a warning right away and stays open, so a fix deployed before it is due still runs it; when it is due and still broken, it is parked. A renamed field that silently gets its default value isn't detected: deserialize strictly (required members, or RespectRequiredConstructorParameters in System.Text.Json).
  • The scheduler. Each saga or policy that ever deferred a command runs a Scheduler next to its subscription, in the same hosted service. It reads the $aggregates-scheduled* entries of every stream from the store (KurrentDB: a server-side prefix filter on $all; MSSP: an event type pattern evaluated by the store), keeps the open requests of its handler in memory, and executes each when it is due, in order of due time. The scheduler of a saga also delivers the saga's deadlines ($aggregates-scheduled-deadline) this way, with the same checkpoint, delivered entries and parking. A due time in the past runs right away. The clock is the TimeProvider in the container, so tests can move it; the scheduler waits at most a minute at a time, which also copes with a clock that jumps.
  • Activated on first use. A saga or policy without deferred commands (or deadlines) costs one read at startup. Before its first request is stored, the stream scheduled-{subscription id} is written; from then on its scheduler runs at every start.
  • Restarts. After executing (or parking) a request, the scheduler appends $aggregates-scheduled-delivered to scheduled-{subscription id}. Its checkpoint (checkpoint-scheduled-{subscription id}) stays before the oldest open request, so a restart reads every open request again, and it executes nothing until it has read back a marker it appended at startup, so it never runs a request that was already handled. A restart costs one filtered read of $all from the oldest open request: about 4 s per million events on KurrentDB and under a second on embedded MSSP (measured). A crash between a command and its delivered entry runs the command again.
  • Failures. A failing command is retried and then parked under parked-scheduled-{subscription id}, like a subscription's message, and the scheduler continues with the next request. A command without a handler in the host fails the same way: register the command handlers in the host that runs the saga or policy. Replay it with IParkedMessages under scheduled-{subscription id}: it is dispatched with the metadata of its request.
  • Contract versions. A new version executes the open requests of its predecessors and continues from their scheduler's checkpoint. With continueFrom: "" it has no predecessors, and their open requests stay unexecuted.
  • Hosts. Run each saga and policy in one host, as for every subscription: two hosts would both execute each request.
  • Replays. A saga or policy that processes its history (no checkpoint, no startFromEnd) defers the commands of the past again, and they run right away. The commands' own checks must reject them, or the handler must start from the end.
  • Only from ReactAsync. ICommandDispatcher has no handler for a DeferredCommand: dispatching one fails.

Projections

A projection listens to the event stream and writes to a read model. It produces an ICommit — a composable unit of pending write work — that the infrastructure executes after ProjectAsync returns.

event stream (all events)
    └── ProjectionSubscriptionService
          ├── IProjection<TEvent>.ProjectAsync(event)  → ICommit
          └── ICommit.CommitAsync()

ICommit is composable: you can chain multiple writes (e.g. SQL via Aggregates.Projections.Sql) using Use(...). CommitAsync runs them in order. The chain as a whole is not atomic: each UseSql commits its statements in its own transaction, after its parent chain.

Exactly-once in SQL

RecordSqlPositions() on the projections builder makes UseSql writes take effect once, even though the subscription delivers at least once.

How it works:

  1. While a subscription projects a live event, ProjectedEvent.Current describes it: the subscription id, the event's commit position and the services of the event's scope. It is an AsyncLocal, so it reaches every commit in the chain without being passed along. A retry gets a new instance; a replayed parked event gets none.
  2. Each UseSql transaction first claims the position in a table, one row per subscription: (SubscriptionId, Position, Step). Step numbers the transactions of one event (1, 2, …), so a chain that writes a read model and then an outbox in two transactions claims (P, 1) and (P, 2).
  3. The claim moves the row forward only when it is behind (Position, Step). When it moved, the statements run and commit with it. When the row is already there or beyond, this transaction was committed for an earlier delivery: its statements are skipped.
Situation Result
Crash after the SQL commit, before the checkpoint The redelivered events find their positions claimed; nothing is written twice.
Crash between the read model and the outbox transaction The first transaction is skipped, the second runs.
A transaction fails and is retried It rolled back its claim; the retry runs it again.
A parked event is replayed No claim: it is projected (at least once).
A new contract version A new subscription id, so a new row.
A checkpoint reset by hand under the same id Events up to the row are skipped: delete the row too.

The claim, and creating the schema and the table when they don't exist, is one T-SQL batch in the transaction. Two claims for the same subscription at once (two hosts) are serialized by the row lock; the second finds the position taken. The checkpoint itself stays in the event store.

Writes outside UseSql in the same chain are still at least once.


Package dependency graph

Aggregates.Sagas ──────────────────────────────────────────────┐
Aggregates.Policies ────────────────────────────────────────── Aggregates.Subscriptions
Aggregates.Projections ─────────────────────────────────────────┘
        │
        └── Aggregates (core)

Aggregates.KurrentDB ──────────── Aggregates + Aggregates.Subscriptions
Aggregates.Sagas.KurrentDB ─────── Aggregates.KurrentDB + Aggregates.Sagas
Aggregates.Policies.KurrentDB ──── Aggregates.KurrentDB + Aggregates.Policies
Aggregates.Projections.KurrentDB ─ Aggregates.KurrentDB + Aggregates.Projections

Aggregates.MSSP ──────────────────── Aggregates + Aggregates.Subscriptions
Aggregates.Sagas.MSSP ────────────── Aggregates.MSSP + Aggregates.Sagas
Aggregates.Policies.MSSP ──────────── Aggregates.MSSP + Aggregates.Policies
Aggregates.Projections.MSSP ─────── Aggregates.MSSP + Aggregates.Projections

The core packages (Aggregates.Sagas, Aggregates.Policies, Aggregates.Projections) contain the hosted service loops and depend only on the shared ISubscriptionFactory / ICheckpointStore / IScheduledStore abstractions from Aggregates.Subscriptions, which also holds the Scheduler of deferred commands. Storage integration packages are the only layer that knows about KurrentDB or MSSP.

Clone this wiki locally