Event sourcing is associated with a separate event database, a broker and a month of configuration. Marten is a .NET library that uses PostgreSQL as a document store (the data goes into jsonb columns) and as an event store. So you have one database, one backup and one transaction covering the events and the views built from them.

Configuration

Registration is a single call. For new projects the documentation recommends lightweight sessions, that is UseLightweightSessions().

C#
builder.Services.AddMarten(options =>
{
    options.Connection(builder.Configuration.GetConnectionString("Marten")!);

    // The aggregate is stored in the same transaction as the events
    options.Projections.Snapshot<Order>(SnapshotLifecycle.Inline);
})
.UseLightweightSessions();

Marten creates its tables and functions in the public schema. You can set a different schema with options.DatabaseSchemaName.

Events and the aggregate

An event is a fact in the past tense, preferably a plain record. The aggregate is an object that Marten builds by replaying events in order. The convention from the documentation: a static Create method builds the aggregate from the first event, and Apply methods update it with the following ones.

C#
public record OrderPlaced(Guid OrderId, string Customer, decimal Amount);
public record OrderPaid(DateTimeOffset PaidAt);
public record OrderCancelled(string Reason);

public class Order
{
    public Guid Id { get; private set; }
    public string Customer { get; private set; } = "";
    public decimal Amount { get; private set; }
    public bool Paid { get; private set; }
    public bool Cancelled { get; private set; }

    public static Order Create(OrderPlaced e) => new()
    {
        Id = e.OrderId,
        Customer = e.Customer,
        Amount = e.Amount,
    };

    public static Order Apply(Order current, OrderPaid e)
    {
        current.Paid = true;
        return current;
    }

    public static Order Apply(Order current, OrderCancelled e)
    {
        current.Cancelled = true;
        return current;
    }
}

Create and Apply return the aggregate, and business code does not touch the state directly. The state changes only through events.

Writing

You start a new stream with StartStream and append further events with Append. Everything reaches the database only after SaveChangesAsync, in one transaction.

C#
await using var session = store.LightweightSession();

var id = Guid.NewGuid();
session.Events.StartStream<Order>(id, new OrderPlaced(id, "ACME", 250m));
await session.SaveChangesAsync();

session.Events.Append(id, new OrderPaid(DateTimeOffset.UtcNow));
await session.SaveChangesAsync();

For commands that first check the state, use FetchForWriting. It returns the aggregate and a handle to the stream on which you append events.

C#
public async Task Cancel(Guid orderId, string reason, IDocumentSession session)
{
    var stream = await session.Events.FetchForWriting<Order>(orderId);

    if (stream.Aggregate.Paid)
        throw new InvalidOperationException("We do not cancel a paid order.");

    stream.AppendOne(new OrderCancelled(reason));
    await session.SaveChangesAsync();
}

If you pass the expected stream version as the second argument of FetchForWriting, Marten throws a ConcurrencyException when someone appended an event first. That is optimistic concurrency control.

Reading: live or from a projection

The simplest read rebuilds the aggregate from the events on every query:

C#
var order = await session.Events.AggregateStreamAsync<Order>(id);

That is enough while streams are short and reads are rare. When reads are frequent, a projection stores the result as a document. In the registration above, Snapshot<Order>(SnapshotLifecycle.Inline) does this in the same transaction as the events, so the view is never inconsistent with the events. You read it like an ordinary document with LoadAsync<Order>(id).

When the view has a different shape than the aggregate, you write your own projection:

C#
public class OrderSummary
{
    public Guid Id { get; set; }
    public string Customer { get; set; } = "";
    public string Status { get; set; } = "placed";
}

public partial class OrderSummaryProjection : SingleStreamProjection<OrderSummary, Guid>
{
    public OrderSummary Create(IEvent<OrderPlaced> placed) => new()
    {
        Id = placed.StreamId,
        Customer = placed.Data.Customer,
    };

    public void Apply(OrderPaid e, OrderSummary view) => view.Status = "paid";
    public void Apply(OrderCancelled e, OrderSummary view) => view.Status = "cancelled";
}

// in AddMarten:
options.Projections.Add<OrderSummaryProjection>(ProjectionLifecycle.Inline);

The lifecycles are Live, Inline and Async. Inline gives immediate consistency at the cost of a longer write. Async moves the work to the background, so a read may lag behind for a moment.

Documents without events

Marten also works for ordinary documents, without event sourcing:

C#
public class Customer
{
    public Guid Id { get; set; }
    public string UserName { get; set; } = "";
}

session.Store(new Customer { Id = Guid.NewGuid(), UserName = "acme" });
await session.SaveChangesAsync();

var active = await session.Query<Customer>()
    .Where(c => c.UserName == "acme")
    .ToListAsync();

You enforce uniqueness of a field with an index in the configuration: options.Schema.For<Customer>().UniqueIndex(UniqueIndexType.DuplicatedField, x => x.UserName).

When a plain table is enough

Event sourcing has a cost. Events have to be versioned, because the types in code change while old events stay in the database forever. The team has to learn a new way of thinking. A plain table is enough if:

  • only the current state matters and nobody cares about the history,
  • an audit can be handled with a simple change-log table,
  • the entity is a form with a few fields, with no rules that depend on how a process went.

Event sourcing makes sense where history is a requirement: orders, payments, processes with state transitions in which the question "how did we get here" is really asked. Then the lack of a separate event database is an argument in itself: you already run PostgreSQL, it has backups and people who know it.