Skip to content
Silver 7 min read · Kafka 2 practice problems ↓

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

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

JSONAvroProtobuf
SchemaNone, unless you add JSON SchemaRequired, written in JSONRequired, a .proto file
Size on the wireLarge: field names in every messageSmall: binary, no field namesSmall: binary, numbered fields
Readable by eyeYesNoNo
Typical homeSimple pipelines, webhooksData 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, CDCServices 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

Before the first send, the producer's serializer registers its schema under a subject, by default <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

Each message carries only the schema's id: one magic byte (0), then a 4-byte id, then the encoded data. Five bytes of overhead, not the whole schema.

Read · consumer

The consumer's deserializer reads the id, fetches that schema once from the registry, caches it, and decodes the message, even if it was written by an older or newer producer.

Compatibility: which changes are allowed

ModePromiseAllowedUpgrade first
BACKWARD (the default)New readers can read old dataDelete a field; add a field with a defaultConsumers
FORWARDOld readers can read new dataAdd a field; delete a field that had a defaultProducers
FULLBothAdd or delete fields that have defaultsEither, in any order
NONENothing is checkedAnythingEveryone 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.

Tip: for a data platform, adding fields with defaults and never removing required ones keeps you compatible under any mode. That habit matters more than which mode you pick.

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.

PySpark · Avro written through a Schema Registry
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.
  • mode is FAILFAST by default: one corrupt message stops the query. PERMISSIVE returns 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_avro reads 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?"

Add the field with a default value, and register the new schema; under the default BACKWARD compatibility the registry accepts it because new readers can fill the default for old messages. Upgrade consumers that need the field first, then the producer. Consumers that do not care keep working, because Avro resolves fields by name. Never rename or retype a field in place; add a new one and deprecate the old. If consumers replay old data, use BACKWARD_TRANSITIVE so the new schema is checked against every version, not just the last.

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?"
BACKWARD checks a new schema only against the latest registered version; BACKWARD_TRANSITIVE checks it against every earlier version. If consumers may replay months of history, a chain of individually compatible changes could still leave the newest reader unable to read the oldest data, so transitive checking is safer for replayable topics.
Scenario"A Spark job reading Avro from Kafka suddenly fails after a producer deployment. How do you debug it?"
Compare the schema ids in the failing messages (bytes 1 to 4 after the magic byte) with the schema the job decodes with. If the producer registered a new version, the job is decoding new messages with the old writer schema. Decode per schema id, or pass the new schema, and switch to PERMISSIVE mode with a dead-letter path so one bad message cannot stop the stream. Then check the subject's compatibility mode, which should have rejected a breaking change.
Trap"The registry stores schemas, so Spark's from_avro can read registry topics directly."
Open-source from_avro takes the schema as a JSON string and knows nothing about registries or their 5-byte header. Strip the header and supply the schema yourself, or use a platform whose from_avro integrates with the registry.

Check yourself

3 questions

Under 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 read
Delivery 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

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