StackPractices
advanced By Mathias Paulenko

Message Schema Evolution Policy (Avro, Protobuf, JSON)

A reusable policy for evolving message schemas safely in event-driven systems: compatibility rules, schema registry requirements, versioning, breaking change procedure, migration checklist, and CI enforcement with Avro, Protobuf, and JSON Schema examples.

Topics: messaging

Overview

Message schemas are a contract between producers and consumers. When a producer changes a schema without governing that change, consumers fail in ways that are hard to trace back: deserialization errors, silently dropped fields, corrupted downstream data. This policy defines the rules every team must follow when evolving message schemas in event-driven systems, and the process for handling changes that can’t stay compatible.

Use it as a template: adapt the normative rules to your organization, fill in the names that fit your platform (registry URL, topic naming convention, ownership model), and publish it as part of your engineering handbook. The examples use Apache Kafka with Confluent Schema Registry, Avro, and Protobuf, but the policy rules apply to any broker and any registry.

When to Use

Adopt this policy when:

  • More than one team produces or consumes the same event topics.
  • Producers and consumers deploy independently, so you can’t guarantee they update in lockstep.
  • You run a schema registry (or are planning one) and need consistent rules for what may change.
  • You’ve been burned by a schema change that took down a consumer in production.

You probably don’t need this policy when:

  • A single service owns both ends of a queue, so the schema lives in the same codebase and ships atomically.
  • Messages are ephemeral commands with a single known consumer and short retention.
  • Your “schemas” are informal JSON payloads on low-stakes topics, though this policy explains why formalizing them still pays off.

If your problem is designing the contract itself (versioned topics, envelope formats, metadata), read the schema registry and evolution pattern first — this document assumes the architectural decisions are already made.

Scope and Roles

In scope: every topic whose messages cross team boundaries: domain events, integration events, CDC streams, and any queue consumed by a service you don’t deploy.

Out of scope: internal implementation details of a single service (its own database schema, in-process message objects, private REST payloads). For database schema changes, use the data migration runbook instead.

RoleResponsibility
Producer teamOwns the schema. MUST register changes before deploying, MUST NOT ship a change that fails the compatibility check without following the breaking change process.
Consumer teamsSHOULD keep deserialization forward-tolerant (ignore unknown fields). MUST migrate off deprecated topics within the published grace period.
Platform teamRuns the schema registry, sets global compatibility levels, and SHOULD block unregistered schemas at the infrastructure level.
Schema owner (per subject)Approves or rejects breaking change requests for that subject. Usually the producer team lead.

The single most common failure mode is an unowned schema: the producing team moved on, nobody watches the subject, and the first consumer to notice a breaking change is the one on call. Every subject in the registry should map to a named owner, and that mapping belongs in code — a service catalog entry, an annotation on the producer service, anything but a wiki page nobody reads.

Policy Rules

Rule identifiers (R1–R12) make it easy to reference violations in code review.

Compatibility Requirements

Compatibility typeOld consumers read new-schema messagesNew consumers read old-schema messages
BackwardYesNo
ForwardNoYes
FullYesYes
Transitive variants (BACKWARD_TRANSITIVE, etc.)Applies the check against all previous versions, not just the latest—
NoneNoNo (breaking)
  • R1 (MUST): Every subject’s compatibility level is BACKWARD by default. Producers deploy before consumers in most release orders, so old consumers must survive new-schema messages.
  • R2 (MUST): Subjects consumed by two or more consumer groups owned by different teams are set to FULL. You can’t control their deployment order.
  • R3 (MUST): Every schema change is registered in the schema registry before the producing code deploys. Committing an unregistered schema to a topic is a policy violation even if it happens to work.
  • R4 (MUST): TRANSITIVE compatibility is used on subjects with more than two active schema versions, so a change is checked against every live version, not just the latest, which would let an already-deployed older consumer break.

Transitive checks are easy to forget and expensive to skip. A subject on plain BACKWARD validates the new schema only against the immediately previous version; a consumer still running the version before that gets no guarantee at all. In practice every long-lived topic accumulates consumers pinned to different versions, so treat transitive as the default for anything more than a year old.

Allowed Changes

These changes are backward-compatible and may ship without any migration. Compatibility varies by format, so check the column for yours.

ChangeAvroProtobufJSON Schema
Add optional field (with default)YesYesYes
Remove a field with a defaultYesYesYes
Add a default to an existing fieldYesN/AYes
Widen a numeric type (int → long, int32 → int64)YesYesN/A
Add a new enum symbolNo*YesYes
Rename a field using an aliasYesNoNo
Add reserved declaration for retired field numbersN/AYesN/A

* Adding an Avro enum symbol breaks consumers that don’t know the new symbol unless a default enum value is configured. Treat it as a breaking change unless you control every consumer.

  • R5 (MUST): Every new field added to a schema carries a default value. No default means old readers see null where they expect data: a silent breakage class that compatibility checks don’t always catch.
  • R6 (SHOULD): New fields are optional (["null", "type"] in Avro, optional in Protobuf 3, absent from required in JSON Schema) rather than required.
  • R7 (MUST): Field numbers in Protobuf are never changed and never reused. Retired numbers are declared reserved so nobody reintroduces them.

Breaking Changes

These changes break existing consumers and require the breaking change process.

ChangeImpactRequired action
Remove a field without a defaultConsumers fail to deserializeNew topic version
Change a field’s typeDeserialization fails or data misinterpretsNew topic version
Rename a field without aliasConsumers can’t find the dataNew topic version
Reuse a retired Protobuf field numberSilent data corruption (the worst outcome)New topic version
Change the message’s key structurePartitioning and joins breakNew topic version
Change namespace/package (Avro fullname)Schema mismatchNew topic version
  • R8 (MUST): Breaking changes ship as a new topic with a versioned suffix: prod.orders.order-created.v1 becomes prod.orders.order-created.v2. Follow your topic naming convention so versions sort and read predictably. Never mutate a schema in place past a failed compatibility check by lowering the subject’s compatibility level to NONE.
  • R9 (MUST): The breaking change process (below) is followed end to end, including the 30-day grace period. Skipping the grace period is how you discover the forgotten consumer at 3 a.m.
  • R10 (SHOULD): Deprecate before you break. Mark legacy fields as deprecated (doc in Avro, [deprecated = true] in Protobuf), announce in the consumer channels, and only proceed to a breaking change after the deprecation window.

Registry and Governance

  • R11 (MUST): No consumer or producer serializes against a locally pasted schema file. Schemas are fetched from the registry at runtime (or generated from registry-pinned versions in CI), so the registry is the single source of truth.
  • R12 (SHOULD): PII and sensitive fields are marked in the schema (custom annotation or documented naming convention like *_pii) so retention and access rules can be enforced automatically downstream.

Examples

Adding an Optional Field (Backward-Compatible)

// v1 — original Avro schema
{
  "type": "record",
  "name": "OrderCreated",
  "namespace": "com.example.orders",
  "fields": [
    {"name": "orderId", "type": "string"},
    {"name": "customerId", "type": "string"},
    {"name": "amount", "type": "double"}
  ]
}

// v2 — backward compatible: optional field with default
{
  "type": "record",
  "name": "OrderCreated",
  "namespace": "com.example.orders",
  "fields": [
    {"name": "orderId", "type": "string"},
    {"name": "customerId", "type": "string"},
    {"name": "amount", "type": "double"},
    {"name": "currency", "type": ["null", "string"], "default": null}
  ]
}
// v2 — backward compatible in Protobuf
message OrderCreated {
  string order_id = 1;
  string customer_id = 2;
  double amount = 3;
  optional string currency = 4;  // new field, new number, optional
}

Deprecating a Field

// Avro — deprecated field stays, documented, removed in v3
{
  "name": "legacyPaymentMethod",
  "type": ["null", "string"],
  "default": null,
  "doc": "DEPRECATED — use paymentMethods. Removal planned for v3."
}
// Protobuf — [deprecated = true] plus the replacement
message OrderCreated {
  reserved 6;  // retired field number, never reuse
  string legacy_payment_method = 4 [deprecated = true];
  repeated string payment_methods = 5;
}

Schema Registry Operations

# Check compatibility before deploying (returns {"is_compatible":true})
curl -X POST \
  -H "Content-Type: application/vnd.schemaregistry.v1+json" \
  --data '{"schema": "<escaped schema json>"}' \
  http://schema-registry:8081/compatibility/subjects/prod.orders.order-created.v1-value/versions/latest

# Set full compatibility on a multi-consumer subject
curl -X PUT \
  -H "Content-Type: application/vnd.schemaregistry.v1+json" \
  --data '{"compatibility": "FULL"}' \
  http://schema-registry:8081/config/prod.orders.order-created.v1-value

The producer and consumer then use registry-backed serializers: the registry validates every produced message against the registered schema:

from confluent_kafka import SerializingProducer, DeserializingConsumer
from confluent_kafka.serialization import StringSerializer
from confluent_kafka.schema_registry import SchemaRegistryClient
from confluent_kafka.schema_registry.avro import AvroSerializer, AvroDeserializer

registry = SchemaRegistryClient({'url': 'http://schema-registry:8081'})

producer = SerializingProducer({
    'bootstrap.servers': 'kafka:9092',
    'key.serializer': StringSerializer('utf_8'),
    'value.serializer': AvroSerializer(registry, order_created_schema),
})

consumer = DeserializingConsumer({
    'bootstrap.servers': 'kafka:9092',
    'group.id': 'payment-service',
    'key.deserializer': StringSerializer('utf_8'),
    'value.deserializer': AvroDeserializer(registry),
    'auto.offset.reset': 'earliest',
})

Breaking Change Procedure

When a change can’t stay compatible, the migration follows a fixed sequence. Don’t improvise it under pressure. Write the runbook before you need it.

flowchart diagram: Schema v2 registered<br/>new topic created
  1. Register the v2 schema and create prod.orders.order-created.v2 with the same partitions and retention as v1.
  2. Update the producer to dual-write: serialize and publish each event to both v1 and v2.
  3. Migrate consumers one team at a time. Each consumer deploys code that reads the v2 topic, then its owner confirms zero lag.
  4. Watch the v1 topic’s consumer groups. kafka-consumer-groups --list plus registry-side subject metadata shows who is still attached.
  5. Once no consumer reads v1, stop the v1 write path in the producer.
  6. Leave v1 idle for the grace period (30 days is the default) with retention shrinking naturally. If a forgotten consumer reconnects, this is your rollback window.
  7. Delete the v1 topic and the v1 subject from the registry.

During migration, consumers that hit malformed or unexpected messages should route them to a DLQ rather than die in a loop. The dead-letter queue runbook covers that pattern.

Consumer Migration Checklist

  • v2 schema registered and compatibility check passed
  • v2 topic created with correct partitions, retention, and ACLs
  • Producer deployed with dual-write to v1 and v2
  • Each consumer team notified with a migration deadline
  • Consumer code updated and deployed against v2
  • Consumer lag on v2 reached zero (caught up)
  • Old consumer group deleted or idle
  • v1 write path disabled after all consumers migrated
  • 30-day grace period elapsed with no v1 activity
  • v1 topic and registry subject deleted

Enforcing the Policy in CI

A policy that lives only in a wiki decays. The same compatibility check the registry runs can run in CI before merge:

  • Schema linting in pull requests. Store schemas in a repository next to the producing code; on every PR, run the compatibility check against the registry (the POST /compatibility/... endpoint above) and fail the build if it returns is_compatible: false.
  • Consumer contract tests. For critical subjects, maintain a small suite that deserializes golden-record messages produced under each live schema version, which catches breaks that the registry’s structural check can’t, like a field that changed semantics but not type.
  • Blocking unregistered writes. Where the platform allows it, configure brokers to reject produce calls that carry no valid schema ID, so bypassing the registry is impossible rather than merely against policy.
  • JSON Schema users don’t get a registry check for free, so run JSON Schema validation in CI against your contract repository instead.

Exceptions and Review

Exceptions exist but they expire. A team that needs a temporary deviation (say, shipping a breaking change during a scheduled migration window — gets a written exception from the schema owner with a fixed end date, recorded next to the subject’s registry metadata. Exceptions without a sunset become permanent, which is how policies die.

Review this policy quarterly, or immediately after any incident where a schema change hurt production. When the review happens, check the grace-period length against real migration times and prune rules nobody can enforce — a rule that’s never applied teaches teams to ignore the rest of the document. A policy that doesn’t get updated after it fails is documentation, not governance.

What Works

  • Defaults on everything. Teams that enforce “every new field has a default” almost never hit the classic breakage where old consumers NPE on a missing field. It costs nothing.
  • Full compatibility on shared topics. The moment a second team consumes your topic, BACKWARD isn’t enough: set FULL and save yourself a cross-team incident.
  • Announcing deprecations in the schema itself. A doc field that says “DEPRECATED — removal in v3” reaches every consumer who regenerates code, which an email doesn’t.
  • Monitoring v1 consumer lag, not just existence. A consumer group that reads nothing for 30 days isn’t migrated — it’s dead. Both states look identical until you check whether the group still fetches.
  • Grace periods that outlast everyone’s sprint planning. 30 days survives vacations, freezes, and the team that only redeploys monthly.

Troubleshooting

Compatibility check rejected a change that looks safe. Check for a field that changed from having a default to not having one, or a renamed field without an alias. Also verify the subject’s compatibility level — a subject set to FULL_TRANSITIVE rejects changes that pass under BACKWARD.

A consumer broke even though the schema was compatible. Structural compatibility isn’t semantic compatibility. If the producer changed what a field means (say, amount became cents instead of dollars), the wire is fine but the data is wrong; that’s a breaking change by this policy even if the registry allows it.

Producer registers to the wrong subject. Subject naming ({topic}-value vs RecordName vs TopicRecordName) must match what consumers expect. Pin auto.register.schemas and the subject name strategy explicitly in producer config instead of relying on defaults.

Dual-write produced duplicates downstream. Consumers that read both v1 and v2 during migration will see each event twice. This is expected, so make consumers idempotent or migrate them in one deploy so they never read both at once.

A consumer forgot to migrate before v1 deletion. This is what the grace period is for. If it still happens, the recovery path is the DLQ/backfill, not republishing v1; restoring a deleted topic’s history is usually impossible.

Adding an Avro enum value broke readers. Adding a symbol to an Avro enum is a breaking change for every consumer that doesn’t know the new symbol, since they fail on unknown enum values. Either set a default enum symbol for the field, or treat the addition as a breaking change and version the topic. Protobuf enums don’t have this trap.

Further Reading

See Also

Frequently Asked Questions

What is the difference between backward and forward compatibility?

Backward compatibility means old consumers can read messages produced with the new schema, for example after adding an optional field. Forward compatibility means new consumers can read messages produced with the old schema. Full compatibility requires both, and is what you want when a topic has two or more consumer teams deploying on their own schedules.

How do I handle schema changes in Protobuf?

Protobuf is designed for evolution: adding optional fields is always safe. Never change or reuse field numbers; they're part of the wire format. Declare removed numbers reserved so they can't come back, and use [deprecated = true] to retire fields before the eventual breaking change.

What happens if a schema change fails the compatibility check?

The registry rejects it and the producer can't serialize with it. By design, incompatible messages never reach the wire. Your options are making the change compatible (add a default, use an alias) or starting the breaking change process with a new versioned topic. Never work around it by disabling the check.

How long should I keep the old topic during migration?

Thirty days after the last consumer finishes migrating. That window covers rollback, forgotten consumers, and teams that deploy monthly. Set retention to expire old messages during the grace period to limit storage, and monitor the v1 consumer groups: a quiet topic is your evidence that deletion is safe.

Should I use Avro, Protobuf, or JSON for message schemas?

Avro if you're in the Confluent ecosystem and want the tightest registry integration. Protobuf if you also use gRPC or want built-in evolution semantics. JSON Schema if you need human-readable payloads and can accept the wire overhead and weaker tooling. Whichever you pick, standardize on one per platform.

Do I need a schema registry for this policy to work?

The rules don't, but the enforcement does. Without a registry there's nothing stopping a breaking change from reaching production — the compatibility check becomes a CI step against a contract repository instead, and you lose runtime validation of every produced message.

How do I enforce schema rules in CI/CD?

Keep schemas in version control next to the producer, and on every PR call the registry's compatibility endpoint for each changed schema. Fail the build on is_compatible: false. For critical subjects, add contract tests that deserialize golden messages under every live schema version.

What if a required change simply cannot be compatible?

That's what breaking changes are for: rename a field, drop a required field, change a type. Follow the breaking change procedure: new versioned topic, dual-write, consumer migration, grace period. The policy forbids breaking in place, not breaking at all.

Should PII go into message schemas?

It can, but mark it. Use a naming convention or schema annotation so downstream systems know which fields to encrypt, mask, or expire. Consumers that don't need PII shouldn't have it at all; that's a separate schema decision, not just an access control one.

What is a data contract and how does it differ from a schema?

A schema describes structure; a contract adds semantics and ownership: what the data means, quality guarantees, and who to page when it breaks. This policy is the governance layer around both: the schema is enforced by the registry, the contract is enforced by your process.