📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

๐Ÿ“š Interview question

Your event-sourced system needs a new read model, and an existing projection has a bug that corrupted its data. How do you replay events to rebuild projections? Explain checkpoints, rebuilding side by side and switching over, what happens to side effects such as emails and integration events during a replay, and why handlers must be idempotent.

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.

Senior Theory Advanced data-consistency distributed-systems event-replay event-sourcing idempotency projections

๐ŸŽฏ Key points

  • Projections are disposable: derived from the event log, so they can be dropped and rebuilt
  • Each projection has its own named checkpoint (global position), committed in the same transaction as its read-model write
  • Rebuild side by side into a new table or index, catch up to live, then switch reads and drop the old one
  • Side effects (emails, payments, integration events) must not re-run: separate reactors from projectors or suppress them in replay mode
  • Handlers must be idempotent and deterministic: no DateTime.Now, no external lookups, use event data and event timestamps
  • Ordering: per-stream order is guaranteed; cross-stream order depends on the store's global position and high-water mark
  • Replay throughput: batches of about 500-5,000 events per transaction, bounded memory, indexes built after the load; measure events per second
  • Replay depends on retention: event store or Kafka/Event Hubs retention; Service Bus deletes completed messages and cannot replay

โฑ 30-second answer

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.

๐Ÿ—ฃ Full answer (senior)

How I would answer this in an interview

"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.UtcNow or 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."


Projectors versus reactors

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)

Rebuild side by side

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

What can replay and what can't

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

Production example

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.

๐Ÿ” What the interviewer is checking

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

  • Stores the checkpoint atomically with the read model, or uses idempotent versioned writes
  • Rebuilds side by side and switches, with a comparison step
  • Separates projectors from reactors and explains why
  • Mentions deterministic handlers and out-of-order commits in SQL event tables

Red flags

  • Truncates the live table and replays in place for customer-facing views
  • Doesn't consider emails or payments firing again
  • Assumes any broker can replay history

๐Ÿ“š Learn in depth

1. Why replay is possible

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.

2. Checkpoints and exactly-once effects on the read model

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.

3. Ordering

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.

4. Determinism

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

5. Side effects during replay

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.

6. Speed

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.

Try it yourself

  1. Create an 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.
  2. Kill the projector mid-batch with and without the checkpoint in the same transaction and compare the resulting balances.
  3. Insert two events in overlapping transactions so the higher identity commits first, and show the naive projector skipping the lower one.
  4. Add DateTime.UtcNow to a projection, rebuild, and observe all dates changing.
  5. With Marten, run a projection rebuild through the async daemon and watch the high water mark and progress.

๐Ÿ’ป Code

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);
    }
}

โš  Common mistakes

  • Mistake: Sending emails or publishing integration events from the same handler that updates a projection. Why it is wrong: A rebuild replays every side effect, so customers get years of emails again. Instead: Separate projectors (replayable) from reactors (live only, deduplicated by event id).
  • Mistake: Saving the checkpoint in a separate transaction from the read-model write. Why it is wrong: A crash between them either skips events or applies them twice, corrupting counters and sums. Instead: Commit both together, or make each write idempotent with the stream version.
  • Mistake: Using 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.
  • Mistake: Rebuilding in place by truncating the live table. Why it is wrong: Readers see empty or partial data for the whole rebuild. Instead: Rebuild into a new table, catch up, compare, then switch.
  • Mistake: Reading a SQL identity-based events table with 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.
  • Mistake: Starting a new reactor from position 0. Why it is wrong: It acts on all historical events, for example charging or notifying for old orders. Instead: Start new reactors at the current head unless backfill is explicitly wanted.
  • Mistake: Assuming Service Bus can replay. Why it is wrong: Completed messages are deleted; there is no history. Instead: Keep an event store, Event Hubs or Kafka with suitable retention, or an archive, if replay is a requirement.
  • Mistake: Per-event 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.

๐Ÿ› Senior insight: trade-offs

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

๐Ÿ”— Follow-ups the interviewer may ask

  1. When: Candidate mentions event stores, snapshots or projections Why: Checks the event-sourcing fundamentals behind replay
    How to answer

    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.

  2. When: Candidate says side-effect handlers deduplicate by event id Why: Checks how reactors deduplicate when they do run twice
    How to answer

    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:

    1. Insert the inbox row first.
    2. Apply the business change.
    3. Commit, then complete the Service Bus message.

    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.

  3. When: Candidate mentions resetting Kafka offsets or retention to replay Why: Checks replay from a log with offsets and retention
    How to answer

    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.

๐Ÿ›  Real-world problems: how you handle them

Rebuilding a corrupted balance projection without re-emailing customers
Situation
A wallet product with an event-sourced Accounts service ([Marten on PostgreSQL / a SQL events table], [40 million] events, [600,000] customers). A projection bug double-applied refunds in the balance view shown in the app.
Signals
Support tickets about inflated balances, a nightly reconciliation between the ledger fold and the balance view reporting [3,100] mismatches, all on accounts with refunds after the [date] release.
Investigation
Folded the event streams of a sample of affected accounts in a test harness and compared with the view, which pinned the bug to the refund handler. Checked which handlers would run during a rebuild and found the refund handler also published a RefundProcessed integration event that triggered emails.
Resolution
Immediate: hid the balance view behind a 'balance updating' banner for affected accounts and served the ledger fold for them. Real fix: split the handler into a projector and a reactor, deployed the fixed projector writing to AccountBalance_v2 with the checkpoint in the same transaction, replayed at [about 15,000] events a second, compared v1 and v2, switched reads with a feature flag, and dropped v1 after a week.
Prevention
An architecture test that fails if a projector type references email, messaging or HTTP clients; a projection lag alert; the nightly reconciliation kept as a permanent check; and a rebuild runbook with time estimates.

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.

โ†ฉ Usually asked after

More in Data Consistency

Last updated 23 Nov 2026.

๐ŸŒ Sangam's Webring

โช Previous ๐Ÿ  Main Next โฉ
๐Ÿ’ฌ Chat with me