Skip to content

About

Source-generated event sourcing for .NET. Zero-allocation event streams, projections, and aggregate roots — dispatch wired at compile time via Roslyn generator. Native AOT safe.

Topics

Resources

Contributing

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

916 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

ZeroAlloc.EventSourcing

NuGet Build codecov License: MIT AOT GitHub Sponsors

Event sourcing for .NET with source-generated aggregates: appends allocate nothing of their own, there is no reflection, and it runs under NativeAOT.

Why ZeroAlloc.EventSourcing

  • No allocation on the write path. EventStore.AppendAsync and AggregateRepository.SaveAsync allocate 0 B of their own, asserted by exact-budget tests. A full stream read allocates nothing of its own either: ReadAsync returns a struct reader.
  • Works under NativeAOT and trimming. Aggregate event dispatch and the event type registry are generated at compile time. CI publishes and runs an AOT app for the core and for every storage adapter.
  • Compile-time diagnostics. The generator tells you when an aggregate or projection cannot be generated, instead of it silently doing nothing at runtime.
  • Tested against real databases. SQL Server and PostgreSQL run through Testcontainers, SQLite in-process, with optimistic concurrency checked inside the transaction.

Install

dotnet add package ZeroAlloc.EventSourcing.Aggregates
dotnet add package ZeroAlloc.EventSourcing.Generators
dotnet add package ZeroAlloc.EventSourcing.InMemory

The generator package emits the aggregate dispatch. The AOT-safe event serialiser comes from ZeroAlloc.Serialisation, which the core package brings in.

The generators need the .NET 10 SDK 10.0.100 or later, or Visual Studio 2026 or later. They are built against Roslyn 5.0, and an older compiler skips them with warning CS9057, after which the generated event type registry and aggregate dispatch are missing. Version 2.0.0 was built against Roslyn 5.12 and loads only in the .NET 11 SDK; on .NET 10, use 2.0.2 or later. 2.0.1 still depended on ZeroAlloc.Serialisation 2.11.1 and other packages whose generators need SDK 10.0.4xx, so on older SDKs their generated methods, such as AddOrderPlacedSerializer() and AddSerializerDispatcher(), were missing. From 2.0.2 every generator in the dependency graph is built against Roslyn 5.0.

Quick start

using System.Text.Json.Serialization;
using Microsoft.Extensions.DependencyInjection;
using ZeroAlloc.EventSourcing;
using ZeroAlloc.EventSourcing.Aggregates;
using ZeroAlloc.EventSourcing.InMemory;
using ZeroAlloc.Serialisation;

var services = new ServiceCollection()
    .AddOrderPlacedSerializer().AddItemAddedSerializer().AddSerializerDispatcher()
    .AddSingleton<IEventTypeRegistry, OrderEventTypeRegistry>(); // emitted by the generator
services.AddEventSourcing()
    .UseInMemoryEventStore() // or UsePostgreSqlEventStore, UseSqlServerEventStore, UseSqliteEventStore
    .UseAggregateRepository<Order, OrderId>(() => new Order(), id => new StreamId($"order-{id.Value}"));
await using var provider = services.BuildServiceProvider();
var orders = provider.GetRequiredService<IAggregateRepository<Order, OrderId>>();

var id = new OrderId(Guid.NewGuid());
using (var order = new Order())
{
    order.Place("alice");
    order.AddItem(9.95m);
    await orders.SaveAsync(order, id); // appends two events, checks the expected version
}

using var loaded = (await orders.LoadAsync(id)).Value; // replays the stream
Console.WriteLine($"{loaded.State.Items} item, total {loaded.State.Total}"); // 1 item, total 9.95

[ZeroAllocSerializable(SerializationFormat.SystemTextJson)] public sealed record OrderPlaced(string Customer);
[ZeroAllocSerializable(SerializationFormat.SystemTextJson)] public sealed record ItemAdded(decimal Price);
[JsonSerializable(typeof(OrderPlaced))]
[JsonSerializable(typeof(ItemAdded))]
internal sealed partial class OrderJson : JsonSerializerContext;

public readonly record struct OrderId(Guid Value);

public partial struct OrderState : IAggregateState<OrderState>
{
    public static OrderState Initial => default;
    public int Items { get; private set; }
    public decimal Total { get; private set; }

    internal OrderState Apply(OrderPlaced e) => this;
    internal OrderState Apply(ItemAdded e) => this with { Items = Items + 1, Total = Total + e.Price };
}

// ApplyEvent dispatch and OrderEventTypeRegistry are source-generated: no reflection.
public sealed partial class Order : Aggregate<OrderId, OrderState>
{
    public void Place(string customer) => Raise(new OrderPlaced(customer));
    public void AddItem(decimal price) => Raise(new ItemAdded(price));
}

The feature tour shows consumers, projections, snapshots, Kafka and telemetry with one example each.

What you get

  • Append-only event store with optimistic concurrency through a typed StreamPosition, and a global stream across all aggregates.
  • Aggregates with struct state, generated event dispatch and a repository that loads and saves them.
  • Projections with filtering, batching and replayable rebuilds.
  • Snapshots with configurable policies, so loads replay only the newer events.
  • Stream consumers with checkpoints, batching, retry with backoff and FailFast, Skip or DeadLetter error handling.
  • Event upcasting, dead-letter stores and health checks.
  • Every runtime package targets net10.0 and net11.0.

Optional packages:

Performance

Against a hand-rolled SQLite event store on the same connection, both transactional, both checking the stream version inside the transaction. .NET 10, BenchmarkDotNet, same run; time is the ratio against the hand-rolled store, allocations are exact.

Operation Hand-rolled ZA.EventSourcing Allocated, hand-rolled → ZA
Append 1 event (transactional, OCC check) 1.00 1.20 3,888 B → 4,688 B
Read 100-event stream (ordered) 1.00 2.03 12,232 B → 25,632 B

The overhead is the price of typed events, pluggable serialisation, optimistic concurrency and the aggregate, projection and snapshot layers; at real-database latency the SQL round trip dominates. Full methodology and the per-call allocation budgets: docs/performance.md.

Learn more

About

Source-generated event sourcing for .NET. Zero-allocation event streams, projections, and aggregate roots — dispatch wired at compile time via Roslyn generator. Native AOT safe.

Topics

Resources

Contributing

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages