Event Sourcing
Excalibur provides a complete event sourcing implementation with aggregates, event stores, snapshots, and projections.
Start with the EventStore walkthrough for one continuous path from a running example through saves, projection consistency, versioning, recovery, and upgrades. This page provides an overview; the other pages are detailed references.
Traditional CRUD overwrites state on every save -- you lose the history of how you got there. Event sourcing stores every change as an immutable event, giving you: full audit trails (who changed what, when), temporal queries (what was the state at any point in time), easy debugging (replay events to reproduce bugs), and decoupled read models (build multiple query-optimized views from the same event stream).
Before You Start
- .NET 10.0
- Install the required packages:
dotnet add package Excalibur.Dispatchdotnet add package Excalibur.EventSourcing
- Familiarity with handlers and domain modeling
Follow the application lifecycle
Start with the walkthrough, then use these references as needed. Each step answers a different question:
- Choose storage and create its schema: providers and database migrations.
- Define what happened and enforce business rules: domain events and aggregates.
- Load, change, and save an aggregate: consumer implementation, followed by the repository reference for additional options.
- Build the query side: projections, choosing Async, Inline, or explicitly transactional processing.
- Change an existing application: event payload versioning for stored events; projection evolution for new read models, replay, cutover, and rollback.
- Operate and upgrade it: snapshots, event-store operations, and the alpha.19 checkpoint upgrade guide when upgrading that schema.
Which version am I changing?
| Concept | What it identifies | When you use it |
|---|---|---|
| Stream version / expected version | An aggregate's progress through its event history | Detect concurrent writes; the store assigns event positions within the stream. |
| Event payload version | The shape of one kind of stored event | Load older payloads through compatible defaults or upcasters. |
| Projection version / generation | A read-model definition and destination | Build changed models alongside existing ones, validate, then switch readers. |
| Database schema migration | Tables, columns, indexes, and constraints | Upgrade storage infrastructure; it does not upcast events or rebuild models. |
Changing one does not automatically perform the others. A CLR type rename is another separate concern: keep its stored message name stable, or preserve historical names with aliases.
Overview
Event sourcing captures all changes to application state as a sequence of events. Instead of storing current state, you store the history of state changes.
Key Benefits
| Benefit | Description |
|---|---|
| Complete audit trail | Every change is recorded with timestamp and metadata |
| Temporal queries | Query state at any point in time |
| Event replay | Rebuild state by replaying events |
| Debugging | Understand exactly how state evolved |
| Integration | Events naturally feed downstream systems |
Aggregate example
For the runnable setup and its expected results, use the walkthrough. The following excerpts illustrate a richer order aggregate and its handlers.
1. Define Domain Events
Events extend the DomainEvent abstract record which provides EventId, OccurredAt, and Metadata. Each event declares the stable name it is stored and transmitted under with [MessageName] — see Stable Message Names. An event carries only its own business data; the aggregate id is passed to the event store when appending, and the stream version is store-assigned:
[MessageName("Contoso.Orders.OrderCreated")]
public record OrderCreated(Guid OrderId, string CustomerId, decimal TotalAmount) : DomainEvent;
[MessageName("Contoso.Orders.OrderShipped")]
public record OrderShipped(Guid OrderId, string TrackingNumber, DateTime ShippedAt) : DomainEvent;
[MessageName("Contoso.Orders.OrderCancelled")]
public record OrderCancelled(Guid OrderId, string Reason) : DomainEvent;
2. Create an Aggregate
public class Order : AggregateRoot<Guid>
{
public string CustomerId { get; private set; } = string.Empty;
public decimal TotalAmount { get; private set; }
public OrderStatus Status { get; private set; }
public string? TrackingNumber { get; private set; }
// Private constructor for rehydration
private Order() { }
// Creates the empty instance that the repository will populate from history.
public static Order Rehydrate(Guid id) => new Order { Id = id };
// Factory method for creation
public static Order Create(Guid orderId, string customerId, decimal totalAmount)
{
var order = new Order();
order.RaiseEvent(new OrderCreated(orderId, customerId, totalAmount));
return order;
}
// Command methods
public void Ship(string trackingNumber)
{
if (Status != OrderStatus.Created)
throw new InvalidOperationException("Only created orders can be shipped");
RaiseEvent(new OrderShipped(Id, trackingNumber, DateTime.UtcNow));
}
public void Cancel(string reason)
{
if (Status == OrderStatus.Shipped)
throw new InvalidOperationException("Shipped orders cannot be cancelled");
RaiseEvent(new OrderCancelled(Id, reason));
}
// Event application - uses pattern matching, no reflection
protected override bool ApplyEventInternal(IDomainEvent @event) => @event switch
{
OrderCreated e => Apply(e),
OrderShipped e => Apply(e),
OrderCancelled e => Apply(e),
_ => false
};
private bool Apply(OrderCreated e)
{
Id = e.OrderId;
CustomerId = e.CustomerId;
TotalAmount = e.TotalAmount;
Status = OrderStatus.Created;
return true;
}
private bool Apply(OrderShipped e)
{
TrackingNumber = e.TrackingNumber;
Status = OrderStatus.Shipped;
return true;
}
private bool Apply(OrderCancelled e)
{
Status = OrderStatus.Cancelled;
return true;
}
}
3. Configure Event Sourcing
services.AddExcalibur(excalibur => excalibur.AddEventSourcing(builder =>
{
// Register repositories with explicit factory
builder.AddRepository<Order, Guid>(Order.Rehydrate);
// Configure snapshot strategy (optional)
builder.UseIntervalSnapshots(100); // Snapshot every 100 events
// Or use composite strategy for more control
// builder.UseCompositeSnapshotStrategy(s => s
// .AddIntervalStrategy(50)
// .AddTimeBasedStrategy(TimeSpan.FromMinutes(5))
// .RequireAll());
}));
// Add SQL Server event store (separate package)
services.AddSqlServerEventStore(opts => opts.ConnectionString = connectionString);
services.AddSqlServerSnapshotStore(opts => opts.ConnectionString = connectionString);
4. Use in Handlers
public class CreateOrderHandler : IActionHandler<CreateOrderAction, OrderResult>
{
private readonly IEventSourcedRepository<Order, Guid> _repository;
public CreateOrderHandler(IEventSourcedRepository<Order, Guid> repository)
{
_repository = repository;
}
public async Task<OrderResult> HandleAsync(
CreateOrderAction action,
CancellationToken ct)
{
var order = Order.Create(
Guid.NewGuid(),
action.CustomerId,
action.TotalAmount);
await _repository.SaveAsync(order, ct);
return new OrderResult(order.Id);
}
}
public class ShipOrderHandler : IActionHandler<ShipOrderAction>
{
private readonly IEventSourcedRepository<Order, Guid> _repository;
public async Task HandleAsync(ShipOrderAction action, CancellationToken ct)
{
var order = await _repository.GetByIdAsync(action.OrderId, ct);
if (order is null)
throw new OrderNotFoundException(action.OrderId);
order.Ship(action.TrackingNumber);
await _repository.SaveAsync(order, ct);
}
}
Architecture
Core Concepts
Domain Events
Events represent facts that have happened. They are immutable and named in past tense.
// Base interface
public interface IDomainEvent : IDispatchEvent
{
string EventId { get; }
DateTimeOffset OccurredAt { get; }
IDictionary<string, object>? Metadata { get; }
string? CorrelationId { get; }
string? CausationId { get; }
}
// Convenient base record with auto-generated defaults
public abstract record DomainEvent : IDomainEvent
{
public virtual string EventId { get; init; } = Guid.NewGuid().ToString();
public virtual DateTimeOffset OccurredAt { get; init; } = DateTimeOffset.UtcNow;
public virtual IDictionary<string, object>? Metadata { get; init; }
public virtual string? CorrelationId { get; init; }
public virtual string? CausationId { get; init; }
}
// The event's stored name is declared with [MessageName] on each event type —
// nothing is derived from the CLR type. See "Stable Message Names" in Domain Events.
//
// The aggregate id is supplied to the event store on append/load; the stream
// version is store-assigned and surfaced on the envelope during replay
// (HistoricEvent.Version / StoredEvent.Version) — never read from the event itself.
Aggregates
Aggregates enforce business rules and emit events when state changes.
public abstract class AggregateRoot<TKey> : IAggregateRoot<TKey>
{
public TKey Id { get; protected set; }
public long Version { get; protected set; }
public string? ETag { get; set; }
public IReadOnlyList<IDomainEvent> GetUncommittedEvents();
public void MarkEventsAsCommitted();
public void LoadFromHistory(IEnumerable<HistoricEvent> history);
protected void RaiseEvent(IDomainEvent @event);
protected abstract bool ApplyEventInternal(IDomainEvent @event);
}
Event Store
Persists events with optimistic concurrency control.
public interface IEventStore
{
ValueTask<IReadOnlyList<StoredEvent>> LoadAsync(
string aggregateId,
string aggregateType,
CancellationToken cancellationToken);
ValueTask<AppendResult> AppendAsync(
string aggregateId,
string aggregateType,
IEnumerable<IDomainEvent> events,
long expectedVersion,
CancellationToken cancellationToken);
}
Recommended Reading Order
- Domain Events -- Start here. Define the events that describe what happens in your domain.
- Aggregates -- Build aggregates that enforce business rules and raise events.
- Repositories -- Load and save aggregates, understand save outcomes, and handle concurrency.
- Event Store -- Persist and load event streams directly when needed.
- Snapshots -- Optimize loading for aggregates with many events.
- Projections -- Build query-optimized read models from event streams.
- Providers -- Choose and configure your database provider.
- Event Versioning -- Handle event schema changes over time.
- Projection Evolution -- Populate changed models and switch readers safely.
- Materialized Views -- Schedule-driven analytics views.
- Migrations -- Schema migrations CLI tool.
See Also
- Patterns - Outbox pattern for reliable event publishing
- Handlers - Command and event handler patterns
- Package Guide - Understanding which packages you need for event sourcing