Kafka Schema Registry and Serialization
Schema Registry keeps producers and consumers of a Kafka topic in agreement about the structure of the data. Kafka itself only stores bytes; it never checks what is inside a record. Schema Registry stores versioned schemas, gives each one an ID, and rejects schema changes that would break existing consumers.
This tutorial explains why serialization needs a contract, how the Avro serializer and Schema Registry work together on the wire, what subjects and compatibility modes mean, and how to use Avro with plain Java and Spring Boot. It also covers the settings you should change before going to production.
1. What Is Schema Registry?
Schema Registry is a separate service with a REST API that stores schemas for Kafka data. Producers register the schema they write with, consumers look it up when they read, and the registry enforces rules about how a schema may change over time. It supports Avro, Protobuf and JSON Schema.
The registry stores its schemas in a compacted Kafka topic (_schemas by default), so it needs no database of its own, and several registry instances can run behind a load balancer for availability.
2. Why Kafka Needs a Schema Contract
In Kafka, the producer and the consumer never talk to each other. They share only the topic. If the order service renames amount to totalAmount in its JSON, every consumer that reads amount breaks at run time, possibly days later, and the bad records stay in the topic until retention removes them.
| Without a schema registry | With a schema registry |
|---|---|
| Structure lives only in code and documentation | Every version of the structure is stored and numbered |
| Breaking changes are found in production, by consumers | Breaking changes are rejected when the producer tries to register them |
| Each JSON record repeats every field name | Binary formats send only values plus a 5-byte header |
Consumers guess types (is amount a string or a number?) | Types, defaults and optional fields are defined precisely |
3. Serialization Formats Compared
| Format | Encoding | Schema | Typical use |
|---|---|---|---|
Plain JSON (for example Spring’s JacksonJsonSerializer) | Text, field names in every record | None enforced | Simple systems with few consumers that are deployed together |
| JSON Schema | Text | JSON Schema in the registry | Teams that want JSON on the wire but validated structure |
| Avro | Compact binary | Avro schema (JSON) in the registry | The most common choice for Kafka data pipelines; excellent evolution rules |
| Protobuf | Compact binary | .proto definition in the registry | Organisations already using Protobuf for gRPC |
Kafka’s own serializers (StringSerializer, ByteArraySerializer and so on) turn objects into bytes but know nothing about schemas. The registry-aware serializers add the schema lookup and the wire format described next.
4. How It Works on the Wire
- Before sending the first record of a type, the serializer asks the registry for the ID of its schema under the record’s subject. With the default settings it registers the schema if it is new; the registry runs the compatibility check at this point.
- The returned ID is cached in the producer, so later records need no registry call.
- Each record value is written as a magic byte (
0), the 4-byte schema ID, then the encoded data. - The consumer’s deserializer reads the ID, downloads that schema the first time it sees the ID, caches it and decodes the record.
Because clients cache schemas by ID, a short registry outage does not stop producers and consumers that already know their schemas; it only blocks new schemas and new clients.
5. Subjects and Naming Strategies
A subject is the name under which versions of a schema are stored and checked for compatibility. The serializer derives it with a naming strategy:
| Strategy | Subject for the value of topic orders | When to use |
|---|---|---|
TopicNameStrategy (default) | orders-value (and orders-key for keys) | One event type per topic; the usual and simplest choice |
RecordNameStrategy | The record’s full name, for example com.javabytechie.OrderPlaced | Several event types in one topic, with the same type used across topics |
TopicRecordNameStrategy | orders-com.javabytechie.OrderPlaced | Several event types in one topic, evolved independently per topic |
Keeping several event types in one topic is the standard way to preserve their order for the same key, for example OrderPlaced and OrderCancelled for one order. See message ordering for why that matters.
6. Compatibility Modes and Schema Evolution
Each subject has a compatibility mode. When a new schema version is registered, the registry checks it against the previous version (or all previous versions for the _TRANSITIVE modes) and rejects it if the check fails. The default mode is BACKWARD.
| Mode | Guarantee | Allowed changes (Avro) | Upgrade first |
|---|---|---|---|
BACKWARD (default) | Consumers using the new schema can read data written with the previous one | Remove fields; add fields that have defaults | Consumers |
FORWARD | Consumers using the previous schema can read data written with the new one | Add fields; remove fields that have defaults | Producers |
FULL | Both of the above | Add or remove only fields that have defaults | Either, in any order |
*_TRANSITIVE | Same, but against all earlier versions | As above | As above |
NONE | No checks | Anything | Everyone at once, or use a new topic |
In practice, give every new field a default value. That one habit keeps most changes compatible in every mode. Renaming a field or changing its type is a breaking change; the usual approach is to add the new field, migrate consumers, and remove the old field later, or to publish to a new topic.
BACKWARD only proves that v5 reads v4; BACKWARD_TRANSITIVE proves that v5 reads every earlier version. Use transitive modes for topics that are replayed or retained for a long time.7. Example: Avro Producer and Consumer in Java
Add a Schema Registry container next to the broker from the Kafka Docker setup:
schema-registry:
image: confluentinc/cp-schema-registry:8.4.1
ports:
- "8081:8081"
environment:
SCHEMA_REGISTRY_HOST_NAME: schema-registry
SCHEMA_REGISTRY_LISTENERS: http://0.0.0.0:8081
SCHEMA_REGISTRY_KAFKASTORE_BOOTSTRAP_SERVERS: PLAINTEXT://broker:19092
depends_on:
broker:
condition: service_healthy
The Confluent serializers are published in Confluent’s Maven repository, not Maven Central:
<repositories>
<repository>
<id>confluent</id>
<url>https://packages.confluent.io/maven/</url>
</repository>
</repositories>
<dependency>
<groupId>io.confluent</groupId>
<artifactId>kafka-avro-serializer</artifactId>
<version>8.4.1</version>
</dependency>
The schema of an order event, with a defaulted optional field:
{
"type": "record",
"name": "OrderPlaced",
"namespace": "com.javabytechie.orders",
"fields": [
{ "name": "orderId", "type": "string" },
{ "name": "customerId", "type": "string" },
{ "name": "amount", "type": { "type": "bytes", "logicalType": "decimal", "precision": 12, "scale": 2 } },
{ "name": "couponCode", "type": ["null", "string"], "default": null }
]
}
A producer that uses GenericRecord, so no code generation is needed for this example:
package com.javabytechie.kafka;
import io.confluent.kafka.serializers.KafkaAvroSerializer;
import java.io.InputStream;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.util.Properties;
import org.apache.avro.Conversions;
import org.apache.avro.LogicalTypes;
import org.apache.avro.Schema;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericRecord;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;
public class AvroOrderProducer {
public static void main(String[] args) throws Exception {
Schema schema;
try (InputStream in = AvroOrderProducer.class.getResourceAsStream("/avro/order-placed.avsc")) {
schema = new Schema.Parser().parse(in);
}
Properties props = new Properties();
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, KafkaAvroSerializer.class);
props.put("schema.registry.url", "http://localhost:8081");
Schema amountSchema = schema.getField("amount").schema();
ByteBuffer amount = new Conversions.DecimalConversion().toBytes(
new BigDecimal("249.90"), amountSchema, LogicalTypes.decimal(12, 2));
GenericRecord order = new GenericData.Record(schema);
order.put("orderId", "ord-1001");
order.put("customerId", "cus-77");
order.put("amount", amount);
order.put("couponCode", null);
try (var producer = new KafkaProducer<String, GenericRecord>(props)) {
producer.send(new ProducerRecord<>("orders", "ord-1001", order), (meta, ex) -> {
if (ex != null) ex.printStackTrace();
else System.out.printf("Sent to %s-%d@%d%n", meta.topic(), meta.partition(), meta.offset());
});
}
}
}
After the first run, the registry contains the subject orders-value with version 1. You can inspect it with the REST API:
curl -s http://localhost:8081/subjects
# ["orders-value"]
curl -s http://localhost:8081/subjects/orders-value/versions/latest
# {"subject":"orders-value","version":1,"id":1,"schema":"{\"type\":\"record\", ...}"}
A consumer only needs the deserializer and the registry URL. Without further settings it returns GenericRecord values; set specific.avro.reader=true to get generated classes instead.
8. Using Schema Registry with Spring Boot
In a Spring Boot application you normally generate Java classes from the .avsc files at build time with the avro-maven-plugin (schema goal, with its sourceDirectory pointing at the folder that holds the .avsc files), and configure the Confluent serializers through Spring Boot properties. Properties under spring.kafka.properties are passed to producers, consumers and admin clients alike:
spring:
kafka:
bootstrap-servers: localhost:9092
properties:
schema.registry.url: http://localhost:8081
producer:
key-serializer: org.apache.kafka.common.serialization.StringSerializer
value-serializer: io.confluent.kafka.serializers.KafkaAvroSerializer
consumer:
group-id: billing-service
key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
value-deserializer: io.confluent.kafka.serializers.KafkaAvroDeserializer
properties:
specific.avro.reader: true
package com.javabytechie.billing;
import com.javabytechie.orders.OrderPlaced; // generated from order-placed.avsc
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
@Component
public class BillingListener {
@KafkaListener(topics = "orders")
public void onOrder(OrderPlaced order) {
// fields are typed; couponCode is null when the producer did not set it
System.out.printf("Invoice for %s, coupon=%s%n", order.getOrderId(), order.getCouponCode());
}
}
Spring for Apache Kafka has no Schema Registry of its own; it simply uses whatever Serializer and Deserializer you configure. To handle a record that cannot be deserialized, for example because its schema ID is unknown, wrap the Avro deserializer in Spring’s ErrorHandlingDeserializer as described in Kafka error handling.
9. Production Configuration
| Setting | Default | Recommendation |
|---|---|---|
auto.register.schemas (serializer) | true | Set to false in production and register schemas from the CI pipeline, so a service cannot publish a schema that nobody reviewed |
use.latest.version (serializer) | false | Set to true together with auto.register.schemas=false to serialize with the latest registered version |
| Subject compatibility | BACKWARD | Use a transitive mode for long-retained or replayed topics; set it per subject with PUT /config/{subject} |
value.subject.name.strategy | TopicNameStrategy | Change only when a topic carries several event types |
Before deploying a schema change, test it against the registry with the compatibility endpoint, for example from a CI job:
curl -s -X POST -H "Content-Type: application/vnd.schemaregistry.v1+json" \
--data @new-schema-request.json \
http://localhost:8081/compatibility/subjects/orders-value/versions/latest
# {"is_compatible":true}
10. Common Mistakes
- Adding a field without a default. Under the default BACKWARD mode the new schema cannot read old records, so registration fails, or with NONE the consumers fail later.
- Leaving auto-registration on in production. A developer’s local change can register a new schema version in the shared registry.
- Mixing serializers on one topic. A record written as plain JSON has no magic byte and schema ID, so the Avro deserializer fails on it, and it blocks the partition unless errors are handled.
- Treating the registry as optional infrastructure. New producers and consumers cannot start without it; run at least two instances in production.
- Forgetting the key. If keys are Avro too, the
orders-keysubject evolves separately; changing the key schema also changes partitioning.
11. Best Practices
- Treat schemas as code: keep
.avscor.protofiles in a shared repository, review changes, and register them from CI. - Default every optional field and avoid renames; deprecate and remove fields over several releases.
- Pick one format per organisation where possible; Avro is the most common choice for Kafka.
- Use simple string keys (such as an order ID) unless you have a reason to put structured data in the key.
- Plan upgrades by mode: with BACKWARD, deploy consumers before producers.
12. Summary
Kafka stores bytes, so the structure of events must be agreed elsewhere. Schema Registry stores versioned schemas per subject, hands out schema IDs that travel in a 5-byte header with every record, and blocks incompatible changes before they reach consumers. Use Avro or Protobuf with registry-aware serializers, keep the default BACKWARD mode (or its transitive form for replayed topics), give new fields defaults, and register schemas from CI rather than from running services.
13. Related Reading
- Apache Kafka vs Confluent: what belongs to Apache Kafka and what Confluent adds
- Kafka producer: serializers in the producer pipeline
- Change data capture with Debezium: Debezium can write Avro with Schema Registry
- Event sourcing and CQRS: long-lived events make schema evolution critical
14. References
- Confluent documentation: Schema Registry overview
- Confluent documentation: Schema evolution and compatibility
- Confluent documentation: Formats, serializers and deserializers
- Confluent documentation: Schema Registry REST API
- Spring for Apache Kafka: Serialization, deserialization and message conversion
- Apache Kafka documentation: Producer configs
Schema Registry Interview Questions and Answers
Common interview questions on Schema Registry, from basic to scenario-based, with short answers you can explain in your own words.
Basic questions
Q. Why use Avro with Schema Registry instead of plain JSON written with Spring’s JacksonJsonSerializer?
Answer: Plain JSON works, but nothing checks its structure: a producer can rename or retype a field and consumers break at run time. With Avro and Schema Registry, every schema version is stored and checked for compatibility when it is registered, records carry only a 5-byte header instead of field names, and types, defaults and optional fields are defined precisely. Plain JSON remains a reasonable choice for small systems whose producers and consumers are deployed together.
Q. What is a subject in Schema Registry?
Answer: The name under which the versions of a schema are stored and checked for compatibility. With the default TopicNameStrategy, the value schema of topic orders is stored under orders-value and the key schema under orders-key. Other strategies derive the subject from the record name, which allows several event types in one topic.
Intermediate questions
Q. How does a consumer know which schema to use for a record it reads?
Answer: The serializer writes a small header before the data: a magic byte (0) and a 4-byte schema ID. The deserializer reads the ID, fetches that schema from the registry the first time it sees it, caches it, and decodes the record. Records therefore carry only an ID, not the schema itself, and the registry is contacted once per new ID.
Q. What does BACKWARD compatibility mean, and in which order do you deploy producers and consumers?
Answer: BACKWARD, the default, guarantees that consumers using the new schema can read data written with the previous schema. In Avro that allows removing fields and adding fields with defaults. Because old consumers are not guaranteed to read new data, you upgrade the consumers first and the producers afterwards. FORWARD is the reverse (producers first), and FULL allows either order.
Q. Why should auto.register.schemas be disabled in production?
Answer: With the default true, any running producer registers whatever schema its code contains, including an untested local change, as a new version in the shared registry. Disabling it and registering schemas from a reviewed CI pipeline makes schema changes deliberate. Combine it with use.latest.version=true so the serializer uses the latest registered version.
Tricky and scenario questions
Q. A team needs to rename the field amount to totalAmount in an Avro schema used by ten consumers. How would you do it?
Answer: A rename is a breaking change, so do it in steps. Add totalAmount with a default and keep writing amount as well; migrate each consumer to read totalAmount; then remove amount in a later version, which BACKWARD allows. Avro aliases can map an old name for readers, but the stepwise migration is clearer and works with any consumer. If the change is too large, publish to a new topic and migrate consumers to it.
Q. Consumers replaying a topic from the beginning fail on old records even though every schema change passed the compatibility check. Why?
Answer: The subject used a non-transitive mode such as BACKWARD, which only checks each new version against the version before it. Version 5 may read version 4 data but not version 1 data. For topics that are retained for a long time or replayed, use BACKWARD_TRANSITIVE (or FULL_TRANSITIVE), which checks a new version against all earlier versions.