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.

Share

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:

Compatibility levels in Confluent Schema Registry
LevelThe new schema mustChecked againstUpgrade first
BACKWARD (default)Read data written with the previous schemaThe latest versionConsumers
BACKWARD_TRANSITIVERead data written with every earlier schemaAll versionsConsumers
FORWARDWrite data that the previous schema can readThe latest versionProducers
FORWARD_TRANSITIVEWrite data that every earlier schema can readAll versionsProducers
FULLBoth of the aboveThe latest versionEither, independently
FULL_TRANSITIVEBoth, for every versionAll versionsEither, independently
NONENothing: checks are offNothingAll 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 MockSchemaRegistryClient, an in-memory registry: it applies the same compatibility checks through testCompatibility, but unlike a real registry it does not refuse an incompatible schema on register, so the programs call the check explicitly. Registering the schemas in Schema Registry itself is covered on its own page.

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:

Java
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);
    }
}
Output
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 tier, so the reader got "standard".
  • 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 name simply skipped it in the data.
  • int was promoted to long. Avro allows promotions from int to long, float or double, from long to float or double, from float to double, and between string and bytes.
  • A rename with "aliases": ["name"] worked: the reader matched its fullName to the writer's name. Without the alias, it is a removed field plus a new field without a default, and it failed.
  • int to string is not a promotion, and it failed with "Found int, expecting 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 BACKWARD, FORWARD and FULL:

Java
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);
    }
}
Output
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 ["null", "string"] union with null.
  • Adding a field without a default passed only FORWARD: old readers ignore it, but new readers cannot read old data.
  • Removing a field without a default passed only BACKWARD: new readers ignore it in old data, but old readers, which require it, cannot read new data.
  • The rename with an alias passed BACKWARD, because the new reader knows the old name, but not FORWARD: the old reader has no alias for fullName.
  • Changing id from string to int failed everywhere. A type change that is not a promotion needs a new field, or a new topic.

The level decides who must be upgraded first. Under BACKWARD, a new schema may contain changes that only new readers handle, so consumers move first, then producers. Under FORWARD, producers move first. Under FULL, the order does not matter, which is why it suits topics whose producers and consumers belong to different teams.

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 amount is an int in v1, removed in v2, and brought back as a string in v3:

Java
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);
    }
}
Output
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 BACKWARD, removing amount passed, and adding it back as a string with a default passed too, because v2 has no amount to conflict with.
  • Under BACKWARD_TRANSITIVE, v3 was also checked against v1 and rejected with TYPE_MISMATCH: "reader type: STRING not compatible with writer type: INT".
  • 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. A closed model rejects properties it does not list; an open model accepts any. The program adds and removes an optional property under each model and checks both directions:

Java
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);
    }
}
Output
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 note was rejected as backward incompatible, because under the old open schema, documents could already contain a note of any type.
  • 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 additionalProperties is a schema, or patternProperties maps name patterns to schemas, so extra properties are allowed but restricted by type or name. It was not tested here. Java-generated schemas use the closed model, as the Schema Registry page showed, so plan for consumers to be upgraded first when properties are added. Protobuf, the third supported format, has rules based on field numbers; it was not run here because its serializer is not in this environment.

A safe process for schema changes

  1. Keep schemas in source control, as .avsc files, next to the code that produces the data.
  2. 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.
  3. Register the new version from the pipeline, and run producers with auto.register.schemas=false, so no service can register a version by accident.
  4. Deploy in the order the level requires: consumers first for BACKWARD, producers first for FORWARD.
  5. 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 to push a change through is the usual way topics become unreadable. If it is needed, change it back right away and treat the change as a migration to plan.

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 ["null", "string"] with "default": null is right and ["string", "null"] with 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.
  • Renaming a record or its namespace: the record's full name is part of the schema, and with RecordNameStrategy it is also the subject. Use aliases on the record, or keep the name.
  • Enums: adding a symbol breaks old readers unless the enum has a default symbol, which Avro uses for unknown values.
  • Semantic changes: changing cents to euros in the same long field passes every check. Compatibility is about structure only; a change of meaning needs a new field.
  • 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

Situations and the level that fits
SituationLevel
Most topics, consumers deployed before producersBACKWARD, the default
Compacted, long-retention or replayed topicsBACKWARD_TRANSITIVE
Producers deploy first, for example a central team publishing to many consumersFORWARD or FORWARD_TRANSITIVE
Producers and consumers deploy independentlyFULL, with defaults on every optional field
Long-lived shared data with independent teamsFULL_TRANSITIVE
Development topics that are thrown awayNONE, never in production

The serializers, subjects and wire format behind these checks are on the Kafka Schema Registry page. For serialization without a registry, see Kafka serialization.