Search Sreeni's Insights

Filter by content type
technical September 11, 2018 11 min read

What is event sourcing? - Part 7

Event sourcing with fund reference data: event streams, appending with expected version, projections, rebuilding views from scratch and the trade-offs.

Share:

What is event sourcing? - Part 7

Current state alone does not always answer the questions our business asks. A fund profile may show the current fee and sector, but operations may also need to know what we knew on a particular date, which provider correction changed the value and how a downstream view was rebuilt. An event in event sourcing is a stored business fact and the source of truth for an aggregate, while an integration event in Event-Driven Architecture (EDA) is a message sent between services to tell them that something happened. They can have similar names, but the first is the history from which state is rebuilt and the second is a communication contract. In the previous article, we discussed event-driven architecture and publishing data-point events to independent consumers. In this article, we are going to see event sourcing, append-only streams, projections, optimistic concurrency and a worked fund reference-data example. This is the final article in the series.

Enterprise Integration Patterns series:

  1. What is enterprise integration and why do we need it? - Part 1
  2. What are the styles of integration? - Part 2
  3. What are messages, commands and events? - Part 3
  4. How do messages flow from producer to consumer? - Part 4
  5. How to make messaging reliable and consistent? - Part 5
  6. What is event-driven architecture? - Part 6
  7. What is event sourcing? - Part 7 (this article)

TL;DR Summary

  • Event sourcing stores state as an append-only sequence of business events instead of only storing the latest row.
  • A stream belongs to an aggregate, such as a fund share class identified by ISIN.
  • The current fund profile is rebuilt by replaying events such as FundLaunched, FeeChanged and SectorChanged.
  • Event sourcing supports audit, as-of queries, provider corrections and rebuilding projections, but it adds schema and query complexity.
  • An event store can be Event Store from eventstore.org, a SQL Server table or a library such as Marten over PostgreSQL.
  • Projections can update incrementally from a checkpoint or rebuild from position zero into a new view before switching consumers.

Why is current state not enough?

A current-state table may contain one row for a fund share class:

ISIN       Fee       Sector       Benchmark       UpdatedAt
GB0000001  0.75      Global Equity MSCI World     2018-07-04

This is useful for a website, but it does not tell us the previous fee, whether the sector was corrected by a provider or what the platform knew before the update. If a performance or reconciliation issue is raised later, deleting the old value has removed useful evidence.

We can add audit columns and history tables to a current-state design. That can be a good choice for a simple application. Event sourcing takes a different approach: the events which changed the state are the primary record, and current-state views are projections derived from them.

What is event sourcing?

Event sourcing stores the state of an aggregate as an append-only sequence of events. Instead of updating one row from Fee = 0.70 to Fee = 0.75 and losing the transition, the system appends FeeChanged with the old and new values. The current state is obtained by replaying the stream.

In simple terms, a bank statement is not replaced by one balance field; transactions explain how the balance was formed. Event sourcing keeps the changes and builds the balance or business view from those changes.

An event stream is normally associated with one aggregate. In the fund platform, a stream can represent one fund share class identified by ISIN. Example events include,

  • FundLaunched
  • ShareClassAdded
  • FeeChanged
  • SectorChanged
  • BenchmarkChanged
  • DataPointCorrected

The events should describe facts which were accepted by the domain. A raw provider row may be retained separately for reconciliation, while a domain event records the mapped and validated change.

The event store and stream

An event store persists events in append order and exposes a stream or position. Event Store, available from eventstore.org and associated with Greg Young’s event-sourcing work, is one specialised option. Marten provides event storage and projections over PostgreSQL. A SQL Server table with stream id, event number, event type, payload, timestamp and metadata can also implement the fundamental append-only model.

The following diagram depicts event sourcing as one source-of-truth flow. Fund reference data ingestion appends events to the event store, where each share class has its own ordered stream. The store is append-only: the events are never updated or deleted, and the views are derived from them.

Event store streams and projections
Event store streams and projections

The flow highlighted in purple is the new v5 FeeChanged event from the Stream: share class ISIN A, read by the projector after checkpoint: v4 and applied to the Current fund profile view. The lower path rebuilds from v1 at position 0 into Fee history view v2; the dashed swap happens only after the rebuilt view catches up. The italic note captures the important rule: views can be deleted and rebuilt, but the events cannot.

A simplified SQL table could look like this,

CREATE TABLE FundEvents
(
    StreamId nvarchar(200) NOT NULL,
    Version int NOT NULL,
    EventType nvarchar(200) NOT NULL,
    Payload nvarchar(max) NOT NULL,
    OccurredAt datetime2 NOT NULL,
    CorrelationId nvarchar(200) NULL,
    CONSTRAINT PK_FundEvents PRIMARY KEY (StreamId, Version)
);

The primary key prevents two writers from appending the same stream version. In practice, the append operation must also check the expected version in one transaction. A unique key alone may turn a concurrency conflict into an unclear duplicate error.

Appending events with expected version

Optimistic concurrency means a writer says which stream version it last read. If another writer has appended an event in the meantime, the expected version does not match and the append fails. The application can reload the stream, decide whether the requested change is still valid and try again.

public sealed class FundEvent
{
    public string StreamId { get; set; }
    public int Version { get; set; }
    public string EventType { get; set; }
    public string Payload { get; set; }
    public DateTime OccurredAt { get; set; }
    public string CorrelationId { get; set; }
}

public async Task AppendAsync(
    string streamId,
    int expectedVersion,
    IReadOnlyCollection<FundEvent> events)
{
    using (var transaction = connection.BeginTransaction())
    {
        var actualVersion = await GetVersionAsync(
            streamId, transaction);
        if (actualVersion != expectedVersion)
        {
            throw new InvalidOperationException(
                "Stream version conflict");
        }

        var version = expectedVersion;
        foreach (var item in events)
        {
            version++;
            await InsertEventAsync(
                item, streamId, version, transaction);
        }

        transaction.Commit();
    }
}

The database-specific transaction and parameter code is omitted to keep the pattern visible. The important parts are stream identity, expected version, append-only inserts and one transaction. Do not update or delete historical events to correct provider data. Append a DataPointCorrected event which points to the reason and the source correction.

Rebuilding current state

To rebuild a fund aggregate, load its events in version order and apply each event to an in-memory state object:

public FundProfile Apply(FundProfile profile, FundEvent item)
{
    switch (item.EventType)
    {
        case "FundLaunched":
            return profile.WithName(Read(item, "Name"));
        case "ShareClassAdded":
            return profile.WithShareClass(
                Read(item, "ShareClass"));
        case "FeeChanged":
            return profile.WithFee(
                ReadDecimal(item, "Fee"));
        case "SectorChanged":
            return profile.WithSector(
                Read(item, "Sector"));
        case "BenchmarkChanged":
            return profile.WithBenchmark(
                Read(item, "Benchmark"));
        case "DataPointCorrected":
            return ApplyCorrection(profile, item);
        default:
            throw new InvalidOperationException(
                "Unknown event type");
    }
}

The result is the current aggregate state. To answer “what did we know on 2018-06-30?”, replay only events whose effective or recorded time falls within the agreed as-of rule. The distinction between when the provider said something and when the platform learned it may matter, so keep both dates where the domain needs them.

Projections

A projection is a read model built from events. The current fund profile view can contain the latest name, currency, fee, sector, asset class and benchmark. Another projection can contain fee history, and another can produce a sector change report.

Projections can be updated incrementally. A subscriber reads new events, applies the event to its view, writes the view and advances a checkpoint. The checkpoint must advance only after the view write is durable. If the process fails before the checkpoint, the event is delivered again and the projection must be idempotent.

public async Task HandleAsync(
    FundEvent item,
    ProjectionCheckpoint checkpoint)
{
    if (item.Version <= checkpoint.Version(item.StreamId))
    {
        return;
    }

    var profile = await profileView.LoadAsync(item.StreamId);
    var updated = Apply(profile, item);
    await profileView.UpsertAsync(
        item.StreamId, updated, item.Version);
    await checkpoint.AdvanceAsync(
        item.StreamId, item.Version);
}

The version check and view update should be designed as one safe operation, or the view should carry the last applied stream version and reject an older duplicate. A checkpoint stored separately from the view can be advanced after the view write, but a crash between those actions will cause a repeated event. That is acceptable only when the view update is idempotent.

Rebuilding from scratch

Incremental projections are fast for day-to-day operation, but a projection bug or a new reporting requirement can require a rebuild. The rebuild process reads from stream position zero, applies all relevant events to a new table or index and validates the result. Once the new view is correct, the platform can switch readers to it.

public async Task RebuildProfileViewAsync(
    string newViewName)
{
    await profileView.CreateEmptyAsync(newViewName);
    var items = await eventStore.ReadFromStartAsync();
    foreach (var item in items)
    {
        var profile = await profileView.LoadAsync(
            newViewName, item.StreamId);
        var updated = Apply(profile, item);
        await profileView.UpsertAsync(
            newViewName, item.StreamId, updated);
    }

    await profileView.ValidateAsync(newViewName);
    await profileView.SwapAsync(newViewName);
}

The event-store read method and result type depend on the selected 2018 library, so the snippet is conceptual and should be adapted to that API. The design remains the same: do not overwrite the live projection while it is being rebuilt, and do not switch until the new view passes reconciliation checks.

Why do we need event sourcing?

Audit and history

The event stream shows which data point changed, when it changed, the old and new values, the source and the correlation id. This helps operations explain a fee correction and allows an auditor to inspect the sequence rather than only the final row.

As-of queries

Replaying events to a business date answers what the platform knew or what the fund state was according to the chosen time rule. This is valuable for investigating historical performance and provider corrections.

Rebuildable views

If a website index has a bug, we can build a corrected projection from the source events. We do not need to ask every provider to resend all historical files, provided the retention and event contract are sufficient.

Separate write and read models

The event stream is optimised for append and aggregate history, while projections are optimised for current profile reads, fee history or reports. Each view can contain only the fields needed by its consumers.

Challenges and trade-offs

Event schema versioning and upcasting

Events live longer than the code which first wrote them. A FeeChanged event may have a different payload shape after a later release. We can keep versioned event types, write upcasters which translate old events to the current in-memory shape or support multiple readers. Never silently reinterpret an old field with a new meaning.

Eventual consistency

The event stream can be written before a projection has caught up. A website may briefly show the previous fee. Expose projection lag where the user or operations team needs to understand the state.

Snapshots

Replaying a very long stream for every command can become expensive. A snapshot stores aggregate state at a known version, after which only later events are replayed. Snapshots are an optimisation and can be discarded and rebuilt; the event stream remains the source.

Storage growth and queries

Append-only storage grows continuously. Define retention, archival and backup policies. Do not ask the event store to answer every reporting query directly; build projections suited to the query and index them.

Deletion and privacy

Financial reference data is not the same as personal data, but provider payloads or operational metadata may contain information which has deletion requirements. An append-only design must consider redaction, encryption, access control and data-minimisation rules before putting sensitive content into an immutable stream.

Learning curve

Event sourcing changes how teams model corrections, queries and migrations. It is not a default replacement for a CRUD table. If the business does not need history, audit or rebuildable views, the extra complexity may not be justified.

Event sourcing versus event-driven architecture

Event sourcing and event-driven architecture are related but not the same.

ConcernEvent sourcingEvent-driven architecture
Main ideaEvents are the primary record of aggregate stateEvents communicate facts between components
Source of truthAppend-only streamCould be a current-state database
Main benefitHistory, audit and replayable projectionsLoose coupling and independent reactions
Required storageEvent store or append-only event tableAny event channel such as Service Bus or Event Grid
Can be used without the other?Yes, a stream can build local viewsYes, a service can publish events after a SQL update

Our data point platform can be event-driven without event sourcing: SQL Server remains the source of current state and it publishes PriceDataPointChanged. A fund reference-data service can use event sourcing internally while publishing integration events for other consumers. Choose each pattern for the problem it solves.

Must Consider: Do not publish every internal event as a public integration contract. Internal events can change with the aggregate model; integration events need a consumer-focused contract.

Practical decision checklist

Event sourcing is worth considering when,

  • The business needs a complete history of changes.
  • As-of queries and provider corrections are important.
  • Read models have different shapes and can be rebuilt.
  • The team can operate event storage, projections and schema migrations.
  • The event volume and retention cost are understood.

Use a simpler current-state table with an audit history when the domain only needs a small change log and no replayable aggregate behaviour. In our case, reference-data corrections and audit requirements may justify event sourcing for selected aggregates, while a high-volume derived price view may remain in a current-state store with its own event history.

Wrap up

In this article, we have looked at event sourcing, aggregate streams, Event Store, Marten, SQL Server append-only storage, expected-version appends, projections, checkpoints, rebuilds, snapshots, schema evolution and the difference between event sourcing and event-driven architecture. Across this series, we have travelled from integration styles and message anatomy to routing, reliability, events and historical state. I really appreciate that you took the time to read this article and the complete Enterprise Integration Patterns series. I hope these patterns provide you some practical guidance while designing the next integration flow.

Related Posts