The user wants a "schema registry with compat checks: modes, pins, and notifications."
Key Components:
- Schema Registry: A centralized repository to store and retrieve schemas (likely Avro, Protobuf, or JSON Schema).
- Compatibility Checks: The core logic to determine if a new schema is compatible with previous versions.
- Modes: Different compatibility modes (BACKWARD, FORWARD, FULL, NONE).
- Pins: "Pinning" specific versions of a schema to ensure compatibility against a specific stable version, not just the latest.
- Notifications: Alerting when schemas change or compatibility fails.
Tech Stack Selection:
- Language: Python (great for prototyping and widely used in data engineering).
- Storage: In-memory (for a simple demo) or SQLite (for persistence without setup overhead). Let's go with a class-based structure that abstracts storage so it can be swapped, but use a simple dictionary or SQLite for the example. SQLite is better to show "state".
- Schema Type: Avro is the standard for schema registries, but I'll make it generic enough to plug in parsers. I'll stick to a JSON-based structure for simplicity in the demo, or maybe just string comparison if I don't want to import heavy libraries, but that's weak.
- Decision: I will use a "Mock" schema parser to keep the code dependency-free, but design the interfaces so real parsers (like
fastavro) could be plugged in.
- Notifications: A simple Observer pattern or a callback list.
Architecture:
SchemaRegistry class.
CompatibilityChecker class.
SchemaStorage class (interface).
Notifier class (interface).
Detailed Logic:
-
Registration:
- Receive
subject (topic name) and schema (definition).
- Check compatibility against existing versions based on the subject's mode.
- Handle "Pins": If a pin exists, check against the pinned version instead of just the latest.
- If valid, store it, increment ID.
- Trigger notifications.
-
Compatibility Modes:
BACKWARD: New schema can read old data. (Consumer update first).
FORWARD: Old schema can read new data. (Producer update first).
FULL: Both.
NONE: No check.
-
Pins:
- A mechanism to say "Subject A" must be compatible with "Version 3", even if Version 5 is the latest. This is common when you have long-running batch jobs or specific consumers that can't upgrade immediately.
-
Notifications:
- Listeners (webhooks, logs) that get called on specific events (Register, IncompatibleError).
Drafting the Code Structure (Mental or Scratchpad):
class CompatibilityMode(Enum):
BACKWARD = 1
FORWARD = 2
FULL = 3
NONE = 4
class SchemaRegistry:
def __init__(self):
self.store = {} # subject -> [schemas]
self.configs = {} # subject -> {mode, pin}
def register(self, subject, schema):
# 1. Get mode and pin
# 2. Get reference schema (latest or pinned)
# 3. Check compatibility
# 4. Save
# 5. Notify
Refining the "Mock" Compatibility Logic:
Writing a real Avro compatibility checker is complex. I will simulate the logic.
check(old, new, mode):
- If mode is NONE, return True.
- I will implement a simple JSON schema check (e.g., checking field existence) to make it look realistic without needing external libraries.
Implementation Steps:
- Models:
Schema, SubjectConfig, CompatibilityMode.
- Exceptions:
IncompatibleSchemaError.
- Storage:
InMemoryStorage.
- Logic:
SchemaRegistry main class.
- Notifications:
ConsoleNotifier.
- Usage/Demo: Script showing how to register, change mode, pin, and fail compatibility.
Self-Correction/Refinement during thought process:
-
User requirement: "Pins".
-
Implementation: A pin is just a configuration per subject. subject_config = {mode: BACKWARD, pin_version: 5}. When checking compatibility, instead of looking up latest_version, look up pin_version.
-
User requirement: "Notifications".
-
Implementation: A publish method or observers list.
Code Outline:
import json
from enum import Enum
from typing import List, Dict, Callable, Optional
# 1. Definitions
class Mode(Enum): ...
# 2. The Exception
class IncompatibleError(Exception): ...
# 3. The Registry
class SchemaRegistry:
def __init__(self):
self.schemas = {}
self.modes = {}
self.pins = {} # subject -> version_id
self.notifiers = []
def register(self, subject, schema_str):
# Parse schema
# Determine config
# Get reference schema (respecting pins)
# Check compatibility
# Store
# Notify
Let's write the solution in Python, ensuring it's modular and clean. I will use a simplified JSON-based compatibility check to demonstrate the logic without requiring fastavro or confluent-kafka installations, but I will add comments on where to plug those in.
Key Feature: Compatibility Logic (Mock)
To make the demo meaningful, I'll define a simple rule:
- Backward: New schema must contain all keys from the old schema (no deleting required fields).
- Forward: Old schema must contain all keys from the new schema (no adding required fields). Actually, forward usually means adding optional fields or removing fields. Let's stick to standard definitions.
- Backward: Can read old data with new schema. (Add fields with defaults, remove fields).
- Forward: Can read new data with old schema. (Remove fields, add fields with defaults).
To keep the code runnable and understandable, I'll treat schemas as Sets of fields.
- Old: {A, B}
- New: {A, C}
- Backward: New must read Old. Old has B. New doesn't. OK (ignore). New has C (ok if default). Simplification: I'll implement a
MockCompatibilityChecker that just checks if a specific field was removed to trigger a failure, or similar.
Plan:
- Enums & Config: Define
CompatibilityMode.
- Schema Entity: Helper to parse JSON strings.
- Registry Class:
update_config(subject, mode, pin)
register(subject, schema)
check_compatibility(subject, schema)
- Notifications: Simple print callback.
- Main execution: Demonstrate the flow.
Let's refine the "Pin" logic.
Standard registry checks against the latest version.
With Pin:
get_reference_schema(subject):
if pin exists -> return schema at pin_version
else -> return latest schema
Let's go.
This solution implements a Schema Registry in Python. It is designed to be storage-agnostic (uses in-memory dictionaries for simplicity) but demonstrates the critical logic required for enterprise data governance:
- Compatibility Modes:
BACKWARD, FORWARD, FULL, and NONE.
- Schema Pinning: Ensuring compatibility is checked against a specific "Golden" version, not just the latest one.
- Notifications: An observer pattern to alert external systems (e.g., Slack, Email) on success or failure.
Implementation
import json
from enum import Enum
from typing import Dict, List, Optional, Callable, Any, Set
# ==========================================
# 1. Definitions & Enums
# ==========================================
class CompatibilityMode(Enum):
"""
BACKWARD: (Default) New schema can read old data (e.g., adding optional fields).
FORWARD: Old schema can read new data (e.g., deleting fields).
FULL: Both backward and forward compatible.
NONE: No checks performed.
"""
BACKWARD = "BACKWARD"
FORWARD = "FORWARD"
FULL = "FULL"
NONE = "NONE"
class CompatibilityError(Exception):
"""Custom exception for compatibility violations."""
def __init__(self, subject: str, mode: CompatibilityMode, details: str):
self.subject = subject
self.mode = mode
self.details = details
super().__init__(f"Schema incompatible for '{subject}' [{mode.value}]: {details}")
# ==========================================
# 2. The Schema Registry Core
# ==========================================
class SchemaRegistry:
def __init__(self):
# subject -> list of schema versions
self._store: Dict[str, List[dict]] = {}
# subject -> global configuration
self._configs: Dict[str, Dict[str, Any]] = {}
# subject -> pinned_version (if any)
self._pins: Dict[str, int] = {}
# List of callback functions for notifications
self._listeners: List[Callable[[str, str, bool, Optional[str]], None]] = []
# --- Configuration & Pins ---
def set_compatibility(self, subject: str, mode: CompatibilityMode):
"""Set the compatibility mode for a specific subject."""
if subject not in self._configs:
self._configs[subject] = {}
self._configs[subject]['mode'] = mode
print(f"[CONFIG] Set {subject} compatibility to {mode.value}")
def pin_version(self, subject: str, version: int):
"""
Pin compatibility checks to a specific version.
Useful for maintaining strict contracts with specific downstream consumers.
"""
if subject not in self._store or version > len(self._store[subject]):
raise ValueError(f"Cannot pin non-existent version {version} for {subject}")
self._pins[subject] = version
print(f"[PIN] Pinned {subject} to version {version}")
def unpin(self, subject: str):
self._pins.pop(subject, None)
print(f"[PIN] Unpinned {subject}")
# --- Notification System ---
def add_listener(self, callback: Callable[[str, str, bool, Optional[str]], None]):
"""Register a callback(subject, event_type, success, message)"""
self._listeners.append(callback)
def _notify(self, subject: str, event_type: str, success: bool, message: Optional[str] = None):
for listener in self._listeners:
try:
listener(subject, event_type, success, message)
except Exception as e:
print(f"Notification Error: {e}")
# --- Core Logic ---
def register(self, subject: str, schema: dict) -> int:
"""
Attempts to register a new schema.
Returns version ID if successful.
Raises CompatibilityError if checks fail.
"""
mode = self._configs.get(subject, {}).get('mode', CompatibilityMode.BACKWARD)
# 1. Determine Reference Schema
reference_schema = None
reference_version = None
if subject in self._pins:
# Case: Pinned. Check against the pinned "Golden" copy.
pinned_v = self._pins[subject]
reference_schema = self._store[subject][pinned_v - 1]
reference_version = pinned_v
elif subject in self._store and self._store[subject]:
# Case: Unpinned. Check against the latest.
reference_schema = self._store[subject][-1]
reference_version = len(self._store[subject])
# 2. Run Compatibility Check
if reference_schema and mode != CompatibilityMode.NONE:
is_valid, reason = self._check_logic(schema, reference_schema, mode)
if not is_valid:
self._notify(subject, "REGISTRATION", False, reason)
raise CompatibilityError(subject, mode, reason)
# 3. Store and Notify
if subject not in self._store:
self._store[subject] = []
self._store[subject].append(schema)
new_version = len(self._store[subject])
self._notify(subject, "REGISTRATION", True, f"Schema registered as version {new_version}")
return new_version
def _check_logic(self, new_schema: dict, old_schema: dict, mode: CompatibilityMode) -> tuple[bool, str]:
"""
Mock implementation of schema compatibility logic.
In a real app (like Confluent SR), this would use Avro/Protobuf specific parsers.
Here we use simple JSON dictionary set logic for demonstration.
"""
new_fields = set(new_schema.get('fields', {}).keys())
old_fields = set(old_schema.get('fields', {}).keys())
# BACKWARD: New schema must be able to read old data.
# Constraint: Cannot remove fields that exist in old data (unless default exists).
# Logic: New fields must have defaults. Old fields must exist in new schema.
if mode in [CompatibilityMode.BACKWARD, CompatibilityMode.FULL]:
# Simple check: New schema cannot DELETE fields from old schema
removed = old_fields - new_fields
if removed:
return False, f"Backward incompatible: Fields {removed} were removed."
# FORWARD: Old schema must be able to read new data.
# Constraint: Cannot add fields without defaults (old code won't understand them).
# Logic: New schema cannot ADD fields without defaults.
if mode in [CompatibilityMode.FORWARD, CompatibilityMode.FULL]:
# Simple check: New schema cannot ADD fields that didn't exist
added = new_fields - old_fields
if added:
# In a real check, we would check if these new fields have default values.
# For this mock, we assume adding fields breaks forward compatibility
# unless explicitly marked safe (which we skip for brevity).
return False, f"Forward incompatible: Fields {added} were added."
return True, "Compatible"
def get_schema(self, subject: str, version: int = None) -> dict:
if subject not in self._store: return None
if version: return self._store[subject][version - 1]
return self._store[subject][-1]
# ==========================================
# 3. Usage Example
# ==========================================
def slack_notifier(subject: str, event: str, success: bool, msg: str):
status = "✅ SUCCESS" if success else "❌ FAILED"
print(f"\n[SLACK BOT] -> Alert! {status} on '{subject}': {msg}\n")
if __name__ == "__main__":
registry = SchemaRegistry()
# 1. Setup Notifications
registry.add_listener(slack_notifier)
# 2. Define Schemas
schema_v1 = {
"type": "record",
"name": "User",
"fields": {
"id": "int",
"name": "string"
}
}
# SCENARIO A: Valid Backward Evolution (Adding a field with default logic - mocked)
schema_v2 = {
"type": "record",
"name": "User",
"fields": {
"id": "int",
"name": "string",
"email": "string" # In a real check, we'd check metadata for defaults
}
}
# SCENARIO B: Breaking Change (Removing a field)
schema_v_break = {
"type": "record",
"name": "User",
"fields": {
"id": "int"
}
}
print("--- STEP 1: Register V1 ---")
registry.set_compatibility("users-topic", CompatibilityMode.BACKWARD)
v1_id = registry.register("users-topic", schema_v1)
print("\n--- STEP 2: Register V2 (Evolution) ---")
try:
# This will fail our MOCK logic because we check BACKWARD (no deletes)
# and our mock logic is very strict regarding field additions for simplicity.
# To pass in this demo, we change mode to NONE or adjust logic.
# Let's change mode to NONE to force registration
registry.set_compatibility("users-topic", CompatibilityMode.NONE)
v2_id = registry.register("users-topic", schema_v2)
except CompatibilityError as e:
print(f"Caught error: {e}")
print("\n--- STEP 3: Test Pinning ---")
# Let's say V2 is the stable production version. We pin it.
registry.set_compatibility("users-topic", CompatibilityMode.BACKWARD)
registry.pin_version("users-topic", v2_id)
# Now we try to register a breaking change.
# Even if V3 is valid against V1 (maybe), it must be valid against V2 (Pinned).
try:
print("Attempting to register breaking schema against PINNED version...")
registry.register("users-topic", schema_v_break)
except CompatibilityError as e:
print(f"Caught expected violation: {e}")
Key Concepts Explained
1. Modes (_check_logic)
The logic separates the types of checks:
- BACKWARD: Ensures new code (using new schema) can read old data. This allows upgrading consumers before producers. The most common default (used by Kafka).
- FORWARD: Ensures old code (using old schema) can read new data. Allows upgrading producers before consumers.
- FULL: Restrictive. Requires both.
2. Pins (pin_version)
In streaming architectures, you might have a "Critical Consumer" that relies strictly on Version 2.
- Without pinning, if you register V3, V4, and V5, the registry usually checks V5 against V4.
- With pinning, the registry forces V5 to be compatible with V2. If V5 breaks the contract V2 established, the registration is blocked, regardless of intermediate versions.
3. Notifications (_notify)
The registry acts as a gatekeeper. It publishes events to listeners. In the example, a simple print function acts as a Slack bot.
- Success: Triggers CI/CD pipelines to update documentation.
- Failure: Triggers alerts to the engineering team that a breaking change was attempted.