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.
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.
"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#
requiredproperty, deserialising an old event without that field throws, and suddenly I can't load aggregates from 2023.When the shape genuinely changes, say
CustomerNameis split intoGivenNameandFamilyName, 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 exampleOrderPlacednow 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."
| 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 |
| 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 |
Event store / topic Read path Domain
[v1 JSON] ----\
[v2 JSON] -----+--> deserialise --> upcast v1→v2→v3 --> OrderPlaced (v3 record)
[v3 JSON] ----/ (type + version from metadata)
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.
Checks whether the candidate treats events as long-lived contracts and knows the concrete techniques and compatibility rules for changing them safely.
Green flags
required trapRed flags
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.
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 |
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.
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.
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.
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.
required property to the type, and deserialise the old JSON to see the exception.JsonNode, with xUnit tests using real stored samples.Unknown and test it with a future value.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>();
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.Unknown.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 |
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.
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.
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.
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.
Last updated 23 Nov 2026.