Event replay in event-sourced and event-driven systems: rebuilding projections from the event store or a retained log, checkpoints and positions, blue-green projection rebuilds, separating projections from side-effect handlers, idempotent and deterministic handlers, and replay speed and ordering.
In an event-sourced system the event log is the source of truth and projections are disposable: you can drop a read model and replay every event to rebuild it. A projection stores a checkpoint (the last global position it processed), ideally in the same transaction as its read-model write, so a crash resumes exactly. To fix a bug or add a read model I rebuild side by side into a new table, let it catch up to live, then switch reads over.
The danger is side effects. Emails, payments and integration events must not fire again, so I keep reactors separate from projectors, or run handlers with replay suppressed. Every handler must be idempotent and deterministic: no DateTime.Now, no live lookups. The trade-off: replay gives you free rebuilds and new views of history, but only if you designed handlers for it from day one.
"In event sourcing, the event store is the truth and every read model is a cache derived from it. Replay means reading the events again from position zero, or from a known checkpoint, and running them through a projection. Each projection keeps a checkpoint: the global position of the last event it applied. I store that checkpoint in the same database transaction as the read-model update, so if the process dies we resume exactly where we stopped, without gaps or double counting. In .NET that might be Marten's async daemon over PostgreSQL, a KurrentDB (formerly EventStoreDB) catch-up subscription, or a hand-rolled projector reading an events table.
For example, at [company] we [had a projection bug that double-counted refunds in a customer balance view]. I didn't patch the table. I deployed the fixed projection writing to a new table,
CustomerBalance_v2, replayed [40 million] events at about [15,000 events a second], let it catch up to live, compared totals against the old table to confirm the only differences were the refunds, then switched the query to v2 behind a feature flag and dropped v1 a week later. Total rebuild time was [about 45 minutes] and readers never saw a half-built table.The mistake I see is mixing projections and side effects in one handler. If the handler that updates the balance view also sends the 'refund processed' email, a replay emails every customer again. So I split them: projectors only write read models and are safe to replay; reactors send emails, call payment providers or publish integration events, run only on live events, and dedupe by event id. And handlers must be deterministic: if a projection calls
DateTime.UtcNowor looks up today's tax rate, replay produces a different answer from the original. Replay is a superpower, but only for handlers that were written to be replayed."
| Projector | Reactor (process manager, policy) | |
|---|---|---|
| Purpose | Build a read model | Cause an effect outside the read model |
| Examples | Balance view, search index, report table | Send email, charge card, publish integration event |
| Safe to replay? | Yes, by design | No; must be suppressed or deduplicated |
| Checkpoint | Own checkpoint per projection | Own checkpoint; starts at "now" for new reactors |
| Determinism | Must use only event data | Can call external services (live only) |
Event store [0 ........................................ 40,000,000 โ live]
| |
Old projection v1 table (buggy) --------- serving reads ---------X dropped
New projection v2 table replay 0 โ 40M ---- catch up ---- switch reads โ v2
checkpoint stored in same tx
| Step | What I check |
|---|---|
| Deploy v2 projector writing to a new table | No impact on readers |
| Replay from position 0 with batching | Events per second, estimated finish time |
| Catch up to live | Lag (head position minus checkpoint) near zero |
| Compare v1 and v2 | Row counts, sums, a sample diff; differences explained by the bug |
| Switch reads (flag or view swap) | Error rates and latency |
| Drop v1 after a soak period | Rollback window has passed |
| Source | Replay? | Notes |
|---|---|---|
| Event store (Marten, KurrentDB, SQL events table) | Yes, the whole history | Designed for it |
| Kafka topic | Within retention, or forever with compaction (latest per key only) | Reset consumer group offsets or use a new group |
| Azure Event Hubs | Within retention (days, longer on higher tiers or with Capture) | Read from an offset or a timestamp |
| Azure Service Bus queue or topic | No, consumed messages are gone | Keep an event store or archive if you need replay |
A customer-balance projection over [40 million] events rebuilt in about 45 minutes after switching from per-event SaveChanges (about 900 events a second) to batches of 1,000 with the checkpoint in the same transaction (about 15,000 events a second). The comparison step found [3,100] balances that differed, all explained by the refund bug, and no customer emails were sent because the email reactor wasn't part of the rebuild.
Checks whether the candidate can rebuild read models safely in production and understands the determinism and side-effect rules that make replay possible.
Green flags
Red flags
Event sourcing stores facts (OrderPlaced, PaymentRefunded) in append-only streams, one per aggregate, with a per-stream version and usually a global position across all streams. Current state is a left fold:
state = events.Aggregate(initial, (s, e) => s.Apply(e))
A projection is the same fold, written into a table shaped for reading. Because the fold is a pure function of the events, you can run it again at any time and get the same result, as long as the function is pure.
The event store delivers at-least-once to a projection: a crash after writing the read model but before saving the checkpoint replays the last batch. Two ways to make that safe:
Option A: atomic checkpoint (preferred when read model and checkpoint share a database)
BEGIN TRAN
UPDATE read model for events 1001..2000
UPDATE ProjectionCheckpoints SET Position = 2000 WHERE Name = 'balances'
COMMIT
Option B: idempotent writes (read model in a different store, e.g. Elasticsearch)
upsert document with version = event's stream version; ignore older versions
Option A gives effectively-once updates to the read model. Option B tolerates duplicates by making each write idempotent.
Within one stream, order is guaranteed by the stream version. Across streams, order is whatever the store's global position says. Marten's async daemon processes up to a "high water mark" so it doesn't skip events from transactions that committed out of order; a hand-rolled SQL events table with an identity column can have gaps that later fill (a transaction with a lower id commits after a higher one), so a naive "read where id > checkpoint" projector can skip events. Fix it by reading only up to a safe position (e.g. events older than a few seconds) or using the store's own subscription mechanism.
A projection must compute only from the event. Common breaks:
| Non-deterministic input | Replay result | Fix |
|---|---|---|
DateTime.UtcNow |
Every row gets today's date | Use the event's recorded timestamp |
| Live lookup (tax rate, exchange rate, user name) | Today's value applied to old events | Put the value in the event when it happens, or project the lookup data from its own events |
Guid.NewGuid() for read-model ids |
New ids each rebuild, broken links | Derive ids from stream id and version |
| Configuration flags | Behaviour depends on when you replay | Version the projection instead |
Reactors subscribe to live events. When a new reactor is deployed it should usually start at the current head, not at position 0, or it will act on years of history. If a single handler must do both, pass a replay flag and skip effects, but separation is cleaner. Integration events published from a reactor carry the source event id so downstream consumers can deduplicate if a reactor does re-run.
Rebuild time = events รท throughput. Per-event round trips cap you at hundreds of events a second. Batch reads (page through the event store), batch writes (one SaveChanges or SqlBulkCopy per batch), disable change tracking where possible, and build indexes after the bulk load. For very large stores, partition the rebuild by stream id across workers when the projection doesn't need cross-stream order.
Events table (global position, stream id, version, type, JSON payload) and a balance projection; replay 1 million synthetic events with per-event saves, then with batches of 1,000, and compare events per second.DateTime.UtcNow to a projection, rebuild, and observe all dates changing.A replay-safe projector: batched, checkpoint in the same transaction, deterministic, and no side effects.
namespace Balances.Projections;
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
public sealed record StoredEvent(long Position, Guid StreamId, string Type, string Payload, DateTimeOffset OccurredAt);
public sealed record FundsDeposited(Guid AccountId, decimal Amount);
public sealed record FundsRefunded(Guid AccountId, decimal Amount);
public sealed class AccountBalance
{
public Guid AccountId { get; init; }
public decimal Balance { get; set; }
public DateTimeOffset LastChangedAt { get; set; } // from the event, never DateTime.UtcNow
}
public sealed class Checkpoint
{
public required string Name { get; init; }
public long Position { get; set; }
}
public sealed class BalanceProjector(IDbContextFactory<ReadDb> dbFactory, IEventReader events)
{
private const string Name = "account-balance-v2"; // new name = new table + new checkpoint
public async Task RunAsync(CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
await using var db = await dbFactory.CreateDbContextAsync(ct);
var cp = await db.Checkpoints.FindAsync([Name], ct) ?? db.Checkpoints.Add(new Checkpoint { Name = Name }).Entity;
var batch = await events.ReadAfterAsync(cp.Position, max: 1_000, ct);
if (batch.Count == 0) { await Task.Delay(TimeSpan.FromMilliseconds(500), ct); continue; }
foreach (var e in batch)
await ApplyAsync(db, e, ct);
cp.Position = batch[^1].Position;
await db.SaveChangesAsync(ct); // read model + checkpoint commit together
}
}
private static async Task ApplyAsync(ReadDb db, StoredEvent e, CancellationToken ct)
{
(Guid id, decimal delta) = e.Type switch
{
nameof(FundsDeposited) => Read<FundsDeposited>(e) is var d ? (d.AccountId, d.Amount) : default,
nameof(FundsRefunded) => Read<FundsRefunded>(e) is var r ? (r.AccountId, -r.Amount) : default,
_ => (Guid.Empty, 0m) // unknown types are skipped, not fatal
};
if (id == Guid.Empty) return;
var row = db.Balances.Local.FirstOrDefault(b => b.AccountId == id)
?? await db.Balances.FindAsync([id], ct)
?? db.Balances.Add(new AccountBalance { AccountId = id }).Entity;
row.Balance += delta;
row.LastChangedAt = e.OccurredAt;
}
private static T Read<T>(StoredEvent e) => JsonSerializer.Deserialize<T>(e.Payload)!;
}
public interface IEventReader
{
// Must only return events up to a safe high-water mark so late commits aren't skipped.
Task<IReadOnlyList<StoredEvent>> ReadAfterAsync(long position, int max, CancellationToken ct);
}
public sealed class ReadDb(DbContextOptions<ReadDb> options) : DbContext(options)
{
public DbSet<AccountBalance> Balances => Set<AccountBalance>();
public DbSet<Checkpoint> Checkpoints => Set<Checkpoint>();
protected override void OnModelCreating(ModelBuilder b)
{
b.Entity<AccountBalance>().ToTable("AccountBalance_v2").HasKey(x => x.AccountId);
b.Entity<Checkpoint>().HasKey(x => x.Name);
}
}
DateTime.UtcNow or live lookups inside projections. Why it is wrong: Replay produces different data from the original run. Instead: Use event timestamps and data captured in the event.WHERE Id > @checkpoint. Why it is wrong: Concurrent transactions commit out of order, so late commits with lower ids are skipped forever. Instead: Read up to a safe high-water mark or use the event store's subscription.SaveChanges during a rebuild. Why it is wrong: Round trips cap throughput at hundreds of events a second, turning a rebuild into days. Instead: Batch reads and writes and measure events per second.Replay is the main return on the cost of event sourcing, so I design for it from the first projection: deterministic handlers, versioned projection names, checkpoints committed with the data, and a hard line between projectors and reactors. I also plan replay as an operation, with a runbook: estimated time (events รท measured throughput), how we compare old and new, how we switch and how we roll back.
The less obvious point is that replay isn't only for event-sourced systems. Any system that keeps an ordered log with enough retention (Kafka, Event Hubs, an archive of integration events) can rebuild downstream views. If replay is a requirement, it decides the platform: Service Bus is a great work queue but cannot replay consumed messages.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Rebuild side by side, then switch | Bug fixes, new projections, schema changes | Double storage during rebuild | Tiny projections where a brief gap is acceptable |
| Rebuild in place | Dev and test, or internal tools | Readers see partial data | Customer-facing views |
| Patch data with SQL | One-off, well-understood corruption | Read model diverges from what replay would produce | When the projection code still has the bug |
| Partial replay from a position | Bug introduced at a known date | Must know the earlier state was correct | When the bug's start is uncertain |
| Metric | Why |
|---|---|
| Projection lag (head position โ checkpoint) | Freshness of reads |
| Replay events per second | Rebuild time estimate |
| Old vs new diff count | Proof the fix changes only what it should |
Event sourcing stores every state change as an immutable event in an append-only stream per aggregate, and derives current state by replaying those events. The event log is the source of truth; tables you query are projections built from it. Appends use the expected stream version for optimistic concurrency. Snapshots speed up replay for long streams, and events are evolved by additive changes and upcasting, never by editing history.
It's worth it when the history itself is valuable: audit, temporal queries ("what did we know on 1 July?"), complex behaviour. It's a poor fit for CRUD and for teams new to it, because you pay in eventual consistency, schema evolution and harder queries.
With at-least-once delivery, duplicates are normal: outbox resends, peek-lock redelivery after a crash or lock expiry, and publisher retries. An idempotent consumer makes processing a message twice have the same effect as once.
The inbox is an InboxMessages table with a primary key on (MessageId, Consumer). For each message, in one EF Core transaction:
If the insert fails with SQL error 2627/2601, the message was already processed, so complete it. A concurrent duplicate blocks on the key lock until the first commits, then fails the insert. If the first rolls back, the duplicate goes ahead.
Purge old rows past the redelivery window. The trade-off is an extra write and table per consumer against correct exactly-once processing.
A Kafka topic is a set of partitions, each an append-only log ordered by offset. Many producers write and many consumer groups read at once. Records are retained by time or size, or by compaction, which keeps only the latest record per key. In a consumer group, each partition goes to one member, so partitions cap parallelism.
The consumer commits offsets, meaning "everything before this is done". Confluent.Kafka's defaults store offsets on consume and auto-commit, which can skip records on a crash. The safe pattern is EnableAutoOffsetStore = false with StoreOffset after processing. That gives at-least-once: a crash or rebalance replays uncommitted records, so handlers must be idempotent.
Lag comes from slow handlers, too few partitions, hot keys or rebalance storms. There is no built-in DLQ. The trade-off: high throughput and replay, but the consumer owns retries, dead-lettering and offset discipline.
How to tell it (STAR)
**S:** At [company], a release double-applied refunds in our balance projection and [3,100] customers saw inflated balances. **T:** I owned the fix and the rebuild. **A:** Before replaying I checked what else would run, and found the same handler published the event that sends refund emails, so a naive replay would have emailed every customer who ever had a refund. I split it into a projector and a reactor, rebuilt into a new table side by side with the checkpoint in the same transaction, compared old and new to confirm only the refund accounts changed, and switched reads behind a flag. **R:** The rebuild took [about 45 minutes], mismatches went to zero, and no customer received a duplicate email.
Last updated 23 Nov 2026.