Schema evolution: changing Kafka schemas without breaking consumers
Topics outlive the code that writes them, so every schema change must still let old data be read by new code, new data by old code, or both. Schema Registry enforces that with compatibility levels built on Avro's schema resolution rules. This page runs those rules directly: what each change does to a reader, which levels accept it, and the transitive trap that a plain check misses.
Contents
Why schemas must evolve carefully
A Kafka topic keeps records for days, months or for ever when it is compacted, and many applications read it. Producers and consumers are deployed at different times by different teams. So at any moment, some consumers read records written with an older schema, and some read records written with a newer one. A schema change is safe only if both situations still work for the readers that will meet them.
Avro makes this checkable. A reader decodes a record with two schemas: the writer's schema, which the Schema Registry id in the record identifies, and its own reader's schema. Avro's schema resolution then matches fields by name, fills in defaults for fields the writer did not have, and skips fields the reader does not want. Schema Registry runs the same rules before it accepts a new version, according to the subject's compatibility level:
| Level | The new schema must | Checked against | Upgrade first |
|---|---|---|---|
BACKWARD | Read data written with the previous schema | The latest version | Consumers |
BACKWARD_TRANSITIVE | Read data written with every earlier schema | All versions | Consumers |
FORWARD | Write data that the previous schema can read | The latest version | Producers |
FORWARD_TRANSITIVE | Write data that every earlier schema can read | All versions | Producers |
FULL | Both of the above | The latest version | Either, independently |
FULL_TRANSITIVE | Both, for every version | All versions | Either, independently |
NONE | Nothing: checks are off | Nothing | All at once, with care |
The level can be set for the whole registry or per subject. The programs use Avro 1.12 and Confluent's 8.4 schema classes. The registry is MockSchemaRegistryClienttestCompatibilityregister
Avro schema resolution, change by change
Every compatibility rule comes from what one schema can decode of another's data. The program writes one customer with schema v1, then reads the same bytes with seven different reader schemas, each with one change:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.apache.avro.AvroTypeException;
import org.apache.avro.Schema;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericDatumReader;
import org.apache.avro.generic.GenericDatumWriter;
import org.apache.avro.generic.GenericRecord;
import org.apache.avro.io.BinaryEncoder;
import org.apache.avro.io.DecoderFactory;
import org.apache.avro.io.EncoderFactory;
public class AvroResolution {
static final Schema V1 = parse("""
{"type": "record", "name": "Customer", "fields": [
{"name": "id", "type": "string"},
{"name": "name", "type": "string"},
{"name": "visits", "type": "int"}
]}""");
public static void main(String[] args) throws Exception {
GenericRecord ann = new GenericData.Record(V1);
ann.put("id", "c-1");
ann.put("name", "Ann");
ann.put("visits", 7);
byte[] v1Bytes = write(V1, ann);
read("new field with a default", v1Bytes, V1, parse("""
{"type": "record", "name": "Customer", "fields": [
{"name": "id", "type": "string"},
{"name": "name", "type": "string"},
{"name": "visits", "type": "int"},
{"name": "tier", "type": "string", "default": "standard"}
]}"""));
read("new field without a default", v1Bytes, V1, parse("""
{"type": "record", "name": "Customer", "fields": [
{"name": "id", "type": "string"},
{"name": "name", "type": "string"},
{"name": "visits", "type": "int"},
{"name": "tier", "type": "string"}
]}"""));
read("field removed by the reader", v1Bytes, V1, parse("""
{"type": "record", "name": "Customer", "fields": [
{"name": "id", "type": "string"},
{"name": "visits", "type": "int"}
]}"""));
read("int promoted to long", v1Bytes, V1, parse("""
{"type": "record", "name": "Customer", "fields": [
{"name": "id", "type": "string"},
{"name": "name", "type": "string"},
{"name": "visits", "type": "long"}
]}"""));
read("field renamed, with an alias", v1Bytes, V1, parse("""
{"type": "record", "name": "Customer", "fields": [
{"name": "id", "type": "string"},
{"name": "fullName", "type": "string", "aliases": ["name"]},
{"name": "visits", "type": "int"}
]}"""));
read("field renamed, no alias", v1Bytes, V1, parse("""
{"type": "record", "name": "Customer", "fields": [
{"name": "id", "type": "string"},
{"name": "fullName", "type": "string"},
{"name": "visits", "type": "int"}
]}"""));
read("int changed to string", v1Bytes, V1, parse("""
{"type": "record", "name": "Customer", "fields": [
{"name": "id", "type": "string"},
{"name": "name", "type": "string"},
{"name": "visits", "type": "string"}
]}"""));
}
// decodes bytes written with one schema using another: Avro schema resolution
static void read(String change, byte[] bytes, Schema writer, Schema reader)
throws IOException {
try {
var datumReader = new GenericDatumReader<GenericRecord>(writer, reader);
GenericRecord r = datumReader.read(null,
DecoderFactory.get().binaryDecoder(bytes, null));
System.out.printf("%-30s %s%n", change + ":", r);
} catch (AvroTypeException e) {
System.out.printf("%-30s FAILS: %s%n", change + ":", e.getMessage());
}
}
static byte[] write(Schema schema, GenericRecord record) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
BinaryEncoder encoder = EncoderFactory.get().binaryEncoder(out, null);
new GenericDatumWriter<GenericRecord>(schema).write(record, encoder);
encoder.flush();
return out.toByteArray();
}
static Schema parse(String json) {
return new Schema.Parser().parse(json);
}
}
new field with a default: {"id": "c-1", "name": "Ann", "visits": 7, "tier": "standard"}
new field without a default: FAILS: Found Customer, expecting Customer, missing required field tier
field removed by the reader: {"id": "c-1", "visits": 7}
int promoted to long: {"id": "c-1", "name": "Ann", "visits": 7}
field renamed, with an alias: {"id": "c-1", "fullName": "Ann", "visits": 7}
field renamed, no alias: FAILS: Found Customer, expecting Customer, missing required field fullName
int changed to string: FAILS: Found int, expecting string
- A new field with a default was filled in: the v1 data has no
, so the reader got "standard".tier - The same field without a default failed with "missing required field tier": the reader has no value to use. This is the most common breaking change.
- A reader without
simply skipped it in the data.name was promoted toint . Avro allows promotions fromlong toint ,long orfloat , fromdouble tolong orfloat , fromdouble tofloat , and betweendouble andstring .bytes- A rename with
worked: the reader matched its"aliases": ["name"] to the writer'sfullName . Without the alias, it is a removed field plus a new field without a default, and it failed.name toint is not a promotion, and it failed with "Found int, expecting string".string
The writer's schema must be known exactly; a record cannot be decoded with only the reader's schema, because Avro binary carries no field names or types. That is why the schema id travels with every record.
Which changes each level accepts
A compatibility level applies those resolution rules in one or both directions. The program registers a v1 customer schema and tests six typical changes against it under BACKWARDFORWARDFULL
import ch.qos.logback.classic.Level;
import io.confluent.kafka.schemaregistry.avro.AvroSchema;
import io.confluent.kafka.schemaregistry.client.MockSchemaRegistryClient;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CompatibilityMatrix {
static final String V1 = """
{"type": "record", "name": "Customer", "fields": [
{"name": "id", "type": "string"},
{"name": "name", "type": "string"},
{"name": "email", "type": ["null", "string"], "default": null}
]}""";
public static void main(String[] args) throws Exception {
quietLogs();
Map<String, String> changes = new LinkedHashMap<>();
changes.put("add field with default", fields(
"{\"name\": \"id\", \"type\": \"string\"}",
"{\"name\": \"name\", \"type\": \"string\"}",
"{\"name\": \"email\", \"type\": [\"null\", \"string\"], \"default\": null}",
"{\"name\": \"phone\", \"type\": [\"null\", \"string\"], \"default\": null}"));
changes.put("add field without default", fields(
"{\"name\": \"id\", \"type\": \"string\"}",
"{\"name\": \"name\", \"type\": \"string\"}",
"{\"name\": \"email\", \"type\": [\"null\", \"string\"], \"default\": null}",
"{\"name\": \"tier\", \"type\": \"string\"}"));
changes.put("remove field with default", fields(
"{\"name\": \"id\", \"type\": \"string\"}",
"{\"name\": \"name\", \"type\": \"string\"}"));
changes.put("remove field without default", fields(
"{\"name\": \"id\", \"type\": \"string\"}",
"{\"name\": \"email\", \"type\": [\"null\", \"string\"], \"default\": null}"));
changes.put("rename field, with alias", fields(
"{\"name\": \"id\", \"type\": \"string\"}",
"{\"name\": \"fullName\", \"type\": \"string\", \"aliases\": [\"name\"]}",
"{\"name\": \"email\", \"type\": [\"null\", \"string\"], \"default\": null}"));
changes.put("change string to int", fields(
"{\"name\": \"id\", \"type\": \"int\"}",
"{\"name\": \"name\", \"type\": \"string\"}",
"{\"name\": \"email\", \"type\": [\"null\", \"string\"], \"default\": null}"));
List<String> modes = List.of("BACKWARD", "FORWARD", "FULL");
System.out.printf("%-30s %-10s %-10s %-10s%n", "change from v1", "BACKWARD", "FORWARD",
"FULL");
int subject = 0;
for (var change : changes.entrySet()) {
StringBuilder row = new StringBuilder(String.format("%-30s", change.getKey()));
for (String mode : modes) {
// a fresh registry subject holding v1, with this compatibility level
MockSchemaRegistryClient registry = new MockSchemaRegistryClient();
String name = "customers-value-" + subject++;
registry.register(name, new AvroSchema(V1));
registry.updateCompatibility(name, mode);
boolean ok = registry.testCompatibility(name, new AvroSchema(change.getValue()));
row.append(String.format(" %-10s", ok ? "ok" : "REJECTED"));
}
System.out.println(row);
}
}
static String fields(String... fields) {
return "{\"type\": \"record\", \"name\": \"Customer\", \"fields\": ["
+ String.join(", ", fields) + "]}";
}
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);
}
}
change from v1 BACKWARD FORWARD FULL
add field with default ok ok ok
add field without default REJECTED ok REJECTED
remove field with default ok ok ok
remove field without default ok REJECTED REJECTED
rename field, with alias ok REJECTED REJECTED
change string to int REJECTED REJECTED REJECTED
- Adding or removing a field that has a default passed every level. These are the changes to aim for: give every field that may ever be added or removed a default, such as an optional
union with["null", "string"] .null - Adding a field without a default passed only
: old readers ignore it, but new readers cannot read old data.FORWARD - Removing a field without a default passed only
: new readers ignore it in old data, but old readers, which require it, cannot read new data.BACKWARD - The rename with an alias passed
, because the new reader knows the old name, but notBACKWARD : the old reader has no alias forFORWARD .fullName - Changing
from string to int failed everywhere. A type change that is not a promotion needs a new field, or a new topic.id
The level decides who must be upgraded first. Under BACKWARDFORWARDFULL
The transitive trap
The non-transitive levels compare a new schema only with the latest version. A sequence of changes that each pass can still end with a schema that cannot read the oldest data in the topic. Here a payment's amountintstring
import ch.qos.logback.classic.Level;
import io.confluent.kafka.schemaregistry.avro.AvroSchema;
import io.confluent.kafka.schemaregistry.client.MockSchemaRegistryClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TransitiveTrap {
static final AvroSchema V1 = schema(
"{\"name\": \"amount\", \"type\": \"int\"}");
static final AvroSchema V2 = schema(); // amount removed
static final AvroSchema V3 = schema( // amount back, as a string with a default
"{\"name\": \"amount\", \"type\": \"string\", \"default\": \"\"}");
public static void main(String[] args) throws Exception {
quietLogs();
for (String mode : new String[] {"BACKWARD", "BACKWARD_TRANSITIVE"}) {
MockSchemaRegistryClient registry = new MockSchemaRegistryClient();
registry.updateCompatibility("payments-value", mode);
registry.register("payments-value", V1);
System.out.println(mode + ":");
System.out.println(" v2 (amount removed) compatible: "
+ registry.testCompatibility("payments-value", V2));
registry.register("payments-value", V2);
System.out.println(" v3 (amount back as string) compatible: "
+ registry.testCompatibility("payments-value", V3));
for (String problem : registry.testCompatibilityVerbose("payments-value", V3)) {
if (problem.contains("errorType")) {
System.out.println(" " + problem);
}
}
}
// what a BACKWARD-only check let through: v3 readers cannot read v1 data
System.out.println("v3 can read v1 data: " + V3.isBackwardCompatible(V1).isEmpty());
}
static AvroSchema schema(String... extraFields) {
String fields = "{\"name\": \"id\", \"type\": \"string\"}"
+ (extraFields.length > 0 ? ", " + extraFields[0] : "");
return new AvroSchema("{\"type\": \"record\", \"name\": \"Payment\", \"fields\": ["
+ fields + "]}");
}
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);
}
}
BACKWARD:
v2 (amount removed) compatible: true
v3 (amount back as string) compatible: true
BACKWARD_TRANSITIVE:
v2 (amount removed) compatible: true
v3 (amount back as string) compatible: false
{errorType:"TYPE_MISMATCH", description:"The type (path '/fields/1/type') of a field in the new schema does not match with the old schema", additionalInfo:"reader type: STRING not compatible with writer type: INT"}
v3 can read v1 data: false
- Under
, removingBACKWARD passed, and adding it back as a string with a default passed too, because v2 has noamount to conflict with.amount - Under
, v3 was also checked against v1 and rejected withBACKWARD_TRANSITIVE : "reader type: STRING not compatible with writer type: INT".TYPE_MISMATCH - The direct check confirms it: a v3 reader cannot read the v1 records still in the topic. A consumer that replays the topic from the beginning would fail on the first one.
Use a transitive level for topics that are kept for long or replayed, such as compacted topics, event-sourced streams and anything with infinite retention. For topics with a few days of retention, the non-transitive level is enough once all old records have expired.
JSON Schema: open and closed content models
JSON Schema has no defaults in the Avro sense, and its rules depend on additionalProperties
import ch.qos.logback.classic.Level;
import io.confluent.kafka.schemaregistry.json.JsonSchema;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class JsonSchemaCompat {
public static void main(String[] args) {
quietLogs();
for (String model : new String[] {"closed", "open"}) {
boolean closed = model.equals("closed");
JsonSchema v1 = schema(closed, "\"id\": {\"type\": \"string\"}");
JsonSchema addOptional = schema(closed, "\"id\": {\"type\": \"string\"}, "
+ "\"note\": {\"type\": \"string\"}");
JsonSchema removeField = schema(closed, "");
System.out.println(model + " content model (additionalProperties: " + !closed + "):");
report(" add optional property", addOptional, v1);
report(" remove property", removeField, v1);
}
}
// a compatible change has no backward and no forward problems
static void report(String change, JsonSchema next, JsonSchema previous) {
List<String> backward = next.isBackwardCompatible(previous);
List<String> forward = previous.isBackwardCompatible(next);
System.out.printf("%-26s BACKWARD %-8s FORWARD %-8s%s%n", change,
backward.isEmpty() ? "ok" : "REJECTED", forward.isEmpty() ? "ok" : "REJECTED",
firstError(backward.isEmpty() ? forward : backward));
}
static String firstError(List<String> problems) {
for (String p : problems) {
int i = p.indexOf("errorType:\"");
if (i >= 0) {
return " (" + p.substring(i + 11, p.indexOf('"', i + 11)) + ")";
}
}
return "";
}
static JsonSchema schema(boolean closed, String properties) {
return new JsonSchema("{\"type\": \"object\", \"properties\": {" + properties + "}, "
+ "\"additionalProperties\": " + !closed + "}");
}
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);
}
}
closed content model (additionalProperties: false):
add optional property BACKWARD ok FORWARD REJECTED (PROPERTY_REMOVED_FROM_CLOSED_CONTENT_MODEL)
remove property BACKWARD REJECTED FORWARD ok (PROPERTY_REMOVED_FROM_CLOSED_CONTENT_MODEL)
open content model (additionalProperties: true):
add optional property BACKWARD REJECTED FORWARD ok (OPTIONAL_PROPERTY_ADDED_TO_OPEN_CONTENT_MODEL)
remove property BACKWARD ok FORWARD REJECTED (OPTIONAL_PROPERTY_ADDED_TO_OPEN_CONTENT_MODEL)
- With a closed model, adding an optional property was backward compatible: the new schema accepts old documents. It was not forward compatible, because old readers reject the unknown property.
- With a closed model, removing a property was the reverse: new readers would reject old documents that still contain it.
- With an open model, the results flipped. Adding
was rejected as backward incompatible, because under the old open schema, documents could already contain anote of any type.note - Removing a property from an open model was backward compatible: the new schema still accepts it as an additional property.
Neither model gives full compatibility for adding a property. Confluent's documentation describes a third option, a partially open model, where additionalPropertiespatternProperties
A safe process for schema changes
- Keep schemas in source control, as
files, next to the code that produces the data..avsc - In CI, test each change against the registry with the compatibility endpoint or the Schema Registry Maven plugin's compatibility goal, and fail the build on a rejection.
- Register the new version from the pipeline, and run producers with
, so no service can register a version by accident.auto.register.schemas=false - Deploy in the order the level requires: consumers first for
, producers first forBACKWARD .FORWARD - For a change no level accepts, such as a new key or a changed type, write to a new topic, run both versions side by side, and move consumers over.
Changing the compatibility level of a subject to NONE
Traps that break readers
- Defaults that do not match the type: the Avro specification requires a union's default to match its first branch, so
with["null", "string"] is right and"default": null with["string", "null"] is wrong. Avro 1.12's parser accepted the wrong form without an error in a test here, so do not rely on it to catch the mistake.null - Renaming a record or its namespace: the record's full name is part of the schema, and with
it is also the subject. Use aliases on the record, or keep the name.RecordNameStrategy - Enums: adding a symbol breaks old readers unless the enum has a
symbol, which Avro uses for unknown values.default - Semantic changes: changing cents to euros in the same
field passes every check. Compatibility is about structure only; a change of meaning needs a new field.long - Key schemas: even a compatible change to a key schema can change the serialized bytes and move keys to other partitions, breaking ordering and compaction.
Choosing a compatibility level
| Situation | Level |
|---|---|
| Most topics, consumers deployed before producers | BACKWARD |
| Compacted, long-retention or replayed topics | BACKWARD_TRANSITIVE |
| Producers deploy first, for example a central team publishing to many consumers | FORWARDFORWARD_TRANSITIVE |
| Producers and consumers deploy independently | FULL |
| Long-lived shared data with independent teams | FULL_TRANSITIVE |
| Development topics that are thrown away | NONE |
The serializers, subjects and wire format behind these checks are on the