Kafka Schema Registry: schemas, subjects and serializers
Kafka stores bytes and knows nothing about their structure. Schema Registry gives producers and consumers a shared, versioned contract for those bytes, at the cost of five bytes per record. This page explains how the serializers, the registry and the record format fit together, then runs Avro and JSON Schema examples with Confluent's 8.4 serializers on a Kafka 4.2 broker.
Contents
Why Kafka needs a schema registry
A Kafka broker stores keys and values as bytes and never looks inside them. The producer's serializer decides what the bytes mean, and every consumer must use a deserializer that agrees. With plain JSON strings, that agreement lives in documentation and in the code of each team. When a producer renames a field, consumers find out in production.
A schema registry is a separate service that stores versioned schemas and checks new versions against old ones. Confluent Schema Registry, the most widely used one, works like this:
- The producer's serializer derives the schema of the value, Avro, JSON Schema or Protobuf, and registers it under a subject, such as
. The registry returns a numeric id, the same id for the same schema.orders-value - The serializer writes a 5-byte prefix, a magic byte 0 and the 4-byte id, followed by the encoded value. Optionally, the id goes in a record header instead.
- The consumer's deserializer reads the id, fetches that schema from the registry once and caches it, and decodes the value.
- When a producer registers a new version, the registry checks it against the subject's compatibility rule,
by default, and rejects changes that would break readers.BACKWARD
| Format | Serializer | Encoding | Best for |
|---|---|---|---|
| Avro | KafkaAvroSerializer | Compact binary, no field names | The usual default in Kafka, strong evolution rules |
| JSON Schema | KafkaJsonSchemaSerializer | Plain JSON text | Teams already on JSON, readable payloads |
| Protobuf | KafkaProtobufSerializer | Compact binary with field numbers | Organisations already using Protobuf and gRPC |
The programs use Confluent's 8.4 serializers with a mock://MockSchemaRegistry
The wire format, byte by byte
An order with three fields is small enough to read in hex. The program serializes it with KafkaAvroSerializer
import ch.qos.logback.classic.Level;
import io.confluent.kafka.schemaregistry.client.SchemaMetadata;
import io.confluent.kafka.schemaregistry.client.SchemaRegistryClient;
import io.confluent.kafka.schemaregistry.testutil.MockSchemaRegistry;
import io.confluent.kafka.serializers.KafkaAvroDeserializer;
import io.confluent.kafka.serializers.KafkaAvroSerializer;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.HexFormat;
import java.util.Map;
import org.apache.avro.Schema;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class WireFormat {
static final String ORDER_SCHEMA = """
{"type": "record", "name": "Order", "namespace": "shop",
"fields": [
{"name": "id", "type": "string"},
{"name": "customer", "type": "string"},
{"name": "cents", "type": "long"}
]}""";
public static void main(String[] args) throws Exception {
quietLogs();
// "mock://" gives an in-memory registry shared by everything in this JVM using the scope
Map<String, String> config = Map.of("schema.registry.url", "mock://shop");
Schema schema = new Schema.Parser().parse(ORDER_SCHEMA);
GenericRecord order = new GenericData.Record(schema);
order.put("id", "o-1001");
order.put("customer", "ann");
order.put("cents", 4599L);
try (var serializer = new KafkaAvroSerializer();
var deserializer = new KafkaAvroDeserializer()) {
serializer.configure(config, false); // false: this is a value serializer
deserializer.configure(config, false);
byte[] bytes = serializer.serialize("orders", order);
System.out.println("serialized: " + bytes.length + " bytes");
System.out.println(" hex: " + HexFormat.ofDelimiter(" ").formatHex(bytes));
ByteBuffer buf = ByteBuffer.wrap(bytes);
System.out.println(" byte 0, magic byte: " + buf.get());
System.out.println(" bytes 1-4, schema id: " + buf.getInt());
System.out.println(" bytes 5-" + (bytes.length - 1) + ": Avro binary, "
+ buf.remaining() + " bytes, no field names");
String json = "{\"id\":\"o-1001\",\"customer\":\"ann\",\"cents\":4599}";
System.out.println("the same order as JSON: "
+ json.getBytes(StandardCharsets.UTF_8).length + " bytes");
SchemaRegistryClient registry = MockSchemaRegistry.getClientForScope("shop");
System.out.println("subjects: " + registry.getAllSubjects());
SchemaMetadata latest = registry.getLatestSchemaMetadata("orders-value");
System.out.println("orders-value: version " + latest.getVersion()
+ ", id " + latest.getId());
Object back = deserializer.deserialize("orders", bytes);
System.out.println("deserialized: " + back.getClass().getSimpleName() + " " + back);
}
}
static void quietLogs() {
// Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
.setLevel(Level.OFF);
}
}
serialized: 18 bytes
hex: 00 00 00 00 01 0c 6f 2d 31 30 30 31 06 61 6e 6e ee 47
byte 0, magic byte: 0
bytes 1-4, schema id: 1
bytes 5-17: Avro binary, 13 bytes, no field names
the same order as JSON: 45 bytes
subjects: [orders-value]
orders-value: version 1, id 1
deserialized: Record {"id": "o-1001", "customer": "ann", "cents": 4599}
- The value is 18 bytes. The first,
, is the magic byte that marks the Confluent format.00 - Bytes 1 to 4,
, are the schema id 1 as a big-endian integer.00 00 00 01 - The remaining 13 bytes are the Avro binary encoding.
is the length 6 of "o-1001" in Avro's zigzag variable-length encoding, followed by its characters;0c and "ann" are the customer;06 is 4599, also zigzag encoded. No field names are stored: the reader needs the schema to know what the bytes are.ee 47 - The same order as JSON takes 45 bytes, because every record repeats the field names.
- Serializing registered the schema under
, the topic name plus "-value", as version 1 with id 1.orders-value - The deserializer found id 1 in the prefix, fetched the schema and returned a
.GenericData.Record
The schema id is global to the registry, not per subject: the same schema registered under two subjects gets the same id. A consumer that receives a record with an id its registry does not know fails with an error, so producers and consumers must use the same registry.
Producing and consuming Avro on a broker
In an application, the serializers are configured as producer and consumer properties, with schema.registry.url
import ch.qos.logback.classic.Level;
import io.confluent.kafka.serializers.KafkaAvroDeserializer;
import io.confluent.kafka.serializers.KafkaAvroSerializer;
import io.confluent.kafka.serializers.schema.id.HeaderSchemaIdSerializer;
import java.io.OutputStream;
import java.io.PrintStream;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.avro.Schema;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericRecord;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.KafkaConsumer;
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.TopicPartition;
import org.apache.kafka.common.header.Header;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
public class AvroOnBroker {
static final Schema ORDER = new Schema.Parser().parse("""
{"type": "record", "name": "Order", "namespace": "shop",
"fields": [{"name": "id", "type": "string"}, {"name": "cents", "type": "long"}]}""");
public static void main(String[] args) throws Exception {
EmbeddedKafkaBroker broker = startBroker();
String servers = broker.getBrokersAsString();
// producer 1: the schema id goes in front of the value, the classic format
try (var producer = new KafkaProducer<String, Object>(producerProps(servers, Map.of()))) {
producer.send(new ProducerRecord<>("orders", "o-1", order("o-1", 4599))).get();
}
// producer 2: the schema id goes in a record header, the value is plain Avro
try (var producer = new KafkaProducer<String, Object>(producerProps(servers,
Map.of("value.schema.id.serializer", HeaderSchemaIdSerializer.class.getName())))) {
producer.send(new ProducerRecord<>("orders", "o-2", order("o-2", 1250))).get();
}
Properties c = new Properties();
c.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, servers);
c.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
c.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,
KafkaAvroDeserializer.class.getName());
c.put("schema.registry.url", "mock://shop");
try (var consumer = new KafkaConsumer<String, Object>(c)) {
TopicPartition tp = new TopicPartition("orders", 0);
consumer.assign(List.of(tp));
consumer.seekToBeginning(List.of(tp));
int seen = 0;
while (seen < 2) {
for (ConsumerRecord<String, Object> r : consumer.poll(Duration.ofMillis(500))) {
seen++;
GenericRecord value = (GenericRecord) r.value();
System.out.println(r.key() + ": " + value + ", cents field is a "
+ value.get("cents").getClass().getSimpleName());
System.out.println(" value size " + r.serializedValueSize() + " bytes");
for (Header h : r.headers()) {
// byte 0 is a format version, the other 16 a random schema GUID
System.out.println(" header " + h.key() + ": " + h.value().length
+ " bytes, first byte " + h.value()[0]);
}
}
}
}
broker.destroy();
}
static GenericRecord order(String id, long cents) {
GenericRecord r = new GenericData.Record(ORDER);
r.put("id", id);
r.put("cents", cents);
return r;
}
static Properties producerProps(String servers, Map<String, String> extra) {
Properties p = new Properties();
p.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, servers);
p.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
p.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, KafkaAvroSerializer.class.getName());
p.put("schema.registry.url", "mock://shop"); // a real registry: "http://registry:8081"
p.putAll(extra);
return p;
}
// Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
static EmbeddedKafkaBroker startBroker() {
// the broker logs at INFO and prints its storage setup: both are silenced.
// Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
.setLevel(Level.OFF);
PrintStream stdout = System.out;
System.setOut(new PrintStream(OutputStream.nullOutputStream()));
try {
// one broker cannot hold the default 3 copies of the transaction log
EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
Map.of("transaction.state.log.replication.factor", "1",
"transaction.state.log.min.isr", "1"));
broker.afterPropertiesSet();
return broker;
} finally {
System.setOut(stdout);
}
}
}
o-1: {"id": "o-1", "cents": 4599}, cents field is a Long
value size 11 bytes
o-2: {"id": "o-2", "cents": 1250}, cents field is a Long
value size 6 bytes
header __value_schema_id: 17 bytes, first byte 1
- Both values came back as
, and theGenericRecord field arrived as a Javalong . Strings arrive as Avro'sLong type unless the schema says otherwise, which is why code callsUtf8 on them.toString() - The first value is 11 bytes: the 5-byte prefix and 6 bytes of Avro.
- With
set tovalue.schema.id.serializer , the second value is 6 bytes of plain Avro, and the id travels in aHeaderSchemaIdSerializer header of 17 bytes: a version byte, 1, and a 16-byte GUID that identifies the schema.__value_schema_id - One consumer read both, because the default
,value.schema.id.deserializer , accepts an id in either place.DualSchemaIdDeserializer
Header ids keep the payload a valid Avro, JSON or Protobuf document that tools without Schema Registry support can read. Older consumers that expect the prefix cannot read such records, so switch producers only after every consumer runs a client version that understands headers. In production, also set specific.avro.reader=true.avscGenericRecord
Subject naming strategies
The subject decides which schemas are compared with each other. Two event types, an order and a refund, are sent to the same payments
import ch.qos.logback.classic.Level;
import io.confluent.kafka.schemaregistry.client.SchemaRegistryClient;
import io.confluent.kafka.schemaregistry.testutil.MockSchemaRegistry;
import io.confluent.kafka.serializers.KafkaAvroSerializer;
import io.confluent.kafka.serializers.subject.RecordNameStrategy;
import io.confluent.kafka.serializers.subject.TopicNameStrategy;
import io.confluent.kafka.serializers.subject.TopicRecordNameStrategy;
import java.util.HashMap;
import java.util.Map;
import org.apache.avro.Schema;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericRecord;
import org.apache.kafka.common.errors.SerializationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SubjectStrategies {
static final Schema ORDER = new Schema.Parser().parse("""
{"type": "record", "name": "OrderPlaced", "namespace": "shop",
"fields": [{"name": "id", "type": "string"}]}""");
static final Schema REFUND = new Schema.Parser().parse("""
{"type": "record", "name": "RefundIssued", "namespace": "shop",
"fields": [{"name": "id", "type": "string"}, {"name": "cents", "type": "long"}]}""");
public static void main(String[] args) throws Exception {
quietLogs();
Class<?>[] strategies = {TopicNameStrategy.class, RecordNameStrategy.class,
TopicRecordNameStrategy.class};
for (Class<?> strategy : strategies) {
String scope = strategy.getSimpleName();
Map<String, Object> config = new HashMap<>();
config.put("schema.registry.url", "mock://" + scope);
config.put("value.subject.name.strategy", strategy.getName());
System.out.println(scope + ": two event types to topic payments");
try (var serializer = new KafkaAvroSerializer()) {
serializer.configure(config, false);
for (GenericRecord event : new GenericRecord[] {record(ORDER), record(REFUND)}) {
try {
serializer.serialize("payments", event);
System.out.println(" " + event.getSchema().getName() + ": registered");
} catch (SerializationException e) {
System.out.println(" " + event.getSchema().getName() + ": REJECTED, "
+ e.getCause().getMessage().split(";")[0]);
}
}
}
SchemaRegistryClient registry = MockSchemaRegistry.getClientForScope(scope);
for (String subject : registry.getAllSubjects().stream().sorted().toList()) {
System.out.println(" subject " + subject + ", versions "
+ registry.getAllVersions(subject));
}
}
// producers in production often must not register schemas themselves
Map<String, Object> strict = new HashMap<>();
strict.put("schema.registry.url", "mock://strict");
strict.put("auto.register.schemas", false);
try (var serializer = new KafkaAvroSerializer()) {
serializer.configure(strict, false);
serializer.serialize("orders", record(ORDER));
} catch (SerializationException e) {
System.out.println("auto.register.schemas=false, schema not registered: "
+ e.getCause().getClass().getSimpleName());
}
}
static GenericRecord record(Schema schema) {
GenericRecord r = new GenericData.Record(schema);
r.put("id", "x-1");
if (schema.getField("cents") != null) {
r.put("cents", 500L);
}
return r;
}
static void quietLogs() {
// Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
.setLevel(Level.OFF);
}
}
TopicNameStrategy: two event types to topic payments
OrderPlaced: registered
RefundIssued: registered
subject payments-value, versions [1, 2]
RecordNameStrategy: two event types to topic payments
OrderPlaced: registered
RefundIssued: registered
subject shop.OrderPlaced, versions [1]
subject shop.RefundIssued, versions [1]
TopicRecordNameStrategy: two event types to topic payments
OrderPlaced: registered
RefundIssued: registered
subject payments-shop.OrderPlaced, versions [1]
subject payments-shop.RefundIssued, versions [1]
auto.register.schemas=false, schema not registered: RestClientException
, the default, put both event types inTopicNameStrategy , as versions 1 and 2. A real registry would have checked the refund against the order as a new version of the same schema and, underpayments-value , rejected it. The mock accepted it, as noted above. This strategy suits one event type per topic.BACKWARD created one subject per record name,RecordNameStrategy andshop.OrderPlaced , whatever the topic. Each type evolves on its own, but the same record name used in two topics shares one history.shop.RefundIssued combined both,TopicRecordNameStrategy andpayments-shop.OrderPlaced : several types per topic, each with its own history per topic.payments-shop.RefundIssued- With
, serializing a schema that was never registered failed withauto.register.schemas=false , the registry's "not found" error. That is what you want in production: schemas are registered by a build pipeline, and a producer cannot invent a new version at run time.RestClientException
Two related settings are useful with auto.register.schemas=falseuse.latest.version=truelatest.compatibility.strict
JSON Schema from Java classes
With JSON Schema, the serializer can generate the schema from a Java class. A Shipmentint
import ch.qos.logback.classic.Level;
import io.confluent.kafka.schemaregistry.client.SchemaRegistryClient;
import io.confluent.kafka.schemaregistry.testutil.MockSchemaRegistry;
import io.confluent.kafka.serializers.json.KafkaJsonSchemaDeserializer;
import io.confluent.kafka.serializers.json.KafkaJsonSchemaSerializer;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Map;
import org.apache.kafka.common.errors.SerializationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class JsonSchemaRecords {
public record Shipment(String id, String city, int parcels) {
}
public static void main(String[] args) throws Exception {
quietLogs();
Map<String, Object> config = Map.of(
"schema.registry.url", "mock://shipping",
"json.fail.invalid.schema", true, // validate every value against its schema
"json.value.type", Shipment.class.getName());
try (var serializer = new KafkaJsonSchemaSerializer<Shipment>();
var deserializer = new KafkaJsonSchemaDeserializer<Shipment>()) {
serializer.configure(config, false);
deserializer.configure(config, false);
byte[] bytes = serializer.serialize("shipments", new Shipment("s-1", "Leeds", 3));
System.out.println("serialized: " + bytes.length + " bytes, prefix "
+ Arrays.toString(Arrays.copyOf(bytes, 5)));
System.out.println("payload: "
+ new String(bytes, 5, bytes.length - 5, StandardCharsets.UTF_8));
SchemaRegistryClient registry = MockSchemaRegistry.getClientForScope("shipping");
System.out.println("registered schema for shipments-value:");
System.out.println(" " + registry.getLatestSchemaMetadata("shipments-value")
.getSchema());
Shipment back = deserializer.deserialize("shipments", bytes);
System.out.println("deserialized: " + back);
try {
serializer.serialize("shipments", new Shipment(null, "York", 1));
System.out.println("null id accepted");
} catch (SerializationException e) {
System.out.println("null id: " + e.getMessage());
}
}
}
static void quietLogs() {
// Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
.setLevel(Level.OFF);
}
}
serialized: 44 bytes, prefix [0, 0, 0, 0, 1]
payload: {"id":"s-1","city":"Leeds","parcels":3}
registered schema for shipments-value:
{"$schema":"http://json-schema.org/draft-07/schema#","title":"Shipment","type":"object","additionalProperties":false,"properties":{"id":{"oneOf":[{"type":"null","title":"Not included"},{"type":"string"}]},"city":{"oneOf":[{"type":"null","title":"Not included"},{"type":"string"}]},"parcels":{"type":"integer"}},"required":["parcels"]}
deserialized: Shipment[id=s-1, city=Leeds, parcels=3]
null id accepted
- The value has the same 5-byte prefix, followed by plain JSON text: 44 bytes in all.
- The generated schema is draft-07. It sets
to false, so a reader rejects unknown fields; this closed content model affects how the schema may evolve.additionalProperties - Each
became "null or string", because a Java reference can be null. OnlyString , a primitiveparcels , is required.int - That is why the shipment with a null id was accepted, although
validates every value: the generated schema allows it.json.fail.invalid.schema
Generated schemas describe Java's type system, not your business rules. For a contract that other teams rely on, write the schema by hand, mark required fields, and register it from the build; annotations such as Jackson's @JsonProperty(required = true)
Working with a real registry
A real Schema Registry is a separate service with a REST API on port 8081 by default, storing its schemas in the Kafka topic _schemas
# list subjects
curl http://localhost:8081/subjects
# register a schema version under a subject
curl -X POST -H "Content-Type: application/vnd.schemaregistry.v1+json" \
--data '{"schema": "{\"type\": \"string\"}"}' \
http://localhost:8081/subjects/Kafka-value/versions
# fetch a schema by its global id
curl http://localhost:8081/schemas/ids/1
# test a schema against the latest version, without registering it
curl -X POST -H "Content-Type: application/vnd.schemaregistry.v1+json" \
--data '{"schema": "{\"type\": \"string\"}"}' \
http://localhost:8081/compatibility/subjects/Kafka-value/versions/latest
# change the global compatibility level
curl -X PUT -H "Content-Type: application/vnd.schemaregistry.v1+json" \
--data '{"compatibility": "NONE"}' http://localhost:8081/config
In client configuration, only the URL changes from the programs above, plus credentials when the registry is secured, for example basic.auth.credentials.source=USER_INFObasic.auth.user.info
Mistakes that break consumers
- Plain deserializers on registry data: a
on an Avro topic returns garbage starting with the 5 prefix bytes. Every consumer of the topic must use the matching deserializer.StringDeserializer - Different registries per environment, shared topics: ids are only meaningful in the registry that issued them. Mirroring a topic to another cluster needs the schemas mirrored too.
- Auto-registration in production: any producer build can register a new version. Disable it and register from CI, where a failed compatibility check stops the release.
- Several event types under
: the second type is checked as a new version of the first and is rejected, or forcesTopicNameStrategy compatibility. Use a record-based strategy or one topic per type.NONE - Keys with schemas: an Avro key is hashed as its serialized bytes. Changing the key schema, even compatibly, can change the bytes and send the same logical key to another partition. Keep keys as simple strings or numbers.
Choosing a format and a strategy
| Situation | Use |
|---|---|
| A new Kafka platform with many teams | Avro with Schema Registry, BACKWARD |
| Existing JSON producers that must stay readable | JSON Schema with hand-written schemas |
| An organisation standardised on Protobuf | Protobuf with Schema Registry |
| One event type per topic | TopicNameStrategy |
| Several event types in one topic, for ordering per key | TopicRecordNameStrategy |
| Consumers or tools that must read payloads without the registry prefix | Schema ids in headers, once all consumers support them |
| Two Spring services owned by one team | JSON without a registry can be enough; see |
How schemas may change over time, and which change breaks which consumer, is the subject of