A Kafka topic outlives every program that writes to it, so the shape of its records has to change without breaking the readers. A schema registry makes that safe. Producers register each schema version once and put a small schema ID in front of every record; consumers fetch the schema by ID and decode with their own version. On every new version the registry checks a compatibility mode, BACKWARD, FORWARD, or FULL, and rejects a change that would break someone. This lesson follows one record from producer to consumer, and shows what happens when compatibility is switched off and when the registry is down for a pod that has just started.
Difficulty: Advanced · Know this first: Lesson 147, Lesson 65, Lesson 38
This bar splits one record's trip, in milliseconds. It is a worked example, not a measurement. With warm caches the registry adds nothing; it only costs time on a cache miss, which is also the only time it can fail you.
Set the message rate, the number of client instances, and the subjects each uses, and whether the clients cache schema IDs. Then see the load on the registry and the cost per record.
With caching, calls at a full restart = instances × subjects and the steady rate is near zero; without it, calls/s = records/s
Cached: the registry is called once per schema per client, 240 calls in a full restart
Three questions. No score is saved anywhere — this is just you against the material.
Schema management grows in four levels: first the wire format and the modes, then evolving schemas safely, then running the registry and CI checks, and finally governance across many teams.
At the basic level you can explain the moving parts. A subject is a named history of schema versions, usually one per topic value (orders-value). Every record carries the schema ID it was written with. The subject's compatibility mode says what a new version must preserve.
Try it: Basic
What does the 4-byte number after the magic byte in a record value tell a consumer?
Now do it: Run schema_compat.py in Go deeper and add a change that adds a field with a default and removes one that had a default.
At the intermediate level you change schemas without incidents.
Try it: Intermediate
You need total_cents to become a long under FULL compatibility. Is the in-place change accepted?
Now do it: Use the demo to check the int-to-long change under each mode.
At the advanced level the registry is production infrastructure.
POST /compatibility/subjects/<subject>/versions/latest), then registers it on merge; production clients run with auto.register.schemas=false.Try it: Advanced
Someone needs to ship a breaking change and asks to set the subject to NONE. What is the safer path?
Now do it: Add a CI step for one topic that calls the compatibility endpoint before merge.
At the master level schemas are the organisation's data contracts.
Trade-off: strict modes slow some changes and force more topics; loose modes move fast until the first record nobody can read, which stays on the topic until retention removes it.
Try it: Master
A topic is replayed from offset 0 by new consumers and has 30 schema versions. Which mode fits?
Now do it: List your topics with infinite or long retention and check their compatibility modes.
The compatibility rules are small enough to write out. This script checks five changes to an order schema under each mode, using the Avro resolution rules (missing fields need defaults; a few types widen), and decodes the 5-byte header. Standard library only; python3 schema_compat.py.
# schema_compat.py - Avro-style compatibility checks (BACKWARD, FORWARD, FULL) and the wire-format header
import struct
PROMOTE = {("int", "long"), ("int", "float"), ("int", "double"), ("long", "float"), ("long", "double"),
("float", "double"), ("string", "bytes"), ("bytes", "string")} # writer type -> reader type
def can_read(reader, writer):
"""Can a consumer using `reader` decode data written with `writer`? Returns the problems."""
problems = []
for name, f in reader.items():
if name not in writer:
if "default" not in f:
problems.append(f"reader needs '{name}', writer has no such field and there is no default")
elif writer[name]["type"] != f["type"] and (writer[name]["type"], f["type"]) not in PROMOTE:
problems.append(f"'{name}' written as {writer[name]['type']}, read as {f['type']}")
return problems # fields only the writer has are skipped by the reader
def check(mode, new, old):
if mode == "BACKWARD":
return can_read(new, old) # new consumers read old data: upgrade consumers first
if mode == "FORWARD":
return can_read(old, new) # old consumers read new data: upgrade producers first
return can_read(new, old) + can_read(old, new) # FULL: either order
v1 = {"id": {"type": "string"}, "total_cents": {"type": "int"}}
changes = {
"add currency, default EUR": dict(v1, currency={"type": "string", "default": "EUR"}),
"add coupon, no default": dict(v1, coupon={"type": "string"}),
"remove total_cents": {"id": {"type": "string"}},
"widen total_cents int -> long": dict(v1, total_cents={"type": "long"}),
"rename total_cents to amount": {"id": {"type": "string"}, "amount": {"type": "int"}},
}
print(f"{'change':<31}{'BACKWARD':<10}{'FORWARD':<10}FULL")
for name, new in changes.items():
marks = ["ok" if not check(m, new, v1) else "REJECT" for m in ("BACKWARD", "FORWARD", "FULL")]
print(f"{name:<31}{marks[0]:<10}{marks[1]:<10}{marks[2]}")
print("why the rename fails BACKWARD:", "; ".join(check("BACKWARD", changes["rename total_cents to amount"], v1)))
# Every record on the topic starts with 5 bytes: a magic byte 0 and the 4-byte schema ID, big-endian.
header = struct.pack(">bI", 0, 42)
magic, schema_id = struct.unpack(">bI", header)
print(f"header bytes {header.hex(' ')} -> magic {magic}, schema id {schema_id}")
$ python3 schema_compat.py change BACKWARD FORWARD FULL add currency, default EUR ok ok ok add coupon, no default REJECT ok REJECT remove total_cents ok REJECT REJECT widen total_cents int -> long ok REJECT REJECT rename total_cents to amount REJECT REJECT REJECT why the rename fails BACKWARD: reader needs 'amount', writer has no such field and there is no default header bytes 00 00 00 00 2a -> magic 0, schema id 42
Read it like this: only the field with a default passes every mode. Removing a field and widening a type pass BACKWARD only, adding a required field passes FORWARD only, and the rename passes nothing. The real registry applies the same idea with the full Avro, Protobuf, or JSON Schema rules.
{
"type": "record",
"name": "Order",
"namespace": "shop.orders",
"fields": [
{"name": "id", "type": "string"},
{"name": "total_cents", "type": "int"},
{"name": "currency", "type": "string", "default": "EUR"}
]
}
The schema is valid Avro and parses as JSON. CI tests it before registering, for example curl -X POST -H "Content-Type: application/vnd.schemaregistry.v1+json" --data @request.json $REGISTRY/compatibility/subjects/orders-value/versions/latest, where request.json wraps the schema as a string in {"schema": "..."}. The response says whether it is compatible. Check the paths against your registry's API; Apicurio offers a compatible API alongside its own.
This is a composite of a failure pattern that keeps repeating; the details are illustrative. A team needed to change a field's type quickly and the registry rejected it, so they set the subject's compatibility to NONE and registered the new version.
Only CI can register schemas or change compatibility, and NONE requires a review. Production clients stopped auto-registering, consumers got a dead-letter handler, and type changes now go through a new field or a new topic.
Introduce a schema registry for a Strimzi-based Kafka platform with 40 topics, 12 producing teams, and some consumers that replay from the beginning.
Which registry, and how is it run highly available? Which format, Avro, Protobuf, or JSON Schema? Which compatibility mode per topic, and which topics need transitive modes? Who can register schemas and change modes? How are existing topics without schemas migrated? What happens to records a consumer cannot decode?
Say 50,000 records a second, 400 client instances, about 3 subjects per client, and retention from 7 days to forever.
Apicurio Registry or Confluent Schema Registry with several replicas; Avro or Protobuf with generated classes; BACKWARD by default and BACKWARD_TRANSITIVE for replayed topics; CI compatibility checks and registration, auto-registration off in production; write access only for CI; dead-letter topics and alerts on deserialization errors; new topics for breaking changes.
Strict modes force additive changes and sometimes new topics; loose modes risk records nobody can read for as long as they are retained. A registry is another critical service, but with caching it is off the hot path except at restarts and new versions.