Schema evolution and encoding
Change the shape of your data so that old code can read new data, and new code can read old data, while both run at once.
Updated since you finished it. We changed this lesson after you marked it done. Your progress is kept.
What broke
On 19 July 2024, Windows machines running CrowdStrike's Falcon sensor crashed. The cause was not new code. It was new data that the sensor code could not safely read. 1
In February 2024, sensor version 7.11 added a new template type for IPC (named pipes). Content files for it arrive from the cloud as Channel File 291. 1
Both parts were built at the same time, and they disagreed from day one. The template's definition said each check had 21 input fields. The sensor code supplied only 20. 1
For months, nobody noticed. The tests and the first live content used a wildcard for the 21st field, so the sensor never had to look at it. 1
Then two new content entries were sent. One had a real value for the 21st field. The content validator approved it, because it also assumed 21 inputs. The sensor tried to read input 21 from an array of 20. That out-of-bounds read crashed the system. 1
The data and the code that read it disagreed about the shape, and the code did not check the array size. Among its fixes, CrowdStrike now checks the number of fields when it builds the sensor. It also added a bounds check that runs on the machine. 1 This lesson is about that gap between writer and reader, and how data formats help you close it.
The idea in simple words
Every time you send or store data, you encode it into bytes. Later, some other code decodes it. That other code may be older or newer than the code that wrote it.
This happens all the time, not only in rare cases:
- Rolling deploys. Kubernetes scales up the new pods while it scales down the old ones. 2 For a few minutes, v1 and v2 talk to each other.
- Messages in a queue or log. A message written yesterday by v1 is read today by v2. In a log, it may be read again in a year.
- Stored data. A database row or a file written three years ago is still read by today's code.
So you need two promises:
- Backward compatibility: new code can read data written by old code.
- Forward compatibility: old code can read data written by new code.
Forward is the harder one. Old code cannot know what you will add later. So it must be built to skip what it does not know.
The key idea. Old and new code always overlap. Change your data so both can read it: add optional fields, never change the meaning of an existing one, and never reuse an old name or number.
How it works
JSON: no schema, so the rules live in your code
JSON carries field names, so a reader can find fields in any order. But nothing checks the shape. Two habits keep JSON safe:
- Ignore unknown fields. Then new fields do not break old readers. Some parsers reject them by default. ProtoJSON parsers do, for example. 7 Check yours.
- Treat missing fields as normal. Then new readers can read old data.
Numbers are a trap. RFC 8259 lets parsers limit precision. Only integers between −(2^53 − 1) and 2^53 − 1 are safe to exchange. 3 JavaScript stores every number as a double, so bigger integers get rounded. 4
JSON.parse('{"id": 9007199254740993}').id
// 9007199254740992 — a different id, and no errorSend big ids, such as 64-bit database keys, as strings. Protobuf's own JSON format does this for all 64-bit integers, for the same reason. 7
Protocol Buffers: the field number is the contract
In Protobuf, each field has a field number. The bytes on the wire carry that number, not the field name. So you can rename a field, but you can never change its number. 9
syntax = "proto3";
// v2
message Order {
int64 id = 1;
int64 amount = 2 [deprecated = true]; // rupees; v1 still reads it
int64 amount_paise = 3; // new in v2
optional string currency = 4; // new in v2
}Later, when no reader needs field 2, v3 deletes it and adds reserved 2; and reserved "amount";.
The rules that matter:
- Adding and removing fields is safe. Changing a field's number is not. 5
- Never reuse a number. Google's guide says it "messes up deserialization". When you delete a field, reserve its number. 6 Also reserve the name, so no new field reuses it. JSON and text formats carry names, not numbers. 5
- Unknown fields survive. An old proto3 reader keeps fields it does not know, and writes them out again. 5 They are lost if you convert the message to JSON. 5
- Missing means default. A missing string reads as empty, a number as zero, and a bool as false. 5 So "zero" and "not sent" look the same.
- Use
optionalwhen "not sent" matters. Then you can check whether a value was set. 5 - Do not change a field's type. 6 A few types are wire-compatible, such as
int32andint64. But a big value read asint32is cut short with no error. 5 - No required fields. Proto3 has none. In proto2, never add one. 6
Step through a rolling deploy that shares one queue. Use Next and Back, or the ← and → keys.
- A rolling deploy is half done. A v2 pod writes an order with a new field 4, currency. A v1 pod reads it. It does not know field 4, so it skips it, and proto3 keeps it in the message. This is forward compatibility.
- A v1 pod writes an order without field 4. A v2 pod reads it. Because currency is declared optional, v2 can see that it was never set, and pick a safe value. This is backward compatibility.
- Months later, someone deletes the old field 2 and gives the number 2 to a new discount field. Old code still thinks field 2 is the amount. It reads 50 as the amount and raises no error.
- The fix: mark number 2 as reserved, so the compiler refuses to reuse it, and give the new field a fresh number. Old code skips field 5. The numbers are the contract, not the names.
Avro: the reader needs the writer's schema
Avro has no field numbers. Binary Avro data has no field names or types either. So a reader needs the exact schema the data was written with: the writer's schema. 8
The reader also has its own schema, the reader's schema. Avro matches the two by field name. 8
- A field only in the writer's schema is ignored.
- A field only in the reader's schema takes its default.
- If that field has no default, the read fails. 8
So if both old and new readers must work, add or remove only fields that have a default. 9
{
"type": "record",
"name": "Order",
"fields": [
{"name": "id", "type": "long"},
{"name": "amount_paise", "type": "long"},
{"name": "currency", "type": ["null", "string"], "default": null}
]
}In Avro before 1.12, a union default had to match the first type in the union. Version 1.12 accepts the first type that matches. 8 Many tools still use the old rule, so put "null" first when the default is null.
Where does the writer's schema come from? An Avro file stores it once in its header. 8 For records stored one by one, such as rows in a database, each record carries a schema version or id. A schema registry maps that id to the full schema. 9 With Confluent Schema Registry, each Kafka message begins with a version byte and a 4-byte schema ID. 11
Schema registries and compatibility modes
A registry also guards changes. Confluent Schema Registry checks each new schema against old ones before it accepts it. 10
- BACKWARD (the default): consumers on the new schema can read data written with the last schema. Upgrade consumers first. 10
- FORWARD: consumers on the old schema can read data written with the new schema. Upgrade producers first. Then make sure consumers no longer read old data. 10
- FULL: both. You can upgrade either side in any order. 10
Each mode also has a _TRANSITIVE form. It checks against all older schemas, not only the last one. 10 Confluent made BACKWARD the default so that consumers can rewind to the start of a topic. 10 If your topic keeps data for a long time, a transitive mode is safer.
What no format can catch
Every check above looks at names, numbers and types. None of them looks at meaning. Say you keep int64 amount = 2, but start to send paise instead of rupees. The schema is the same, so every check passes. Old readers now show prices 100 times too high.
So a change of unit or meaning is a new field, with a new name and a new number. That is why the example above added amount_paise instead of changing amount.
Trade-offs
| Format | Schema needed to read? | New fields and old readers | Main risk | Use it when |
|---|---|---|---|---|
| JSON | No Names are in the data. | Yes , if readers ignore unknown fields. | Nothing checks shape. Big numbers lose precision. 3 | Public APIs, webhooks, browsers. |
| Protobuf | Yes , to know names. Unknown fields can still be skipped. 9 | Yes Old code skips them. 5 | A reused field number gives wrong data, silently. 6 | Calls between your own services, such as gRPC. |
| Avro | Yes The exact writer's schema. 8 | Yes Old readers ignore it. A default lets new readers read old data. 8 | Lost or wrong writer's schema means unreadable data. | Kafka topics and data files, with a registry. |
Simple rule: pick the format your readers can handle. Then put a compatibility check in CI, not in a reviewer's memory.
At work: how a senior uses this
- For every data change, ask: "Who reads this, and how old can their code be?" Count queue backlog, log retention and stored rows, not only live services.
- Add new fields as optional, with a safe default. Never make a new field required.
- Never change the meaning or unit of a field. To move from rupees to paise, add
amount_paiseand keepamountuntil nobody reads it. - Deprecate before you delete. Stop writing the field, wait until no reader needs it, then delete it and reserve its number and name.
- Run a schema check in CI. For Protobuf, a breaking-change linter. For Kafka, the registry's compatibility mode.
- Make readers fail safe on bad input. CrowdStrike's fix was a bounds check at runtime as well as a check at build time. 1
- For changes to public HTTP APIs, use API versioning and lifecycle. For database columns, use zero-downtime schema migrations.
With AI
What to ask the agent
"Compare this .proto file with the one on main. List every change that breaks old readers or old writers: changed or reused field numbers, changed types, removed fields without reserved, and new required fields."
"Here is our Avro schema and the new version. Would Confluent Schema Registry accept it in BACKWARD mode? In FORWARD mode? Explain each field."
"Find every place our JavaScript code parses JSON ids that can be larger than 2^53 − 1. Change them to strings end to end."
What to check yourself
- No field number was reused or renumbered. An agent may "tidy up" numbers so they run 1, 2, 3.
- Every deleted Protobuf field has its number and name in
reserved. - Every new Avro field has a default, and a union default matches the first type, for older Avro tools.
- No field kept its name but changed its unit or meaning. A linter cannot catch that.
- The plan says which side deploys first, and it matches the registry mode.
Check yourself
Your progress is saved only in this browser. Export it to keep it safe.
You have finished 5 lessons. Your progress lives only in this browser. Export a copy so you don’t lose it.
Go deeper
Show 11 sources and related lessons
- CrowdStrike, External Technical Root Cause Analysis — Channel File 291 (6 August 2024) (opens in a new tab)
How content data that expected 21 input fields met sensor code that supplied 20, and the fixes CrowdStrike made. - Kubernetes documentation, Deployments (opens in a new tab)
How a rolling update scales up new pods while it scales down old ones. - T. Bray (ed.), RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format (IETF, December 2017) (opens in a new tab)
Section 6 on number precision, and which integers are safe to exchange. - MDN Web Docs, Number.MAX_SAFE_INTEGER (opens in a new tab)
The largest integer a JavaScript number can hold exactly, with an example of what goes wrong above it. - Protocol Buffers Documentation, Language Guide (proto 3) (opens in a new tab)
Field numbers, defaults, the optional keyword, reserved fields, unknown fields and safe changes to a message. - Protocol Buffers Documentation, Proto Best Practices (opens in a new tab)
Short rules such as never reuse a field number, and never add a required field. - Protocol Buffers Documentation, ProtoJSON Format (opens in a new tab)
How Protobuf maps to JSON, why 64-bit integers become strings, and what happens to unknown fields. - Apache Avro, Specification (version 1.12.0) (opens in a new tab)
The schema resolution rules between the writer's schema and the reader's schema. - Martin Kleppmann, “Schema evolution in Avro, Protocol Buffers and Thrift” (5 December 2012) (opens in a new tab)
A side-by-side look at how each format encodes fields, and how it handles old and new schemas. - Confluent Documentation, Schema Evolution and Compatibility for Schema Registry on Confluent Platform (opens in a new tab)
The BACKWARD, FORWARD and FULL compatibility types, and which side to upgrade first for each. - Confluent Documentation, Formats, Serializers, and Deserializers for Schema Registry on Confluent Platform (opens in a new tab)
The wire format, where each message begins with a version byte and a 4-byte schema ID that the reader looks up in the registry.
Real incident: CrowdStrike, 19 Jul 2024: CrowdStrike outage: a content update crashed Windows hosts
Related: REST API design · API versioning and deprecation · Schema migrations without downtime · Queues vs logs and delivery guarantees · Webhooks and async APIs · RPC and gRPC (coming soon) · Contract and integration tests for services (coming soon) · Kafka internals
- Queues vs logs: why old messages stay around to be read again.
- Webhooks and async APIs: JSON events that your customers decode with code you cannot update.
- Safe deploys and config changes: rolling out content and config as carefully as code.
- Kafka internals: how the messages you encode are stored and replicated.
- Coming later: RPC and gRPC, and contract and integration tests.