Learn Labs
Schemas

Schema Registry

Typed messages with Avro, compatibility rules, and evolving schemas safely

Kafka stores bytes. It has no idea what's inside a record. That's flexible, and dangerous: one producer renames a JSON field, and every consumer breaks at once, in production, possibly days later when they reprocess old data. A schema registry makes the format of each topic explicit and enforces rules about how it may change. DDIA chapter 5 covers encoding and evolution in general.

How it works

producer serializerregisters the schema (or finds it), gets an id, writes: [0][id: 4 bytes][Avro bytes]Schema Registrystores schemas per "subject" (default: <topic>-value), checks compatibilityconsumer deserializerreads the id, fetches that schema (cached), decodes into the reader's schema
producerSchema RegistryKafkaconsumerregister Customer v1id 1[0][id 1][Avro bytes]recordGET /schemas/ids/1cached afterv2 without default409 incompatible

Records carry only a 5-byte header (a magic byte 0 and the schema id), not the schema itself, so typed data costs almost nothing extra:

kafka-console-consumer.sh ... --topic customers --from-beginning --max-messages 1 | xxd | head -2
00000000: 0000 0000 0102 1e61 6461 4065 7861 6d70  .......ada@examp
00000010: 6c65 2e63 6f6d 0641 6461 0a              le.com.Ada.
#         ^^ magic byte 0
#           ^^^^ ^^^^ schema id 1 (4 bytes, big-endian), then the Avro body

Schemas themselves are stored in a compacted Kafka topic, _schemas.

Producing with Avro

V1 = """{"type": "record", "name": "Customer", "namespace": "shop",
"fields": [
  {"name": "id", "type": "int"},
  {"name": "email", "type": "string"},
  {"name": "name", "type": "string"}
]}"""

serializer = AvroSerializer(sr, V1)
p.produce(TOPIC, key=str(cid), value=serializer(record, SerializationContext(TOPIC, MessageField.VALUE)))
registered v1 as schema id 1; message bytes start with magic byte 0 + that id

A record that doesn't match the schema, say id as a string, fails in the producer, before it ever reaches Kafka. That's the point: bad data is rejected at the source.

Compatibility

When a producer tries to register a new version, the registry checks it against previous versions under the subject's compatibility mode:

ModeNew schema must be able to...Safe changesDeploy order
BACKWARD (default)Read data written with the previous schemaDelete fields; add fields with defaultsConsumers first
FORWARDBe read by consumers using the previous schemaAdd fields; delete fields with defaultsProducers first
FULLBothAdd/delete fields with defaults onlyEither
*_TRANSITIVE...against all previous versions, not just the last
NONEAnythingEverything (no protection)Good luck

The lab tries two changes under BACKWARD:

global compatibility mode: BACKWARD
add field WITH default       compatible: True
add field WITHOUT default    compatible: False
registering the incompatible schema fails: HTTP 409
registered v2 as schema id 2

Adding phone without a default is rejected: a consumer using the new schema couldn't read old records, which have no phone. Adding tier with "default": "free" is accepted, and old records decode with the default:

{'id': 1, 'email': 'ada@example.com', 'name': 'Ada', 'tier': 'free'}     # written with v1
{'id': 2, 'email': 'alan@example.com', 'name': 'Alan', 'tier': 'free'}   # written with v1
{'id': 3, 'email': 'grace@example.com', 'name': 'Grace', 'tier': 'pro'}  # written with v2

The REST API

curl localhost:8081/subjects["customers-value"]curl localhost:8081/subjects/customers-value/versions[1, 2]curl localhost:8081/subjects/customers-value/versions/latestthe schema and its idcurl localhost:8081/schemas/ids/1a schema by idcurl localhost:8081/configglobal compatibilitycurl -X PUT -H "Content-Type: application/json" --data '{"compatibility": "FULL"}' \localhost:8081/config/customers-valueper-subject mode

Avro, Protobuf, or JSON Schema

AvroProtobufJSON Schema
EncodingCompact binaryCompact binaryJSON text
Field identityBy name, resolved with writer and reader schemasBy field numberBy name
EcosystemKafka's traditional default (Connect, ksqlDB)Strong in gRPC shopsEasy to read and debug
SizeSmallestSmallLargest

All three are supported by the registry and clients. Pick one per organisation and stick with it.

Practices

  • Register schemas in CI, not from production producers (auto.register.schemas=false on producers). A schema change then goes through review like code.
  • Every new field gets a default. It's the one habit that keeps almost every change compatible.
  • Never reuse a removed field's name with a different meaning.
  • Keys too: if keys are structured, give them a schema (<topic>-key), and remember that changing a key's encoding changes its partition.

Lab

  1. Run schema_registry.py, then explore the subject with curl.
  2. Set the subject to FULL and try to register a v3 that deletes name (no default). Then one that deletes tier (has a default).
  3. Produce a record that's missing a required field and read the producer-side error.
  4. Dump a record written with v2 (the third one) and find its schema id in the raw bytes.

On this page