🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Schema Registry: Avro, Protobuf, Compatibility Modes

Apache KafkaSchema Registry⭐ Premium

Schema Registry: Avro, Protobuf, Compatibility Modes

Difficulty: Senior | Asked at: Confluent, LinkedIn, Netflix, Uber

â„šī¸Interview Context

Schema Registry is essential for data governance in Kafka. Interviewers expect you to understand schema evolution, compatibility modes, and how to handle breaking changes gracefully.

The Question

How does Schema Registry work? Explain the difference between Avro, Protobuf, and JSON Schema. What are the compatibility modes and how do you handle schema evolution?

Schema Registry Architecture

Schema Registry ClusterRegistry 1 │ │ Registry 2 │ │ Registry 3(Leader) │ │ (Follower) │ │ (Follower)↑ ↑ ↑KafkaTopic:_schemasProducer/Consumer+--> Schema Registry (HTTP API)| GET/POST /subjects/{topic}/versions+--> Kafka TopicMessages encoded with schema ID

The registry is a small stateful service whose state happens to live in Kafka. Every registered version is written to the _schemas topic, so the registry itself can be rebuilt by replaying that topic, and running several instances behind a load balancer gives high availability without introducing a separate database. Producers and consumers interact with it over HTTP at registration and lookup time, but the data path bypasses it entirely: a message carries a four-byte schema id immediately after the magic byte, and readers resolve that id from a local cache, falling back to the registry only on a miss. That design is why the registry does not sit in the critical path of every produce call, and also why a registry outage degrades schema evolution rather than stopping traffic. What the registry truly enforces is policy: it decides whether a proposed new version may be registered at all, based on the compatibility mode configured for that subject.

Schema Formats

The format decides both the wire size and how much the schema can express, and each is optimised for a different kind of contract.

Avro Schema

{
  "type": "record",
  "name": "User",
  "namespace": "com.example",
  "fields": [
    {"name": "id", "type": "long"},
    {"name": "name", "type": "string"},
    {"name": "email", "type": ["null", "string"], "default": null},
    {"name": "created_at", "type": "long", "logicalType": "timestamp-millis"}
  ]
}

Protobuf Schema

syntax = "proto3";
package com.example;

message User {
  int64 id = 1;
  string name = 2;
  optional string email = 3;
  int64 created_at = 4;
}

JSON Schema

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "User",
  "type": "object",
  "properties": {
    "id": {"type": "integer"},
    "name": {"type": "string"},
    "email": {"type": ["string", "null"]},
    "created_at": {"type": "integer"}
  },
  "required": ["id", "name"]
}

Schema Format Comparison

FeatureAvroProtobufJSON Schema
Binary encodingYesYesNo (text)
Schema evolutionExcellentGoodFair
Default valuesYesYesYes
Code generationYesYesLimited
PerformanceFastestFastSlowest
Human readableNoNoYes

â„šī¸Format Selection

  • Avro: Best for Kafka. Excellent schema evolution, compact binary format, strong compatibility checking.
  • Protobuf: Good for gRPC integration. Slightly less flexible schema evolution.
  • JSON Schema: Best for human readability. Larger payloads, slower parsing.

Compatibility Modes

Compatibility is a property of the direction data must be readable, and choosing a mode is really choosing which side of a deployment is allowed to move first. Backward compatibility means a new schema can read data written with the previous schema, which is what you need when new consumers will read old messages during a rolling deploy. Forward compatibility means an old schema can still read data written with the new schema, which is what you need when old consumers are still running after producers upgrade. Full compatibility is both at once and is the usual choice for topics that several teams consume at different release cadences. Two practical notes: the mode is stored per subject, so one topic can be strict while an internal topic stays flexible, and the default of none means registration succeeds even when a change would break every existing reader.

BACKWARD Compatible

python
# BACKWARD: New schema can read old data
# Old consumers can read new data

# Old schema (v1)
old_schema = {
    "type": "record",
    "name": "User",
    "fields": [
        {"name": "id", "type": "long"},
        {"name": "name", "type": "string"}
    ]
}

# New schema (v2) - ADD field with default
new_schema = {
    "type": "record",
    "name": "User",
    "fields": [
        {"name": "id", "type": "long"},
        {"name": "name", "type": "string"},
        {"name": "email", "type": ["null", "string"], "default": null}  # NEW
    ]
}

# BACKWARD compatible:
# - New schema can read old data (email defaults to null)
# - Old consumers can't read new data (they don't know about email)

FORWARD Compatible

python
# FORWARD: Old schema can read new data
# New consumers can read old data

# Old schema (v1)
old_schema = {
    "type": "record",
    "name": "User",
    "fields": [
        {"name": "id", "type": "long"},
        {"name": "name", "type": "string"},
        {"name": "email", "type": ["null", "string"], "default": null}
    ]
}

# New schema (v2) - REMOVE field
new_schema = {
    "type": "record",
    "name": "User",
    "fields": [
        {"name": "id", "type": "long"},
        {"name": "name", "type": "string"}
        # email removed
    ]
}

# FORWARD compatible:
# - Old schema can read new data (ignores unknown fields)
# - New consumers can read old data (email field ignored)

FULL Compatible

python
# FULL: Both backward and forward compatible

# Allowed changes:
# 1. Add field with default value
# 2. Remove field with default value
# 3. Rename field (with aliases)

# Example:
v1 = {
    "type": "record",
    "name": "User",
    "fields": [
        {"name": "id", "type": "long"},
        {"name": "name", "type": "string"},
        {"name": "email", "type": "string"}
    ]
}

v2 = {
    "type": "record",
    "name": "User",
    "fields": [
        {"name": "id", "type": "long"},
        {"name": "full_name", "type": "string", "aliases": ["name"]},  # Renamed
        {"name": "email_address", "type": "string", "aliases": ["email"]}  # Renamed
    ]
}

# FULL compatible:
# - Old data readable by new schema (uses aliases)
# - New data readable by old schema (uses original names)

Compatibility Mode Matrix

ModeAdd FieldRemove FieldRename FieldChange Type
BACKWARDYes (with default)NoNoNo
FORWARDNoYes (with default)NoNo
FULLYes (with default)Yes (with default)Yes (with aliases)No
NONEYesYesYesYes

âš ī¸Compatibility Warning

Setting compatibility mode to NONE disables all checks. This is dangerous in production. Always use BACKWARD, FORWARD, or FULL compatibility.

Schema Evolution Strategies

Most schema changes fall into four patterns, and the safe version of each is dictated by the compatibility mode rather than by taste. Adding a field is safe only when the new field carries a default, because a reader holding the older schema has to produce some value for data it cannot see. Removing a field is a two-phase operation: stop writing it, wait at least as long as your retention window so old messages age out, then remove it from the schema. Renaming a field is a removal and an addition in disguise unless you declare an alias, which is the only mechanism that lets readers map the old name onto the new one. Type changes are limited to a small promotion ladder, and staying inside that ladder is what keeps both directions readable.

Adding Fields

python
# Strategy: Add field with default value
# This is always safe for BACKWARD compatibility

# v1
schema_v1 = {
    "type": "record",
    "name": "Order",
    "fields": [
        {"name": "order_id", "type": "string"},
        {"name": "amount", "type": "double"},
        {"name": "currency", "type": "string"}
    ]
}

# v2 - Add optional field
schema_v2 = {
    "type": "record",
    "name": "Order",
    "fields": [
        {"name": "order_id", "type": "string"},
        {"name": "amount", "type": "double"},
        {"name": "currency", "type": "string"},
        {"name": "discount_code", "type": ["null", "string"], "default": null}
    ]
}

# v3 - Add required field with default
schema_v3 = {
    "type": "record",
    "name": "Order",
    "fields": [
        {"name": "order_id", "type": "string"},
        {"name": "amount", "type": "double"},
        {"name": "currency", "type": "string"},
        {"name": "discount_code", "type": ["null", "string"], "default": null},
        {"name": "priority", "type": "string", "default": "standard"}
    ]
}

Removing Fields

python
# Strategy: Deprecate then remove
# Phase 1: Stop producing the field (but still accept it)
# Phase 2: Remove from schema after retention period

# v1 - Field exists
schema_v1 = {
    "type": "record",
    "name": "Order",
    "fields": [
        {"name": "order_id", "type": "string"},
        {"name": "amount", "type": "double"},
        {"name": "deprecated_field", "type": "string"}
    ]
}

# v2 - Field deprecated (still in schema for backward compat)
schema_v2 = {
    "type": "record",
    "name": "Order",
    "fields": [
        {"name": "order_id", "type": "string"},
        {"name": "amount", "type": "double"},
        {"name": "deprecated_field", "type": "string", "doc": "DEPRECATED: will be removed"}
    ]
}

# v3 - Field removed (after retention period)
schema_v3 = {
    "type": "record",
    "name": "Order",
    "fields": [
        {"name": "order_id", "type": "string"},
        {"name": "amount", "type": "double"}
    ]
}

Renaming Fields

python
# Strategy: Use aliases for backward compatibility
schema_v1 = {
    "type": "record",
    "name": "User",
    "fields": [
        {"name": "id", "type": "long"},
        {"name": "name", "type": "string"}
    ]
}

schema_v2 = {
    "type": "record",
    "name": "User",
    "fields": [
        {"name": "user_id", "type": "long", "aliases": ["id"]},
        {"name": "full_name", "type": "string", "aliases": ["name"]}
    ]
}

# Aliases allow old data to be read with new field names
# And new data to be read with old field names

Type Promotion

python
# Avro supports safe type promotions
# Int -> Long -> Float -> Double

schema_v1 = {
    "type": "record",
    "name": "Product",
    "fields": [
        {"name": "price", "type": "int"}  # $19.99 stored as 1999 cents
    ]
}

schema_v2 = {
    "type": "record",
    "name": "Product",
    "fields": [
        {"name": "price", "type": "long"}  # Promoted to long
    ]
}

# This is FULL compatible because:
# - Old int data can be read as long
# - New long data can be read as int (with truncation warning)

â„šī¸Evolution Best Practice

  1. Always add fields with default values
  2. Never remove required fields without deprecation period
  3. Use aliases for renames
  4. Test compatibility before deploying schema changes

Schema Registry API

Register Schema

python
import requests
import json

class SchemaRegistryClient:
    def __init__(self, registry_url):
        self.registry_url = registry_url
    
    def register_schema(self, subject, schema, schema_type='AVRO'):
        """Register a new schema version"""
        url = f"{self.registry_url}/subjects/{subject}/versions"
        
        payload = {
            'schema': json.dumps(schema),
            'schemaType': schema_type
        }
        
        response = requests.post(url, json=payload)
        response.raise_for_status()
        
        return response.json()  # {'id': 1, 'subject': '...', 'version': 1}
    
    def get_schema(self, subject, version='latest'):
        """Get schema by version"""
        url = f"{self.registry_url}/subjects/{subject}/versions/{version}"
        response = requests.get(url)
        response.raise_for_status()
        return response.json()
    
    def get_schema_by_id(self, schema_id):
        """Get schema by ID"""
        url = f"{self.registry_url}/schemas/ids/{schema_id}"
        response = requests.get(url)
        response.raise_for_status()
        return response.json()
    
    def check_compatibility(self, subject, schema):
        """Check if schema is compatible"""
        url = f"{self.registry_url}/subjects/{subject}/compatibility"
        payload = {'schema': json.dumps(schema)}
        response = requests.post(url, json=payload)
        response.raise_for_status()
        return response.json()  # {'is_compatible': true}
    
    def set_compatibility_mode(self, subject, mode):
        """Set compatibility mode for subject"""
        url = f"{self.registry_url}/config/{subject}"
        payload = {'compatibility': mode}
        response = requests.put(url, json=payload)
        response.raise_for_status()

# Usage
client = SchemaRegistryClient('http://localhost:8081')

# Register schema
schema = {
    "type": "record",
    "name": "User",
    "fields": [
        {"name": "id", "type": "long"},
        {"name": "name", "type": "string"}
    ]
}

result = client.register_schema('users-value', schema)
print(f"Registered schema with ID: {result['id']}")

# Check compatibility
is_compatible = client.check_compatibility('users-value', new_schema)
print(f"Compatible: {is_compatible['is_compatible']}")

Schema ID in Messages

python
# Messages encoded with schema ID prefix
# Format: [magic byte (0)] [4-byte schema ID] [avro data]

import struct

def encode_with_schema_id(schema_id, avro_data):
    """
    Encode message with schema ID prefix.
    
    Wire format:
    - Byte 0: Magic byte (0x00)
    - Bytes 1-4: Schema ID (big-endian int32)
    - Bytes 5+: Avro-encoded data
    """
    magic_byte = b'\x00'
    schema_id_bytes = struct.pack('>I', schema_id)
    
    return magic_byte + schema_id_bytes + avro_data

def decode_with_schema_id(encoded_message):
    """
    Decode message and extract schema ID.
    """
    magic_byte = encoded_message[0]
    schema_id = struct.unpack('>I', encoded_message[1:5])[0]
    avro_data = encoded_message[5:]
    
    return schema_id, avro_data

Schema Registry Metrics

python
# Key metrics to monitor
schema_metrics = {
    # Registration
    'schema-registrations': 'Total schema registrations',
    'schema-registration-rate': 'Registration rate per second',
    
    # Compatibility
    'compatibility-checks': 'Total compatibility checks',
    'compatibility-failures': 'Failed compatibility checks',
    
    # Performance
    'request-latency-avg': 'Average request latency',
    'request-rate': 'Request rate',
    'error-rate': 'Error rate',
    
    # Storage
    'schemas-count': 'Total registered schemas',
    'subjects-count': 'Total subjects'
}

âš ī¸Production Tip

Run Schema Registry in a cluster (3+ nodes) for high availability. It stores schemas in Kafka topic _schemas, so ensure that topic has sufficient replication factor.

Common Schema Evolution Patterns

python
# Pattern 1: Safe field addition
def add_optional_field(schema, field_name, field_type, default_value=None):
    """
    Add an optional field to schema.
    Always backward compatible.
    """
    new_field = {
        'name': field_name,
        'type': ['null', field_type] if default_value is None else field_type,
        'default': default_value
    }
    schema['fields'].append(new_field)
    return schema

# Pattern 2: Field deprecation
def deprecate_field(schema, field_name):
    """
    Mark field as deprecated.
    Field remains in schema for backward compatibility.
    """
    for field in schema['fields']:
        if field['name'] == field_name:
            field['doc'] = f'DEPRECATED: {field.get("doc", "")}'
            break
    return schema

# Pattern 3: Schema branching
def create_schema_branch(base_schema, branch_name):
    """
    Create a branch for experimental schema changes.
    """
    branched = base_schema.copy()
    branched['name'] = f"{base_schema['name']}_{branch_name}"
    return branched

â„šī¸Key Insight

Schema Registry is not just for validation. It enables:

  1. Schema evolution without breaking consumers
  2. Data governance and documentation
  3. Cross-language compatibility (Avro/Protobuf)
  4. Schema versioning and lineage tracking

Operating the registry in production

Three operational settings decide whether the registry helps you or surprises you. Set the compatibility mode per subject before the first producer registers, because tightening it later on a subject that already holds an incompatible version fails outright and leaves you choosing between a fresh subject and a documented exception. Configure clients with a local schema cache of an appropriate size, since a cache miss on every batch turns a lookup into a network round trip and quietly multiplies latency for no benefit. Keep subject naming aligned with topic naming, whether that is the topic name itself, a convention with key and value suffixes, or the record name, because an inconsistent convention lets two services register conflicting contracts for what each believes is the same data.

Monitoring should cover four numbers: registration requests per second, compatibility failures, cache hit ratio, and lookup latency. A rising compatibility failure count is the earliest signal that somebody is about to ship a breaking change, and blocking at registration is far cheaper than debugging a deserialiser error in a consumer three services downstream. Back up the _schemas topic like any other critical data, because it is the registry's entire state, and rehearse restoring the registry from it so a lost deployment never becomes a lost contract history. Finally, treat schemas as reviewable code kept in source control, with the registry agreeing with it rather than being the place where a mistake is first discovered.

Common Mistakes

Leaving the compatibility mode on none and discovering the break in a downstream consumer

Fix: Set BACKWARD or FULL per subject before the first registration so an incompatible version is rejected at the API

Removing or renaming a field in a single deploy

Fix: Deprecate first, wait for at least one full retention window, then remove, using aliases for renames

Calling the registry on every produce to resolve a schema

Fix: Rely on the four-byte schema id in the message and a client-side cache so the registry stays out of the hot path

Key Takeaways

  • Registry state lives in the _schemas topic, and messages carry only a schema id, so lookups are cached rather than per-record
  • Compatibility modes map to which side may deploy first: BACKWARD for new readers, FORWARD for old readers, FULL for both
  • Safe evolution is additive with defaults, deprecate-then-remove, aliases for renames, and promotions along the allowed type ladder
  • Subject-level policy plus compatibility failures as a metric turns schema breaks into blocked registrations instead of production incidents
🔒

Premium Content

Schema Registry: Avro, Protobuf, Compatibility Modes

You've previewed the first section. Unlock this full lesson and 900+ advanced tutorials with a Premium plan.

đŸŽ¯End-to-end Projects
đŸ’ŧInterview Prep
📜Certificates
🤝Community Access

Already a member? Log in

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-17

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Advertisement