Platform Engineering · Lesson 148

Schema Registry for Kafka: Schema IDs, Compatibility Modes, and Safe Schema Evolution

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

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

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.

Try it: how much traffic does the registry get?

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

0registry calls/s, steady
240calls when every client restarts
0 msadded per record

Cached: the registry is called once per schema per client, 240 calls in a full restart

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

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.

Basic — IDs, subjects, and modes

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.

  • BACKWARD (the usual default): new readers can read old data. Add fields with defaults, remove fields. Upgrade consumers first.
  • FORWARD: old readers can read new data. Add fields, remove only fields that had defaults. Upgrade producers first.
  • FULL: both. Add or remove only fields with defaults. Any order.
  • _TRANSITIVE variants check against every earlier version, not only the latest; NONE checks nothing.

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.

Intermediate — Evolve schemas safely

At the intermediate level you change schemas without incidents.

  • Defaults everywhere new fields appear, so old records and old readers keep working.
  • Renames are three steps: add the new field with a default, move readers and writers to it, then remove the old one; or use an Avro alias where readers support it.
  • Type changes only by allowed promotion (int to long, float to double); anything else is a new field.
  • Enums: give them a default symbol, or a new symbol breaks old readers.
  • Protobuf: never reuse a field number; reserve removed ones.

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.

Advanced — Run the registry and gate changes in CI

At the advanced level the registry is production infrastructure.

  • CI owns registration: a pipeline step tests each schema change against the subject (POST /compatibility/subjects/<subject>/versions/latest), then registers it on merge; production clients run with auto.register.schemas=false.
  • High availability: several registry instances behind a service; Confluent Schema Registry stores schemas in a compacted Kafka topic, and Apicurio, often paired with Strimzi, can use Kafka or a database.
  • Access control: only CI can write subjects or change compatibility; NONE needs a review.
  • Poison records: an error handler that sends undecodable records to a dead-letter topic, with alerts, instead of blocking the partition.

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.

Master — Governance across teams

At the master level schemas are the organisation's data contracts.

  • Ownership: each subject has an owning team, documented fields, and a published compatibility policy.
  • Transitive modes for topics consumers replay from the start, so every retained version stays readable.
  • Catalog: schemas feed the data catalog and lineage, so analysts and other teams can find and trust topics.
  • Platform defaults: Strimzi topic templates, serializer settings, and CI checks provided by the platform team so teams adopt them by default.

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.

Go deeper

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.

Compatibility modes and the wire header

# 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.

The same change, as Avro

{
  "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.

One time it broke

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.

Timeline

  • 14:00The new producer ships. The registry accepts the schema; the broker accepts the records.
  • 14:02Three consumer groups stop on deserialization errors at the first new record; lag starts to grow on every partition.
  • 15:30Consumers are patched to skip and dead-letter undecodable records; the producer is rolled back. The bad records remain on the topic until retention expires.

What changed after

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.

If you remember nothing else

Design exercise

Introduce a schema registry for a Strimzi-based Kafka platform with 40 topics, 12 producing teams, and some consumers that replay from the beginning.

Clarifying questions to ask

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?

Rough sizing

Say 50,000 records a second, 400 client instances, about 3 subjects per client, and retention from 7 days to forever.

Shape of the answer

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.

Trade-offs to name

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.

Saved on this device, in this browser.
Next in this series · Lesson 149
DataOps

A company runs on data that moves. Orders come in, payments clear, support tickets pile up. None of that data is useful where it lands. It has to be picked up, cleaned, checked, and put somewhere the dashboards and the reports…

Go to Lesson 149 →

Or browse the full course from the Lessons index.