Schemas and Schema Registry
Kafka stores bytes and never checks what is inside. If one team adds a field and another renames one, readers break at 3 am. Schemas, and a Schema Registry that enforces rules about how they change, prevent that. This lesson compares JSON, Avro and Protobuf, explains compatibility modes, and shows how to decode Avro and Protobuf in Spark.
Step 4 · Structured Streaming · Silver · Kafka in depth, lesson 2 of 2
On this page
Read first: Kafka producers: acks, retries and batching (skip if you know it)
In plain words first
A tax office accepts forms by post. If everyone could design their own form, every clerk would have to guess what each box means. So the office publishes official forms, and when a form changes, it follows rules: a new box must be optional, so old forms are still accepted, and clerks are trained on the new version before it is released.
A schema is the official form for a topictopic: A named stream of events in Kafka or Pub/Sub, such as "orders". Producers write to it; consumers read from it. Learn more →'s messages. A Schema Registry is the office that keeps every version and refuses changes that break the rules, called compatibility. Producersproducer: An application that writes events to a topic. Learn more → and consumersconsumer: An application that reads events from a topic and keeps track of how far it has read. Learn more → that follow it can be upgraded at different times without breaking each other.
JSON, Avro or Protobuf
| JSON | Avro | Protobuf | |
|---|---|---|---|
| Schema | None, unless you add JSON Schema | Required, written in JSON | Required, a .proto file |
| Size on the wire | Large: field names in every message | Small: binary, no field names | Small: binary, numbered fields |
| Readable by eye | Yes | No | No |
| Typical home | Simple pipelines, webhooks | Data platforms, KafkaKafka: A system that stores streams of events in topics, in order within each partition, so many readers can read them, and read them again, at their own pace. Learn more → Connect, CDC | Services that already use gRPC |
With plain JSON, the schema exists only in the code that parses it, such as the DDL string you pass to from_json. A producer can change it whenever it likes, and you find out from nulls or a failed job. Binary formats need a schema to read anything, which is exactly what makes them safe to share.
How a Schema Registry works
Register · producer
<topic>-value, such as orders-value. The registry checks the new version against the old ones and refuses it if it breaks the compatibility rule.Send · id, not schema
Read · consumer
Compatibility: which changes are allowed
| Mode | Promise | Allowed | Upgrade first |
|---|---|---|---|
BACKWARD (the default) | New readers can read old data | Delete a field; add a field with a default | Consumers |
FORWARD | Old readers can read new data | Add a field; delete a field that had a default | Producers |
FULL | Both | Add or delete fields that have defaults | Either, in any order |
NONE | Nothing is checked | Anything | Everyone at once, or a new topic |
The plain modes compare against the previous version only. The _TRANSITIVE variants (such as BACKWARD_TRANSITIVE) compare against every earlier version, which matters when a consumer may replay months of old messages. The one change no mode allows is renaming a field or changing its type in place: add a new field instead, and retire the old one later.
Decoding in Spark
Spark ships Avro and Protobuf support as separate modules (spark-avro, spark-protobuf), added with --packages. Open-sourcesource: Where a stream reads from: a Kafka topic, a folder of files, a Delta table. Learn more → Spark does not talk to a Schema Registry: you give it the schema, and you remove the 5-byte header yourself.
from pyspark.sql.avro.functions import from_avro import requests REG = "https://registry:8081" schema = requests.get(f"{REG}/subjects/orders-value/versions/latest").json()["schema"] orders = (raw # a Kafka source DataFrame .select(F.expr("substring(value, 6, length(value) - 5)").alias("avro")) .select(from_avro("avro", schema, {"mode": "PERMISSIVE"}).alias("o")) .select("o.*"))
substring(value, 6, ...)skips the magic byte and the 4-byte schema id; SQL positions start at 1.modeisFAILFASTby default: one corrupt message stops the query.PERMISSIVEreturns null instead, so you can route it to a dead-letter table.- This decodes every message with one schema version. When the topic holds messages from several versions, read the id from bytes 2 to 5 and pick the matching schema, or use a platform whose
from_avroreads the registry directly (Databricks does).
Protobuf works the same way: from_protobuf("value", "Order", descFilePath="order.desc"), where the descriptor file is produced from your .proto file by protoc. Messages written through a registry also start with the 5-byte header, followed by a few bytes that say which message type in the file was used.
Common mistakes
- Renaming a field in place — No compatibility mode allows it. Add the new field with a default and retire the old one later.
- Adding a field without a default under BACKWARD — New readers cannot fill it for old messages, so the registry refuses the schema.
- Passing registry-framed bytes straight to from_avro — The 5-byte header makes decoding fail or produce garbage. Strip it first.
- Upgrading producers first under BACKWARD — Old consumers may meet fields they cannot read. BACKWARD means consumers go first.
Key takeaways
- Kafka stores bytes; a schema says what they mean, and a registry keeps every version.
- Each message carries a 5-byte header with the schema id, not the schema itself.
- BACKWARD (the default) means upgrade consumers first; FORWARD means producers first; FULL means either.
- Spark's from_avro and from_protobuf need the schema given to them and the registry header stripped.
Interview prep
THE QUESTION
"A producer team wants to add a field to an Avro topic that 12 teams consume. How do you roll it out safely?"
Avoid: "just use JSON, it is flexible" without saying that nothing then stops a producer from breaking every consumer.
Follow-ups · answer out loud, then open
Follow-up"What is the difference between BACKWARD and BACKWARD_TRANSITIVE?"
Scenario"A Spark job reading Avro from Kafka suddenly fails after a producer deployment. How do you debug it?"
Trap"The registry stores schemas, so Spark's from_avro can read registry topics directly."
Check yourself
3 questionsUnder BACKWARD compatibility, which change does the registry accept?
Show the answer
Adding a field with a default. A new reader can fill the default when it reads an old message that lacks the field.
What do the first 5 bytes of a registry-framed message hold?
Show the answer
A magic byte and the 4-byte schema id. Byte 0 is the magic byte; bytes 1 to 4 are the schema id.
from_avro meets one corrupt message with the default mode. What happens?
Show the answer
The query fails. FAILFAST is the default; PERMISSIVE returns null instead.
Practise this
Interview problems on streaming, graded on hidden tests
Keep going
Up next · new module: Correct results end to end · 9 min readDelivery guarantees end to end
At-most-once, at-least-once and exactly-once, why most hops are at-least-once, and how idempotent sinks and event ids give exactly-once results.
Related lessons
Kafka producers: acks, retries and batchingStructured Streaming · 10 min read
Bad records and dead-letter queuesStructured Streaming · 7 min read
Restarts, query changes and reprocessing
Previous: Kafka producers: acks, retries and batching
Primary sources: Spark: Avro data source and from_avro · Spark: Protobuf data source · Schema evolution and compatibility · Wire format