Sub topic 9
Designing and versioning event schemas
This chapter assumes you know what events, producers, consumers and brokers are, and that you can read JSON and basic Python. It covers how to shape an event so many consumers can use it, and how to change that shape later without breaking them.
Why schemas are harder with events
In a request/response API, you can often update the server and client together. Events differ in two ways:
- The producer does not know its consumers. A topic may have five subscribers, and a sixth may appear next month. You cannot ask them all to upgrade on the same day.
- Old events can outlive the code. A broker may retain events for days or years. If events are replayed, a consumer must handle shapes written long ago.
An event schema is therefore a public contract. A change that looks harmless in the producer can crash a consumer you have never seen.
Anatomy of an event
Separate the event into an envelope and a payload. The envelope has the same fields on every event. The payload (data) is specific to the event type.
{
"id": "6f1c2d9e-3b7a-4c55-9d0e-1a2b3c4d5e6f",
"type": "order.placed",
"version": 1,
"occurredAt": "2026-11-26T11:00:00Z",
"data": {
"orderId": "o-1",
"customerId": "c-9",
"totalCents": 4599
}
}Each envelope field has a job:
| Field | Purpose |
|---|---|
| `id` | Unique per event. Consumers use it to detect duplicates. |
| `type` | Names the fact. Consumers route on it. |
| `version` | Identifies the payload schema, so consumers know how to read `data`. |
| `occurredAt` | When the fact happened, not when it was delivered. |
| `data` | The business details. |
Keep the envelope small and stable. Changing it affects every event type at once.
Design rules for a payload
Most compatibility problems come from early design choices. These rules help.
- Name events as past-tense facts.
order.placeddescribes something that happened.place.orderis a command and belongs in a different channel. - Use explicit types and units.
totalCents: 4599is clear.total: 45.99invites floating-point rounding errors. Use ISO 8601 UTC for timestamps. Include a currency code wherever an amount appears. - Use stable identifiers, not display values. Send
customerId, not a customer's name that may change. - Choose what to carry deliberately. If you use event-carried state transfer, include the data consumers need. If you use notification events, include only IDs. Either way, avoid leaking internal database columns. Consumers will start depending on them.
- Make optional things optional. A field that is absent in some events should be documented as optional, with a defined meaning for "missing".
- Do not reuse a field name with a new meaning. A field called
statusthat once meant payment status and now means shipping status will silently corrupt consumers. - Never put secrets or unnecessary personal data in events. Events are copied to many systems and retained for a long time, so deleting the data later is hard.
Compatibility: who must be able to read what
Compatibility describes which combinations of producer and consumer versions work together.
- Backward compatible: consumers on the new schema can read events written with the old schema. This matters for replay and for consumers that are upgraded first.
- Forward compatible: consumers on the old schema can read events written with the new schema. This matters when the producer is upgraded first.
- Full compatibility: both of the above.
Because producers and consumers deploy independently, aim for full compatibility on ordinary changes. Reserve incompatible changes for a deliberate migration.
The table below shows common changes and how they behave.
| Change | Safe for existing consumers? | Note |
|---|---|---|
| Add an optional field | Yes, if consumers ignore unknown fields | The most common change. |
| Add a required field | No for old events | Old events lack it, so give it a default or a new version. |
| Remove an optional field | Only if no consumer reads it | Hard to verify across unknown consumers. |
| Remove or rename a field | No | Treat as breaking. Add the new field first, then retire the old one later. |
| Change a field's type or unit | No | `totalCents` as an integer cannot silently become a string. |
| Change a field's meaning | No | Even if the type is the same, this is the worst case because it fails silently. |
| Add a new enum value | Risky | Consumers with a strict `switch` may fail. Document that enums can grow. |
The tolerant reader
The most useful consumer habit is to be a tolerant reader. A tolerant reader reads only the fields it needs, ignores fields it does not recognize, and does not fail on extra data. This makes additive changes safe.
Strict validation that rejects unknown fields makes every additive change a breaking change. Validate the fields you depend on, and nothing more.
def read_order_placed(event):
data = event["data"]
# Read only the fields this consumer needs. Extra fields are ignored.
return {
"order_id": data["orderId"],
"total_cents": data["totalCents"],
}
v1 = {"type": "order.placed", "version": 1,
"data": {"orderId": "o-1", "totalCents": 4599}}
v2 = {"type": "order.placed", "version": 2,
"data": {"orderId": "o-1", "totalCents": 4599, "currency": "EUR"}}
print(read_order_placed(v1))
print(read_order_placed(v2)) # same result: the new field is ignoredVersioning strategies
Even with additive changes, some changes cannot be made compatibly. You have three main options.
Version inside the event
Keep one event type and increase version when the payload changes. Consumers check version and handle each one they support. This works well when changes are small and consumers upgrade at different times.
Version in the type name
Publish a new type, such as order.placed.v2, possibly on a new topic. Old and new consumers are fully separated. The cost is that the producer may need to publish both types during a transition.
Upcasting
An upcaster converts an old event to the current shape before the handler sees it. The handler then only needs to understand the latest version. Upcasting is common when you replay history.
def upcast(event):
"""Convert order.placed v1 events to the v2 shape."""
if event["type"] == "order.placed" and event["version"] == 1:
data = {**event["data"], "currency": "USD"} # v1 was USD-only
return {**event, "version": 2, "data": data}
return event
def handle_order_placed(event):
event = upcast(event)
data = event["data"]
print(data["orderId"], data["totalCents"], data["currency"])
handle_order_placed({"type": "order.placed", "version": 1,
"data": {"orderId": "o-1", "totalCents": 4599}})
handle_order_placed({"type": "order.placed", "version": 2,
"data": {"orderId": "o-2", "totalCents": 1000,
"currency": "EUR"}})The default (USD) must be a real fact about the old data. If the old system could not have produced other currencies, the default is correct. If it is only a guess, the upcaster invents data.
Changing a field safely: expand and contract
To rename or replace a field without breaking anyone, use the expand and contract sequence:
- Expand. The producer emits both the old field and the new one. For example, send
totalandtotalCents. - Migrate. Consumers move to the new field at their own pace.
- Verify. Confirm that no consumer still reads the old field. Use consumer inventories, schema registry usage data, or logs.
- Contract. Stop emitting the old field. Remember that replayed old events will still contain it, so keep upcasters.
The long part is step 3. Plan for weeks or months, not a single release.
Schema formats and registries
JSON is readable but does not enforce a schema by itself. Formats such as Avro, Protocol Buffers and JSON Schema let you describe the structure formally. A schema registry stores the schemas, assigns versions, and checks each new schema against a compatibility rule before the producer may use it. Many teams run the check in CI so that a breaking change fails the build instead of failing a consumer in production.
Key points when choosing:
- Binary formats (Avro, Protocol Buffers) are compact and have defined evolution rules. For example, Protocol Buffers identify fields by number, so you must never reuse a number.
- JSON with JSON Schema is easier to debug but needs discipline to keep schemas and code in sync.
- Whatever you pick, record the compatibility mode (backward, forward or full) as a team decision and enforce it automatically.
Common errors
- Treating the schema as internal. The moment one consumer exists, it is a contract.
- Strict consumers. Rejecting unknown fields turns additive changes into outages.
- Forgetting replays. A change that is fine for new events can break a replay of old ones.
- Reusing a version number for a different shape. Versions must identify one shape only.
- Putting a whole database row in the event. Every column becomes part of the contract.
- No owner. Every event type needs a named team that approves changes.
Exercise
The payment.completed event, version 1, has the field amount as a decimal number such as 45.99. You want to change to integer cents and also support multiple currencies. Describe a safe rollout using expand and contract, and say what the old and new consumers each do during the transition.
Show answer
Expand: publish version 2 events that keep amount and add amountCents (integer) and currency. Old consumers ignore the new fields as tolerant readers and keep using amount. Migrate: update each consumer to read amountCents and currency, with an upcaster that turns version 1 events into the new shape by computing cents from amount and setting a currency only if the old system was single-currency. Verify: confirm that no consumer still reads amount, including replay jobs. Contract: stop emitting amount in a later version, and keep the upcaster for historical events that are still replayed.
Exercise
A consumer validates events against a schema that rejects any field not listed. The producer adds an optional couponCode field to order.placed. What happens, and what should the consumer do instead?
Show answer
The consumer rejects every new event as invalid, so an additive and otherwise safe change causes failures, and the events may end up retried or in a dead-letter queue. The consumer should be a tolerant reader: validate only the fields it depends on and ignore unknown ones.