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

📚 Interview question

Events are stored for years and read by consumers you don't control, but the event shapes keep changing. How do you version events? Explain additive (weak-schema) changes, upcasting old events when they are read, new event types for breaking changes, schema registries and their compatibility modes, and how you keep old consumers working during a rollout.

Event versioning for event stores and integration events: weak-schema tolerant readers, upcasting chains at read time, new event types and parallel publishing for breaking changes, copy-and-transform migrations, schema registries (Confluent, Azure Schema Registry) with backward, forward and full compatibility, and System.Text.Json behaviour.

Senior Theory Advanced data-consistency distributed-systems event-sourcing event-versioning schema-registry upcasting

🎯 Key points

  • Events are immutable facts: never rewrite stored events in place as a first option
  • Weak schema / tolerant reader: add optional fields only, ignore unknown fields, give missing fields safe defaults
  • Upcasting: transform v1 JSON into the current shape at read time, as a chain v1 → v2 → v3, so domain code sees one version
  • Breaking change = new event type (OrderPlacedV2), published in parallel until consumers move
  • Schema registry compatibility: BACKWARD (upgrade consumers first), FORWARD (upgrade producers first), FULL (either order)
  • System.Text.Json: unknown properties ignored by default, but C# required members throw when an old event lacks them
  • Copy-and-transform migration into a new stream or store as the last resort, with replay and comparison
  • Contract tests and a registry check in CI stop breaking schemas before they ship

⏱ 30-second answer

Stored events are immutable facts, so I version them without rewriting history. Most changes are additive under a weak schema: add optional fields, never rename or remove, and make readers tolerant (ignore unknown fields, default missing ones). When the shape really changes, I upcast: a chain of small functions turns v1 JSON into v2 and then v3 at read time, so domain code only knows the latest shape. A change in meaning gets a new event type, published in parallel while consumers move.

For integration events across teams, a schema registry (Confluent, or Azure Schema Registry in Event Hubs) enforces backward, forward or full compatibility in CI. The trade-off: every version you keep readable is code you maintain forever, so I prefer additive changes and only break when the business meaning changed.

🗣 Full answer (senior)

How I would answer this in an interview

"Events are facts that already happened, and in an event store they're the source of truth, so I don't edit them. That means the code has to read every version that was ever written. My first tool is a weak schema: changes are additive. I add optional fields with safe defaults and never rename, remove or change the type of an existing one. Readers are tolerant: System.Text.Json ignores unknown properties by default, so an old consumer reading a newer event is fine. The trap is the other direction: if I add a C# required property, deserialising an old event without that field throws, and suddenly I can't load aggregates from 2023.

When the shape genuinely changes, say CustomerName is split into GivenName and FamilyName, I write an upcaster: a function from the old JSON to the new shape that runs when the event is read. Upcasters chain, v1 to v2 to v3, so each one is small and tested on its own, and the aggregate and projections only see the current version. Marten supports upcasting out of the box; with KurrentDB or a SQL events table I put it in the deserialiser. When the meaning changes, for example OrderPlaced now means 'placed and paid', that isn't a version, it's a new event type. I publish both for a while, move consumers, then stop the old one.

For integration events going to other teams, I'd use a schema registry with a compatibility rule checked in CI. For example, at [company] we [had a producer rename a field in a Kafka topic and three consumers failed overnight]. We moved to [Confluent Schema Registry / Azure Schema Registry] with BACKWARD_TRANSITIVE compatibility, and the next breaking change was rejected by the build instead of production. The mistake I see is treating events like DTOs that can change with each release. An event schema is a public contract with a very long life."


Types of change and how to handle them

Change Safe? Technique
Add optional field with default Yes Weak schema; old readers ignore it, new readers default it
Add field the domain needs for old events Needs work Upcaster supplies a derived or default value
Rename field Breaking Upcaster maps old name to new; or add new, keep old
Split or merge fields Breaking Upcaster
Change type (int → decimal, string → enum) Breaking Upcaster or new event type
Change meaning Breaking New event type, published in parallel
Remove field Breaking for consumers that read it Deprecate, keep publishing until consumers stop reading it

Schema registry compatibility modes

Mode Guarantee Deployment order
BACKWARD (Confluent default) New schema can read data written with the previous schema Upgrade consumers first
FORWARD Previous schema can read data written with the new schema Upgrade producers first
FULL Both Either order
*_TRANSITIVE Check against all earlier versions, not just the last Needed when data is retained or replayed for a long time
NONE No check Avoid for shared topics

Where versioning happens

Event store / topic           Read path                          Domain
[v1 JSON] ----\
[v2 JSON] -----+--> deserialise --> upcast v1→v2→v3 --> OrderPlaced (v3 record)
[v3 JSON] ----/        (type + version from metadata)

Production example

An order event store had [11 million] OrderPlaced events across three versions. Upcasting v1 and v2 at read time added under 5 microseconds per event, measured with BenchmarkDotNet, and removed the need for a [12-hour] copy-and-transform migration. The registry's transitive check rejected [two] breaking pull requests in the following quarter.

🔍 What the interviewer is checking

Checks whether the candidate treats events as long-lived contracts and knows the concrete techniques and compatibility rules for changing them safely.

Green flags

  • Prefers additive changes and tolerant readers, and knows the required trap
  • Explains upcasting at read time as a tested, pure chain
  • Distinguishes a changed shape from a changed meaning
  • Knows backward versus forward compatibility and the deployment order each implies

Red flags

  • Proposes updating stored events with SQL as the normal fix
  • Shares one event-class package across services and upgrades in lockstep
  • Can't say which side deploys first for a given compatibility mode

📚 Learn in depth

1. Why events need different versioning from APIs

An HTTP API can retire v1 after consumers move. Events don't retire: an event-sourced aggregate loads its whole stream, and a projection rebuild reads every event ever written. Integration events in Kafka or Event Hubs may be replayed from retention. So every version must stay readable for as long as data of that version exists.

2. Weak schema and the tolerant reader

A weak schema means the reader maps what it recognises and tolerates the rest. With System.Text.Json:

Situation Default behaviour Gotcha
JSON has a property the type lacks Ignored JsonUnmappedMemberHandling.Disallow (opt-in) makes it throw
Type has a property the JSON lacks Default value (null, 0) C# required members or [JsonRequired] throw JsonException
Enum value unknown to the reader Throws when reading enums as strings Map unknown values to an Unknown member with a custom converter
Property renamed Silently defaulted Upcaster or [JsonPropertyName] for the old name

3. Upcasting

An upcaster is a pure function JsonNode -> JsonNode that takes a document of version n to n + 1. The store records the event type and schema version in metadata, so the read path knows where to start.

read {type: "OrderPlaced", version: 1, data: {...}}
  -> V1ToV2: rename "customerName" to "customer": {"name": ...}
  -> V2ToV3: add "currency": "AUD" (all v2 orders were Australian)
  -> deserialise as OrderPlaced (current record)

Rules: upcasters are pure (no database or clock), each tested with a stored sample of the old JSON, and the chain is ordered by version. Writes always use the latest version. Defaults must be true for the old data: adding currency = "AUD" is only correct if every v2 order really was in AUD.

4. New event types for changed meaning

If OrderPlaced used to be emitted before payment and is now emitted after payment, an upcaster can't fix consumers that react to it. Create OrderPlacedAndPaid (or OrderPlaced v2 as a new contract), publish both during migration, let consumers switch, then stop the old one. In an event store, aggregates keep handling both types for old streams.

5. Copy and transform

The heaviest option: read the old stream or store, transform each event, write to a new stream or store, then switch. It's useful for removing personal data (Privacy Act deletion requests where crypto-shredding isn't in place) or collapsing years of upcasters. It needs replay, comparison and a cut-over plan, like a projection rebuild.

6. Schema registries

Confluent Schema Registry stores Avro, Protobuf and JSON Schema per subject (usually per topic) and enforces a compatibility mode on registration. Azure Schema Registry (part of Event Hubs) stores Avro, JSON Schema and Protobuf schemas in groups with similar compatibility settings, and the .NET client libraries can serialise against it. In both, CI registers or checks the schema before deploy, so an incompatible change fails the build.

Try it yourself

  1. Serialise a v1 record, add a required property to the type, and deserialise the old JSON to see the exception.
  2. Write V1ToV2 and V2ToV3 upcasters over JsonNode, with xUnit tests using real stored samples.
  3. Benchmark deserialisation with and without the upcast chain using BenchmarkDotNet for 1 million events.
  4. Run Confluent Schema Registry in Docker, register a schema under BACKWARD, then try registering one with a renamed field.
  5. Make an enum converter that maps unknown values to Unknown and test it with a future value.

💻 Code

An upcasting chain over JsonNode: writes use the latest version, reads upgrade old events before deserialising.

namespace Orders.Events;

using System.Text.Json;
using System.Text.Json.Nodes;

// Current shape. No 'required' on fields added after v1, or old events would fail to load.
public sealed record CustomerRef(string Name, string? Email);
public sealed record OrderPlaced(Guid OrderId, CustomerRef Customer, decimal Total, string Currency);

public interface IUpcaster
{
    string EventType { get; }
    int FromVersion { get; }
    JsonObject Upcast(JsonObject data); // pure: no clock, no database
}

public sealed class OrderPlacedV1ToV2 : IUpcaster
{
    public string EventType => nameof(OrderPlaced);
    public int FromVersion => 1;

    // v1 had a flat "customerName"; v2 nests it under "customer".
    public JsonObject Upcast(JsonObject data)
    {
        var name = data["customerName"]?.GetValue<string>() ?? "(unknown)";
        data.Remove("customerName");
        data["customer"] = new JsonObject { ["name"] = name, ["email"] = null };
        return data;
    }
}

public sealed class OrderPlacedV2ToV3 : IUpcaster
{
    public string EventType => nameof(OrderPlaced);
    public int FromVersion => 2;

    // Every order before v3 was taken in Australia, so AUD is TRUE for old data, not a guess.
    public JsonObject Upcast(JsonObject data)
    {
        data["currency"] ??= "AUD";
        return data;
    }
}

public sealed class EventDeserializer(IEnumerable<IUpcaster> upcasters)
{
    public const int CurrentVersion = 3;
    private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);

    private readonly Dictionary<(string, int), IUpcaster> _chain =
        upcasters.ToDictionary(u => (u.EventType, u.FromVersion));

    public T Read<T>(string eventType, int version, string payload)
    {
        var data = JsonNode.Parse(payload)!.AsObject();
        for (var v = version; v < CurrentVersion; v++)
        {
            if (!_chain.TryGetValue((eventType, v), out var up))
                throw new InvalidOperationException($"No upcaster for {eventType} v{v}");
            data = up.Upcast(data);
        }
        return data.Deserialize<T>(Json)!;
    }
}
// Program.cs: register the chain once; every reader (aggregates, projections) shares it.
builder.Services.AddSingleton<IUpcaster, OrderPlacedV1ToV2>();
builder.Services.AddSingleton<IUpcaster, OrderPlacedV2ToV3>();
builder.Services.AddSingleton<EventDeserializer>();

⚠ Common mistakes

  • Mistake: Updating stored events in place with a SQL script. Why it is wrong: It destroys the audit trail, can't be undone, and breaks consumers that already processed the old shape. Instead: Upcast at read time, or copy and transform into a new stream with a cut-over plan.
  • Mistake: Adding a required property to an event record. Why it is wrong: System.Text.Json throws when old events lack it, so aggregates and rebuilds fail. Instead: Make new fields optional with defaults, or supply them in an upcaster.
  • Mistake: Renaming a field because the new name is clearer. Why it is wrong: Old events and old consumers silently get default values. Instead: Keep the old name, or add the new field and upcast.
  • Mistake: Using an upcaster for a change in meaning. Why it is wrong: Consumers react to the event's meaning; reshaping JSON can't change when it was emitted. Instead: Introduce a new event type and publish both during migration.
  • Mistake: Defaults in upcasters that aren't true for the old data. Why it is wrong: You invent history (for example AUD for orders that were in NZD). Instead: Derive values from the old event or other recorded facts, or use an explicit Unknown.
  • Mistake: Sharing one NuGet package of event classes across all services and bumping it each release. Why it is wrong: Every consumer must upgrade in lockstep, which is a distributed monolith. Instead: Publish schemas, let consumers own their own types, and check compatibility in a registry.
  • Mistake: Schema registry set to BACKWARD when data is replayed from long retention. Why it is wrong: Only the last version is checked, so a consumer may not read data from three versions ago. Instead: Use a transitive mode.

🏛 Senior insight: trade-offs

Event versioning is a cost you pay forever, so I minimise the number of versions rather than make versioning clever. Most of the time a weak schema is enough. Upcasters are for real reshaping, new types are for changed meaning, and copy-and-transform is the rare reset, often driven by privacy requirements (an Australian Privacy Act deletion request is easier if personal data lives outside the event, referenced by id, or is crypto-shredded).

For integration events I separate the internal event (what the aggregate stored) from the published contract, so internal refactoring doesn't break other teams. The contract is versioned and checked by a registry or a contract test (Pact or a schema snapshot test) in CI, and every upcaster has a unit test against a stored sample of the old JSON. On format: Avro and Protobuf make compatibility mechanical (Avro resolves reader and writer schemas with defaults; Protobuf uses field numbers, so renames are free and removed numbers are reserved), and they're compact on high-volume topics. JSON Schema is easier to read and debug but has looser compatibility checking, so I'd choose Avro or Protobuf for high-volume Kafka or Event Hubs topics shared across teams, and JSON for low-volume Service Bus events.

Option When it fits Cost When not to
Weak schema (additive) Most changes Fields accumulate Changes in meaning
Upcaster chain Reshaping stored events A small pure function per step, forever Meaning changed, or chain grows beyond a handful
New event type Meaning changed Consumers must migrate; both types handled for old streams Pure reshaping
Copy and transform Privacy deletion, collapsing old versions Migration project with replay and cut-over Routine changes
Schema registry Cross-team topics on Kafka or Event Hubs Extra service and CI step Single-team, in-process events

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions integration event contracts or CloudEvents Why: Checks contract ownership and evolution for integration events
    How to answer

    An integration event is a public API owned by the publisher. Within a version I only make backward-compatible changes: add optional (nullable or defaulted) fields. I never add a required field mid-version (messages already in queues won't have it), and never rename, remove or retype. Consumers are tolerant readers: they ignore unknown fields and default missing optional ones. A breaking change becomes a new event type (orders.order-placed.v2), published alongside v1 until consumers move, then deprecated with a date.

    I wrap events in a CloudEvents envelope (id, source, type, time, dataschema). Each publisher ships its own contracts package or JSON Schema; one shared events library for every service forces lockstep upgrades.

    The trade-off: discipline and some duplication in exchange for independent deployments.

  2. When: Candidate mentions event stores or loading aggregates from events Why: Checks event-sourcing basics behind stored event versions
    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.

  3. When: Candidate mentions replaying old events through new code Why: Checks rebuilding projections after an event shape change
    How to 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.

🛠 Real-world problems: how you handle them

Aggregates fail to load after a 'required' field was added
Situation
An event-sourced policy service ([KurrentDB / SQL events table], [6 million] events since [2021]) for an insurer. A release added `required string Channel` to the PolicyIssued event record.
Signals
After deploy, [12%] of policy loads returned 500 with JsonException 'missing required properties', only for policies issued before the release; projection rebuilds in staging failed at the first old event.
Investigation
Application Insights exceptions grouped by event type and version showed every failure was a v1 PolicyIssued. Reproduced locally by deserialising a stored v1 sample into the new record. Git history showed the required modifier was added in the release.
Resolution
Immediate: rolled back the release. Real fix: made Channel optional on the record, added a V1ToV2 upcaster setting Channel to "Unknown" (true for old data, which never recorded it), wrote events as v2 from then on, and added stored samples of every version to the test suite.
Prevention
A test that deserialises a stored sample of every event version on every build, a code review rule against required on event records after v1, and an ADR describing additive changes, upcasters and new types.

How to tell it (STAR)

**S:** At [company], a release made [12%] of policies fail to load. All of them were issued before that day. **T:** I was on call and then owned the fix. **A:** The exceptions all came from old PolicyIssued events, and a new required property was the cause: old events didn't have it, so deserialisation threw. I rolled back, made the field optional, added an upcaster that sets Unknown for old events, and added tests that load a stored sample of every event version on each build. **R:** Loads went back to [0] failures, and the sample tests have since caught [two] more breaking changes before they shipped.

More in Data Consistency

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me