Schema Registry Enforcement in Kafka

Schema Registry Enforcement in Kafka

How a central schema registry turns Kafka topics from loose piles of bytes into governed data contracts, and how the different layers of enforcement stop bad or breaking data before it hurts anyone.

Imagine a city where every household posts letters to every other household, and nobody has agreed on a language, a format or even which side of the envelope the address goes on. One day the bakery changes its order form, and the delivery company that reads those forms suddenly cannot understand a single one. Deliveries stop, and nobody knows why. Now imagine the city introduces a rule book: every form design must be registered at the town hall, and a change is accepted only if old readers can still make sense of it. That town hall, together with its rule book, is what a schema registry does for Kafka, and the act of applying those rules is called enforcement.

This tutorial walks through the topic step by step. We begin with the problem, meet the schema and the registry, then look at every layer where rules can be enforced, from the producer’s code to the broker to the deployment pipeline. Each new term is explained when it first appears, with an everyday comparison and practical examples.

1The Problem: Kafka Does Not Look Inside Your Data

Understanding why enforcement exists starts with a surprising fact about Kafka itself.

Kafka stores bytes, not meaning

Apache Kafka stores streams of events in topics. Producers write events, consumers read them, and brokers, the servers that form the Kafka cluster, store and deliver them. A key design choice is that the broker treats every event as an opaque sequence of bytes. It does not know whether the bytes describe an order, a temperature or a photograph. This makes Kafka fast and flexible, but it also means Kafka, on its own, will happily accept any bytes from any producer.

What goes wrong without agreement

When producers and consumers are built by different teams, they must agree on the structure of the data: which fields exist, what type each field has and which fields are optional. Without a central place to record and check this agreement, several problems appear over time.

Problem 1

Silent breaking changes

A producer renames or removes a field, and downstream consumers crash or, worse, quietly compute wrong results.

Problem 2

Poison messages

One malformed event blocks a consumer that cannot decode it and keeps failing on the same record.

Problem 3

Undocumented formats

New team members must guess the structure by reading code or sampling messages.

Problem 4

Bloated messages

Sending field names inside every event wastes space and network bandwidth.

Simple Analogy

Kafka is like a postal service that delivers sealed envelopes without opening them. The post office does not care what is written inside. If two neighbours change the way they write their letters without telling each other, the postal service will still deliver them, and the confusion happens only at the recipient’s kitchen table.

“A topic without a schema is a promise nobody wrote down.”

2What Is a Schema and What Is a Schema Registry?

Two ideas form the foundation: the schema, which describes the data, and the registry, which stores and guards those descriptions.

A schema

A schema is a formal description of the structure of a piece of data. It lists the fields, names each one, states its type such as text, whole number or true and false, and says whether it is required or optional. For an order event, a schema may say that there is an order identifier, a customer identifier, a total amount and an optional coupon code.

A schema registry

A schema registry is a separate service that stores schemas, gives each one a unique number called a schema ID, keeps track of their versions over time, and checks whether a new version is allowed. It is not part of the Kafka brokers themselves. Applications talk to it over a simple web interface. The best known implementation is the Confluent Schema Registry, and there are alternatives from the open-source community and from cloud providers that follow similar ideas.

flowchart LR
  P["Producer"] -->|"1. register or look up schema"| R[("Schema Registry")]
  P -->|"2. send event with schema ID"| K["Kafka topic"]
  K -->|"3. deliver event"| C["Consumer"]
  C -->|"4. fetch schema by ID"| R
        
FIG 1 — The registry sits beside Kafka: the events flow through Kafka while schemas are stored in the registry
Simple Analogy

The registry is the town hall’s records office. Every form design is filed there with a reference number. Letters carry only the reference number, not the whole design. Anyone who receives a letter can ask the records office for the design that matches the number.

Where the registry keeps its data

The registry stores its schemas in an internal Kafka topic, so it inherits Kafka’s durability. Several registry instances can run together, with one acting as the leader that handles writes. Because schemas are small and change rarely, the registry is lightweight compared with the Kafka cluster.

Schema
describes the shape of data
Registry
stores, versions and checks schemas
Schema ID
small number that points to a schema

3What Does “Enforcement” Actually Mean?

Having a registry is not the same as enforcing it. Enforcement is the set of checks that make the rules unavoidable.

Schema Registry enforcement means making sure that only data that follows a registered, approved schema can be written to a topic, and that any change to a schema respects the compatibility rules the organisation has chosen. It answers two separate questions. First: is this event valid according to a known schema? Second: is this new version of the schema safe for everyone who depends on the older versions?

Enforcement is a stack of layers

No single switch enforces everything. Enforcement is built from several layers, each catching a different kind of mistake at a different moment. The earlier a mistake is caught, the cheaper it is to fix.

flowchart TB
  L1["Layer 1: Build pipeline checks, before code ships"] --> L2["Layer 2: Registry compatibility rules, when a schema is registered"]
  L2 --> L3["Layer 3: Client serializer checks, when an event is produced"]
  L3 --> L4["Layer 4: Broker schema validation, when an event arrives"]
  L4 --> L5["Layer 5: Governance and access control, who may change what"]
        
FIG 2 — Five layers of enforcement, from the earliest and cheapest to the last line of defence
Simple Analogy

Airport security has several layers: a ticket check at booking, an identity check at the desk, a bag scan, a gate check and cabin crew. No single check catches everything, but together they make it very hard for a problem to reach the aircraft.

!
Common Misconception

Many people believe that installing a schema registry automatically blocks bad data. It does not. The registry only stores schemas and answers questions. Enforcement happens only where clients and brokers are configured to ask those questions and obey the answers.

4How It Works Inside: Schema IDs and the Wire Format

The trick that makes registries efficient is that events carry a tiny reference instead of the full schema.

The shape of an event on the wire

When a producer uses the registry-aware serializer, each event is written in a small envelope. The first byte is a fixed marker that tells readers this event follows the registry format. The next four bytes hold the schema ID. Everything after that is the actual data, encoded compactly using the chosen format. Because the field names and types are stored once in the registry, each event carries only values.

1

Marker byte

A single fixed byte that signals the event uses the registry format, so readers can recognise it.

2

Schema ID

Four bytes holding the number of the schema that was used to write the event.

3

Encoded payload

The field values themselves, packed tightly without repeating field names.

What the producer does

The serializer first checks its local memory to see whether it already knows the schema ID for this data shape. If not, it contacts the registry, either to register the schema or to look up an existing one, depending on configuration. It remembers the answer, so later events need no further calls. It then writes the marker, the ID and the encoded data, and sends the event to Kafka.

What the consumer does

The deserializer reads the marker and the schema ID from the first five bytes. If it has not seen that ID before, it asks the registry for the matching schema and remembers it. It then decodes the rest of the event using that schema, and, if the consumer application expects a slightly different version, resolves the differences between the writer’s schema and its own reader schema.

sequenceDiagram
  participant P as Producer
  participant R as Schema Registry
  participant K as Kafka
  participant C as Consumer
  P->>R: Register or look up schema
  R-->>P: Schema ID 17
  P->>K: Event with ID 17 and data
  K-->>C: Event with ID 17 and data
  C->>R: What is schema 17?
  R-->>C: Schema definition
  C->>C: Decode data using the schema
        
FIG 3 — The schema ID travels with the event, and the schema is fetched only once per ID
Simple Analogy

Instead of stapling the whole instruction manual to every parcel, the sender writes only the manual’s catalogue number on the box. The receiver looks up that number once, keeps a copy of the manual, and reads every later parcel with the same number without asking again.

i
Good to Know

Because of local caching, the registry is asked only when a new schema ID appears. Normal traffic does not need a call to the registry for each event, so the registry is not a bottleneck on the data path.

5Subjects, Versions and Naming Strategies

Schemas are organised into named groups so that each evolves independently and its history is kept.

Subjects

A subject is a named container in the registry that holds the history of one schema as it evolves. Each time a new, accepted version is registered under a subject, it receives the next version number, and a globally unique schema ID. Compatibility rules are applied per subject, comparing new versions against earlier versions in the same subject.

Versions versus IDs

People often mix up versions and IDs. A version is a counter within a subject: first, second, third. An ID is a number unique across the whole registry. The same schema text registered under two subjects shares one ID but is version one in each. Events carry the ID, while humans talk about versions.

Naming strategies

A naming strategy is the rule for choosing the subject name when producing. It decides how strictly a topic is tied to a schema.

StrategySubject Is Based OnBest ForEffect on Enforcement
Topic nameThe topic name plus a suffix for key or valueOne kind of event per topicStrongest: each topic has one evolving contract
Record nameThe fully qualified name of the record typeMany event types in one topic, reused across topicsCompatibility is checked per event type, not per topic
Topic and record nameBoth the topic and the record typeSeveral event types in one topic, but kept separate per topicFine-grained contracts per topic and type
Simple Analogy

A subject is like a folder in the town hall’s cabinet, labelled with the name of one form. Inside, every past design of that form is kept in order. The naming strategy decides how the folders are labelled: by mailbox, by form type, or by both.

!
Design Warning

The default topic-based naming makes it hard to mix several event types in the same topic, because the compatibility check would compare unrelated types. If you intend to mix types in one topic, choose a record-based strategy from the beginning and set expectations for consumers.

6Schema Formats: Avro, Protobuf and JSON Schema

The registry supports several ways of describing data, each with its own strengths.

Format 1

Avro

A compact binary format where the schema is required to read the data. Widely used with Kafka and known for clear evolution rules and default values.

Format 2

Protobuf

A compact binary format from the gRPC world, using numbered fields. Popular where services already share Protobuf definitions.

Format 3

JSON Schema

Describes ordinary JSON documents. Human readable and easy to adopt, but larger on the wire than binary formats.

AspectAvroProtobufJSON Schema
Size on the wireVery compactVery compactLarger, text based
Human readable dataNoNoYes
Field identityBy nameBy field numberBy name
Evolution styleDefaults on added or removed fieldsAdd new numbers, never reuse old onesDepends on openness of the schema
Tooling reachStrong in data platformsStrong in service ecosystemsStrong in web ecosystems
Simple Analogy

The three formats are like three ways to write a shopping list. Avro is a neatly typed list with a legend kept elsewhere. Protobuf is a numbered list where item three always means milk. JSON Schema is a handwritten list with labelled items that anyone can read at a glance but takes more paper.

Choosing a format

Pick the format that your teams already know and that fits your performance and tooling needs. Consistency across the organisation matters more than small differences, because every extra format multiplies the rules, libraries and training needed.

i
Practical Tip

Enforcement works with all three formats, but the details of what counts as a safe change differ. Whichever you choose, write down the evolution rules for your teams in plain language.

7Compatibility Modes: The Heart of Enforcement

When someone registers a new version of a schema, the registry checks it against earlier versions using a chosen compatibility mode.

Two directions of compatibility

Compatibility is about who can read whose data. Backward compatible means that a consumer using the new schema can still read data written with the older schema. Forward compatible means that a consumer still using the older schema can read data written with the new schema. Full compatibility means both directions hold.

Mode 1

Backward

New readers can read old data. This is the usual default. Consumers are upgraded before producers.

Mode 2

Forward

Old readers can read new data. Producers may be upgraded before consumers.

Mode 3

Full

Both directions hold between a version and its neighbour, so upgrade order is flexible.

Mode 4

Transitive variants

The same rules, but checked against every earlier version, not only the latest one.

Mode 5

None

No compatibility check at all. Any change is accepted, so all protection is lost.

ModeChecked AgainstUpgrade OrderTypical Use
BackwardLatest versionConsumers first, then producersMost topics, and replaying old data
Backward transitiveAll earlier versionsConsumers first, then producersTopics that keep long history and are re-read from the start
ForwardLatest versionProducers first, then consumersProducers evolve faster than consumers
Forward transitiveAll earlier versionsProducers first, then consumersMany long-lived consumers on old versions
FullLatest versionAny orderIndependent teams with no coordination
Full transitiveAll earlier versionsAny orderStrictest safety for critical shared data
NoneNothingNot applicableShort-lived experiments only
Simple Analogy

Backward compatibility is like a new edition of a textbook that can still explain old exam papers. Forward compatibility is like an old textbook that can still make sense of the new exam papers because the new questions only add extras it can ignore. Full compatibility means both statements hold.

!
Common Mistake

Using a non-transitive mode on a topic that consumers replay from the beginning. Version three may be compatible with version two, yet not with version one. A consumer replaying old data may then hit events it cannot read. Choose a transitive mode when history matters.

8Safe and Unsafe Changes, and the Order of Upgrades

Compatibility modes are abstract until you see what real changes they allow or block.

Changes that are usually safe

Adding an optional field with a default

Old data has no value for the new field, so new readers fill in the default. Old readers ignore the extra field in new data. This is the most common safe change and works in both directions.

Removing an optional field that has a default

New data simply lacks the field, and old readers use the default. Old data still holds the field, which new readers ignore.

Adding documentation or descriptive text

Comments and descriptions do not change the data layout, so they are always safe.

Changes that usually break something

Adding a required field with no default

New readers cannot make sense of old data that lacks the field. This breaks backward compatibility.

Removing a required field

Old readers expect the field and cannot proceed when it is missing. This breaks forward compatibility.

Renaming a field

To a reader, a rename looks like removing one field and adding another. Unless aliases or field numbers cover it, this is unsafe.

Changing the type of a field

Turning a number into text, or narrowing a large number into a small one, can make old data unreadable. A few widening changes are allowed by the format rules, but most are not.

The order of upgrades

Compatibility also tells you who to upgrade first. Under backward rules, upgrade consumers first so they can already read both old and new data, then upgrade producers. Under forward rules, upgrade producers first, since old consumers can already read the new data. Under full rules, either order works.

flowchart LR
  subgraph B["Backward compatible"]
    B1["Upgrade consumers first"] --> B2["Then upgrade producers"]
  end
  subgraph F["Forward compatible"]
    F1["Upgrade producers first"] --> F2["Then upgrade consumers"]
  end
  subgraph U["Full compatible"]
    U1["Upgrade in any order"]
  end
        
FIG 4 — The compatibility mode decides which side of the pipeline must be upgraded first
Simple Analogy

Changing a road from left-hand to right-hand traffic needs a plan. If readers must understand both first, you train the drivers before repainting the roads. If old drivers can already cope with the new road markings, you can repaint first and train later.

9Layer One: Enforcement in the Client

The first line of defence is the serializer inside the producer application.

What the client checks

When the producer’s serializer receives an object, it converts it into bytes according to a schema. If the object does not match the schema, for example a required field is missing or a value has the wrong type, the serializer fails right there and the event is never sent. This stops malformed data at the source, which is the cheapest place to stop it.

Automatic registration

By default, many serializers automatically register the schema they use if it is not yet in the registry. This is convenient in development, but it means any application can create or change contracts simply by running. In production, many organisations switch automatic registration off, so that schemas are registered only through an approved process, and applications can only use schemas that already exist.

Using the latest approved version

Producers can be told to use the latest version registered for a subject, rather than deriving a schema from their own code. This keeps the code from silently drifting from the approved contract. If the application’s data does not fit that version, serialization fails, which alerts the team early.

Advantages of Client Enforcement

  • Bad data is stopped before reaching Kafka
  • Fast, with no extra network calls after caching
  • Errors appear directly in the producing application
  • Works with any Kafka cluster

Limitations

  • Only works for clients that use the serializer
  • A rogue or old client can bypass it
  • Relies on correct configuration in every application
Simple Analogy

Client-side enforcement is like a mail clerk who refuses to accept an envelope that is not correctly addressed. It catches most mistakes at the counter, but only for those who use the counter. Someone dropping a letter in a side door bypasses the check.

!
Production Warning

Leaving automatic registration on in production lets any developer’s test run change a shared contract. Turn it off for production clients and register schemas through a controlled pipeline.

10Layer Two: Enforcement in the Registry

The registry itself is the referee that decides whether a new schema version may exist at all.

Compatibility checks on registration

When a schema is registered under a subject, the registry compares it with the earlier versions according to the subject’s compatibility setting. If the new version breaks the rule, the registry refuses it and returns an error explaining why. The bad version never receives an ID, so no event can ever carry it. This is the single most important enforcement point for schema evolution.

Global and per-subject settings

A default compatibility level applies to the whole registry, and individual subjects may override it. A good practice is to set a strict global default and permit exceptions only with a clear reason and an owner.

Registry modes

The registry can also be put into different operating modes. In the normal read-write mode, schemas may be added. In read-only mode, no new schemas or changes are accepted, which is useful for locking down production or during migrations. An import mode allows schemas to be loaded with specific IDs when copying from another registry.

Immutability of registered schemas

A registered version is not edited in place. To change a contract, you register a new version. This immutability is what lets events safely carry an ID that always means the same thing.

Control 1

Compatibility level

Decides which changes are accepted, globally and per subject.

Control 2

Read-only mode

Blocks all registrations, locking down a sensitive environment.

Control 3

Import mode

Allows controlled copying of schemas from another registry with their original IDs.

Control 4

Immutable versions

Once registered, a version and its ID never change meaning.

Simple Analogy

The town hall’s clerk compares every new form design with the old ones and stamps it approved only if old readers can still cope. Once stamped, the design is sealed in the cabinet and can never be secretly edited. A different design must be filed as a new version.

11Layer Three: Broker-Side Schema Validation

To stop clients that bypass the serializer, the brokers themselves can check every incoming event.

What it is

Broker-side schema validation is a feature of the Confluent Server distribution of Kafka, which is a commercial platform edition and not part of the plain open-source Apache Kafka broker. When it is turned on for a topic, the broker connects to the registry, and for every event it receives it checks that the event carries a schema ID, and that this ID is registered under the subject that belongs to that topic according to the naming strategy. If not, the broker rejects the event and the producer receives an error.

What it does not do

It is important to understand the limits. The broker checks the schema ID and its association with the subject. It does not open the payload to confirm that the bytes truly match the schema. A client that stamps a valid ID on nonsense bytes would pass the broker check. Broker validation therefore stops raw, unregistered or wrongly-labelled data, but it is not a full content inspection.

flowchart TD
  E["Event arrives at broker"] --> Q1{"Has a schema ID?"}
  Q1 -- "No" --> X1["Reject event"]
  Q1 -- "Yes" --> Q2{"ID registered under the topic's subject?"}
  Q2 -- "No" --> X2["Reject event"]
  Q2 -- "Yes" --> OK["Accept and store event"]
        
FIG 5 — The broker accepts an event only if its schema ID is known and belongs to the topic’s subject
Simple Analogy

A security guard at the sorting office checks that every parcel has a valid reference number that matches the destination. The guard does not open each parcel to check the contents, so a parcel with a valid number but wrong contents can still pass.

Advantages

  • Catches clients that skip the serializer
  • Protects topics regardless of who produces
  • Configured per topic, so it can be rolled out gradually
  • Helps prevent unregistered formats entering shared topics

Disadvantages / Trade-offs

  • Requires a broker distribution that supports it
  • Adds a dependency of brokers on the registry
  • Does not verify the payload content itself
  • Extra work for brokers on the write path
i
Practical Tip

Treat broker validation as a safety net, not a replacement for client checks. Use both: the client catches bad content early, and the broker catches clients that ignore the rules.

12Layer Four: Checks in the Build and Deployment Pipeline

The cheapest time to find a breaking change is before the code ever runs in production.

Schemas as code

Treat schema files like source code: keep them in version control, review changes with pull requests, and give each schema an owner. This gives a history of who changed what and why, and lets the team discuss a change before it is applied.

Compatibility tests in the pipeline

The registry offers a way to test whether a proposed schema would be accepted without actually registering it. A build pipeline can call this check for each changed schema. If the test says the change is incompatible, the build fails and the developer sees the problem within minutes, not after a production incident.

Controlled registration

After a change is reviewed and merged, a deployment step registers the schema in the registry using an account that has permission to do so. Applications themselves then only need permission to read. This separates the power to change contracts from the power to use them.

flowchart LR
  D["Developer edits schema"] --> PR["Pull request and review"]
  PR --> CT["Pipeline runs compatibility test"]
  CT -- "Incompatible" --> F["Build fails, fix the change"]
  CT -- "Compatible" --> M["Merge"]
  M --> RG["Deploy step registers schema"]
  RG --> APP["Applications use approved schema"]
        
FIG 6 — A pipeline that tests, reviews and then registers schemas in a controlled way
Simple Analogy

Before a new building is constructed, the architect’s drawings are inspected by the city. Finding a wrong beam on paper costs an afternoon. Finding it after the walls are up costs months.

i
Good Habit

Require a schema change to be reviewed by at least one representative of a consuming team. They know best what their code assumes about the data.

13Layer Five: Security, Access Control and Governance

Rules mean little if anyone can change them, so the registry needs its own security.

Authenticate and encrypt registry access

Require applications and people to prove who they are when calling the registry, and encrypt the traffic. Otherwise anyone on the network could read or change contracts.

Separate read from write permissions

Give applications read access only. Reserve write access for the deployment pipeline or a small group of schema owners. This prevents accidental or hostile changes at run time.

Control access per subject

In platforms that support it, permissions can be granted on individual subjects or groups of subjects, so a team can manage only its own contracts.

Restrict who can change compatibility and mode

The ability to weaken a compatibility level or flip the registry into another mode is as powerful as changing the schemas themselves. Limit it to administrators.

Protect the registry’s own storage topic

Schemas live in an internal Kafka topic. Only the registry should be able to write to it, and access should be audited like any sensitive topic.

Audit and ownership records

Keep a record of who owns each subject, who approved each change and when it happened. This turns the registry into a governance tool, not just a technical service.

Simple Analogy

The town hall’s cabinet is locked. Everyone can request a copy of a form design, but only authorised clerks can file a new one, and each filing is logged with a name and date.

!
Common Mistake

Giving every application full access to the registry because it is simpler at the start. Any bug or compromised application can then rewrite contracts for everyone.

14Data Contracts and Rules Beyond Structure

A schema says what shape data has. A data contract also says what values are acceptable and who is responsible.

The limit of structure alone

A schema can say that an age field is a whole number, but it cannot say that the number must be between zero and one hundred and fifty. A structurally valid event can still be meaningless. Recent versions of schema registry platforms extend schemas into data contracts by adding more information beside the structure.

What a data contract can carry

Element 1

Metadata

Owner, team, description, classification of sensitive fields and a lifecycle status.

Element 2

Domain rules

Value checks such as ranges, formats and relationships between fields, evaluated when data is produced or consumed.

Element 3

Migration rules

Instructions for transforming data between incompatible versions, so a breaking change can be introduced with a controlled conversion.

Element 4

Failure handling

What to do when a rule fails: reject the event, send it to a separate error topic, or record it for review.

Simple Analogy

A schema is the layout of a form: name box, age box, address box. A data contract adds the rules a clerk checks: the age must be a sensible number, the postal code must have the right pattern, and who to call if the form is wrong.

Handling invalid events gracefully

When a rule fails, throwing away the event or crashing the pipeline are both harsh choices. A common approach is to route the failing event to a dedicated error topic, called a dead letter topic, along with a reason. Teams can then inspect, fix and reprocess these events without blocking the good ones.

i
Availability Note

Data contract features and their exact names differ between registry products and versions. Check what your chosen platform supports before designing around them.

15Life of a Schema Change, End to End

A worked example in words shows how the layers cooperate when a team adds a field.

1

The team proposes the change

The payments team wants to add an optional coupon code to the order event. They edit the schema file in version control and open a pull request.

2

The pipeline tests compatibility

The pipeline asks the registry whether the new version is acceptable under the subject’s rule. Because the new field is optional with a default, the test passes.

3

Reviewers from consuming teams approve

The billing and analytics teams confirm that ignoring an extra field is safe for their code, and approve the pull request.

4

The deploy step registers the schema

A controlled account registers the new version. It receives a new version number and a new schema ID.

5

Consumers upgrade first

Under backward rules, consumers are updated to understand the new version, while they still happily read old events.

6

Producers start using the new version

The payments application now writes events with the new ID. The broker check passes because the ID is registered under the topic’s subject.

7

The team watches the metrics

Error rates, consumer lag and rejected events are watched for a while to confirm the rollout is healthy.

i
Insight

Notice that no step required stopping the system. Enforcement lets independent teams change data safely while everything keeps running.

16Breaking Changes Done Safely

Sometimes a real breaking change is unavoidable. The enforcement system does not forbid it. It forces you to do it carefully.

The new-topic approach

The most common safe method is to create a new topic with a new subject and a new, incompatible schema, then move producers and consumers across gradually. During the transition, a small translation application can read the old topic, convert events and write them to the new topic, so both sides continue to work. Once all consumers have moved, the old topic is retired.

flowchart LR
  OP["Old producers"] --> OT["Old topic, old schema"]
  OT --> TR["Translator application"]
  TR --> NT["New topic, new schema"]
  NP["New producers"] --> NT
  OT --> OC["Old consumers, migrating"]
  NT --> NC["New consumers"]
        
FIG 7 — A translator bridges old and new topics so teams can migrate at their own pace

Migration rules

On platforms that support migration rules, a breaking change can be published as a new schema version together with a rule describing how to convert between the old and new shapes. Readers on either version then get data converted for them, allowing a smooth changeover without a separate topic.

Never bypass the check by weakening the rule

When the registry rejects a change, the tempting shortcut is to switch the compatibility level to none, register the change, and switch it back. This defeats the entire purpose and is how most schema-related outages begin. Use it only in a genuine emergency, with sign-off, and with a plan to repair the damage.

Simple Analogy

If a city wants to change the format of all its official forms, it does not simply announce the change overnight. It runs the old and new forms side by side, provides a conversion desk, and closes the old form only when nobody uses it any more.

!
Serious Warning

Temporarily turning compatibility off is like removing the lock from the town hall cabinet for an afternoon. Anything might be filed, and you may not notice until much later.

17Availability, Caching and Failure of the Registry

Adding a registry adds a dependency, so we must understand what happens if it is slow or down.

What still works when the registry is down

Because clients cache schemas, a producer or consumer that already knows the schemas it needs can continue working during a registry outage. Existing schema IDs resolve from local memory, and events flow as usual. This makes short outages much less harmful than they might seem.

What stops working

New producers or consumers starting up with empty caches cannot fetch schemas, and cannot start processing. A producer that needs to register or look up a new schema cannot proceed. If broker-side validation is on, the broker needs the registry to validate unfamiliar IDs, so brokers may reject events until the registry returns, unless their caches already cover the schemas in use.

Designing for resilience

Run several registry instances

Run multiple instances across zones behind a load balancer, so one failure does not stop schema lookups.

Warm caches before peak traffic

Restarts during an outage are the riskiest. Avoid deploying applications while the registry is unhealthy.

Protect the storage topic

Give the registry’s internal topic a high replication factor and safe settings, since it is the only source of truth for schemas.

Back up and export schemas

Keep exported copies of schemas in version control, so the registry can be rebuilt if something goes badly wrong.

Simple Analogy

If the town hall closes for a day, people who already have copies of the form designs can keep writing letters. Only newcomers who need a first copy, or clerks needing to file something new, are stuck until it reopens.

18Multiple Environments, Regions and Migration

Real organisations run development, test and production, and often several clusters. Schemas must travel with the data.

Keeping environments aligned

Each environment normally has its own registry. Because schema IDs are assigned by each registry, the same schema may have different IDs in different environments. Promoting a schema from test to production means registering it again in production through the same pipeline, not copying IDs by hand.

Replicating data across clusters

When events are copied from one Kafka cluster to another, the schema IDs inside them must still resolve on the other side. There are two approaches. One keeps a single shared registry that both clusters use. The other synchronises schemas between registries, preserving IDs, using features such as schema linking on platforms that provide it, or the import mode described earlier.

Schema contexts

Some registries support contexts, which are separate namespaces inside one registry. They allow schemas from different sources or environments to live side by side without their names or IDs clashing.

ApproachHow It WorksBest WhenWatch Out For
Single shared registryAll clusters use one registryNearby clusters, one team owning governanceRegistry becomes a wide dependency
Synchronised registriesSchemas copied with IDs preservedSeparate regions or organisationsKeeping the copy consistent and read-only
Separate environments, promote by pipelineSame schema registered in each environmentTest to production flowIDs differ between environments
!
Common Mistake

Copying events between clusters without also making the schemas available. Consumers on the far side then see schema IDs they cannot resolve, and every event becomes unreadable.

Simple Analogy

If a letter written in one city is sent to another city, the reference number on it is useless unless the second city’s records office has the same form design filed under the same number.

19Deleting and Retiring Schemas

Schemas are meant to be permanent, so deletion needs special care.

Soft and permanent deletion

Registries usually offer two stages of deletion. A soft delete hides a version or a subject from normal listings but keeps the underlying schema so existing events can still be decoded. A permanent delete removes it completely, after which any event carrying that ID becomes unreadable. Permanent deletion should be extremely rare and follow a soft delete.

When deletion is justified

Deleting makes sense for experimental schemas that never carried real data, or when a topic has been fully retired and all its retained events have expired. It does not make sense while any topic still holds events written with that schema, including archives or backups.

Simple Analogy

Throwing away the instruction manual for a product while thousands of boxes with that product are still sitting in warehouses makes those boxes impossible to open. Shelve the manual out of sight first, and destroy it only after the last box is gone.

!
Serious Warning

Permanently deleting a schema that is still in use makes all events with that ID unreadable, with no easy recovery. Always check retention, replay needs and archives before deleting.

20Monitoring Enforcement

Enforcement is only useful if you can see it working and notice when it does not.

SignalWhat It Tells YouTypical Response
Registration rejectionsSomeone tried an incompatible changeReview the change with the owning team
Serialization errors in producersData does not match the schemaFix the application or the schema
Deserialization errors in consumersUnknown IDs or unreadable dataCheck registry access and schema versions
Events rejected by broker validationA client bypassed or misused the serializerFind and fix the offending client
Registry latency and errorsRegistry health and loadScale instances, check dependencies
Compatibility level changesSomeone weakened protectionAlert immediately and verify authorisation
Growth in number of schemas and versionsSchema sprawlReview ownership and clean up unused subjects

Auditing who changed what

Keep logs of every registration, compatibility change, mode change and deletion, with the caller’s identity. Alert on changes to compatibility levels and modes in production, since these are the moves that weaken enforcement.

Dead letter topics as a signal

If invalid events are routed to a dead letter topic, its volume is a valuable quality indicator. A sudden rise usually points to a producer change or a broken upstream system.

Simple Analogy

A smoke detector is useful only if someone hears the alarm. Monitoring enforcement means listening for the alarms: rejected forms at the counter, letters that cannot be read, and anyone unlocking the cabinet at odd hours.

21Design Patterns and Anti-Patterns

Practices that keep contracts healthy, and the traps that quietly undo them.

Patterns worth adopting

Default to a strict, transitive compatibility level

Start strict for shared topics. Loosening later is easy, while repairing damage from a loose start is painful.

Optional fields with defaults as the standard way to add data

Make it a team habit that new fields are optional and carry defaults, so most changes are naturally safe.

Schema owners per subject

Every subject has a named owning team that reviews all changes and is contactable when problems arise.

Pipeline-driven registration

Only a controlled deployment step registers schemas in production. Applications have read access only.

Anti-patterns to avoid

ANTI-PATTERN-01 Avoid
Problem

Leaving the compatibility level at none for convenience, especially on shared production topics.

Why It’s Harmful

Any change is accepted, including breaking ones. The registry becomes a record-keeper that offers no protection, and failures appear only in consumers at run time.

Correct Approach

Choose a real compatibility mode that matches your upgrade practice, and make exceptions rare, temporary and approved.

ANTI-PATTERN-02 Avoid
Problem

Relying on automatic schema registration by production applications.

Why It’s Harmful

Any deployment can create or change contracts without review, and a small code change can silently publish a new schema version.

Correct Approach

Disable automatic registration in production and register through a reviewed pipeline.

ANTI-PATTERN-03 Avoid
Problem

Enforcing only at the client, and assuming that every producer will always use the serializer correctly.

Why It’s Harmful

A forgotten script, a test tool or an old application can write raw bytes to a shared topic, and consumers will fail on them.

Correct Approach

Add broker-side validation where available, and restrict who may produce to shared topics through access control.

ANTI-PATTERN-04 Avoid
Problem

Reusing or repurposing an existing field to hold a different kind of data, such as reusing a field for a new meaning.

Why It’s Harmful

Old events are silently misread by new code, and structural checks cannot detect the change of meaning.

Correct Approach

Add a new field for the new meaning, and retire the old field gradually with clear documentation.

ANTI-PATTERN-05 Avoid
Problem

Putting everything in one giant schema with dozens of optional fields, to avoid ever making a new one.

Why It’s Harmful

Nobody knows which fields are really used together. The contract becomes vague and hard to validate or understand.

Correct Approach

Model distinct business events as distinct schemas, with clear names and owners.

22A Rollout Plan for Introducing Enforcement

Turning on every layer at once in a busy organisation causes friction. A staged approach works better.

flowchart TD
  A["Stage 1: Inventory topics and formats"] --> B["Stage 2: Adopt registry and serializers for new topics"]
  B --> C["Stage 3: Set compatibility levels and owners"]
  C --> D["Stage 4: Add pipeline checks and controlled registration"]
  D --> E["Stage 5: Disable auto-registration in production"]
  E --> F["Stage 6: Turn on broker validation for critical topics"]
  F --> G["Stage 7: Add rules, monitoring and audits"]
        
FIG 8 — A staged path from no enforcement to a fully governed set of topics
1

Take stock

List existing topics, who produces and consumes them, and what format the data uses. Identify the most critical shared topics first.

2

Start with new topics

Require the registry and a compatible serializer for every new topic. This stops the problem growing while you work on old topics.

3

Set rules and owners

Choose default compatibility levels and assign an owning team to each subject.

4

Automate the checks

Add compatibility tests to build pipelines, and move registration into a controlled deploy step.

5

Tighten production

Turn off automatic registration and restrict write permissions on the registry.

6

Add the safety net

Enable broker-side validation on the most important topics, one at a time, watching for surprises from legacy clients.

7

Mature the practice

Add data contract rules, dashboards, alerts and regular audits, and review ownership periodically.

i
Change Management Tip

Treat this as a change in team habits as much as a technical change. Provide templates, examples and quick help, so following the rules is easier than avoiding them.

23Best Practices and Common Mistakes

A checklist to keep close when designing or reviewing enforcement.

Best Practices

  • Use a strict compatibility level, transitive for long-lived topics
  • Add optional fields with defaults, never required ones
  • Keep schemas in version control with reviews
  • Test compatibility in the build pipeline
  • Disable auto-registration in production
  • Give applications read-only registry access
  • Use broker validation as a safety net on critical topics
  • Assign an owner to every subject
  • Alert on any weakening of compatibility rules

Common Mistakes

  • Assuming the registry alone blocks bad data
  • Setting compatibility to none to get past an error
  • Renaming or repurposing fields
  • Ignoring replay needs when choosing non-transitive modes
  • Deleting schemas that old events still use
  • Copying events across clusters without schemas
  • Giving every application write access
  • Mixing event types in one topic without a matching naming strategy
  • Forgetting that broker validation checks IDs, not content
!
Reminder

Structural checks cannot catch a change of meaning. Two fields with the same name and type can still mean different things. Communication and review by consuming teams remain essential.

Simple Analogy

Enforcement is like traffic rules. Signs, signals and speed cameras prevent most accidents, but drivers who understand why the rules exist and talk to each other prevent the rest.

24Real-World Scenarios

Five common situations show enforcement at work.

Scenario 1: A retail company with many teams sharing order events

Dozens of teams consume the order topic. The organisation sets full transitive compatibility on it, requires pull request review from consumer representatives, and registers schemas only from the pipeline. Teams can add fields without coordinating release dates.

Scenario 2: A bank protecting payment events

Payment topics use strict compatibility, restricted write access, broker-side validation and domain rules that reject impossible amounts. Rejected events go to a dead letter topic for investigation, and an alert fires on any compatibility change.

Scenario 3: A data platform team cleaning up legacy topics

Old topics carry loosely structured text. The team introduces new registry-backed topics with translators from the old ones, moves consumers over gradually, and retires the legacy topics once the last consumer has moved.

Scenario 4: Two regions replicating events

An organisation runs clusters in two regions. It synchronises schemas between the registries with their IDs preserved, marks the secondary registry as read-only, and monitors that every ID in replicated events resolves on both sides.

Scenario 5: A startup moving fast

A small team keeps automatic registration on in development but off in production. Schemas live in the same repository as the code, and a pipeline check blocks incompatible changes. The cost is small and prevents most problems.

ScenarioMain Layers UsedKey Concern
Retail order eventsRegistry rules, pipeline, reviewsMany independent consumers
Bank paymentsAll layers plus domain rulesCorrectness and audit
Legacy cleanupNew topics, translatorsGradual migration
Two-region replicationSynchronised registriesIDs resolving everywhere
Fast-moving startupPipeline check, client settingsLow overhead, real protection

25Frequently Asked Questions

Q1Does Kafka itself validate the structure of my data?

No. Brokers treat events as bytes. Structural checks come from serializers, the schema registry and optional broker-side validation on platforms that support it.

Q2Is the schema stored inside every message?

No. Each message carries a small marker and a schema ID. The schema itself lives in the registry and is fetched once and cached.

Q3Which compatibility mode should I choose?

Backward is a common default. If consumers may replay old data, use a transitive version. If you cannot control upgrade order across many teams, full transitive gives the most freedom. Avoid none except for short-lived experiments.

Q4What happens if a producer sends data that does not match the schema?

The serializer fails and the event is not sent. This stops bad data at the source, before it reaches Kafka.

Q5Can a producer bypass the registry?

Yes, if nothing on the broker side checks. A client that writes raw bytes can send them to the topic. Broker-side validation and access control on producing reduce this risk.

Q6Does broker-side validation check the whole message?

No. It checks that the event carries a schema ID registered under the topic’s subject. It does not confirm that the payload truly follows the schema.

Q7Is broker-side validation available in every Kafka distribution?

No. It is a feature of a commercial platform edition of the broker, not of the plain open-source Apache Kafka broker, so check what your distribution offers.

Q8What if the registry goes down?

Running applications continue using their cached schemas. New starts, new schema registrations and validation of unfamiliar IDs are affected until it returns. Running several instances lowers the risk.

Q9Can I change a field’s type?

Only in limited ways allowed by the format’s rules, such as certain widenings. Most type changes break compatibility, and are best handled by adding a new field or a new topic.

Q10How do I handle a truly breaking change?

Create a new topic and subject, bridge with a translator, migrate consumers, and retire the old topic. Some platforms also allow migration rules that convert between versions.

Q11Should applications be allowed to register schemas themselves?

Convenient in development, but risky in production. Prefer registering through a reviewed pipeline and giving applications read-only access.

Q12Is a schema registry the same as a data contract?

Not exactly. A schema is the structural part. A data contract adds ownership, metadata, value rules and handling of failures, and builds on the registry.

26Summary and Key Takeaways

Kafka moves bytes without understanding them, so agreements about the shape of data must be recorded and enforced elsewhere. A schema registry stores schemas with versions and IDs, and lets producers and consumers refer to a contract by a tiny number. Enforcement is the practice of making those contracts unavoidable, through several layers: pipeline checks, registry compatibility rules, client serializers, broker-side validation and access control.

Good enforcement is strict where data is shared, automated where humans forget, and observable where things can go wrong. If you remember one sentence, let it be this: the registry keeps the contracts, but only the layers you switch on will make anyone obey them.

Key Takeaways

  • Kafka does not inspect data — brokers store bytes, so structure must be agreed and checked through schemas and a registry.
  • Events carry an ID, not a schema — a marker and a four-byte schema ID let clients fetch and cache the schema once.
  • Compatibility modes are the core rule — backward, forward and full, with transitive variants, decide which changes are accepted and which side to upgrade first.
  • Enforcement has layers — pipeline tests, registry checks, client serializers, broker validation and access control each catch different mistakes.
  • Broker validation checks IDs, not content — it is a valuable safety net on supported platforms, but does not inspect the payload itself.
  • Control who can change contracts — turn off auto-registration in production, register through a pipeline, and give applications read-only access.
  • Plan for breaking changes and failures — use new topics or migration rules for real breaks, keep schemas available across clusters, run the registry with redundancy, and monitor rejections and rule changes.