Here is the failure that a schema registry exists to prevent. A producer team ships a new version of the OrderPlaced event. They rename a field, or change amount from a string to a long, or drop a column that three downstream services still read. The event lands on the topic. Hours later - sometimes weeks later, when a consumer finally catches up on a backlog - a deserializer in the fraud service throws, the analytics pipeline silently writes nulls, and the warehouse service crashes in a loop it cannot recover from because every poll returns the same poisoned message. Nobody who shipped the change is on call. The producer and the consumer never talked. They were decoupled by the message bus - that was the whole point - and that same decoupling is exactly why nobody caught the break.

A schema registry is the thing that makes “producers and consumers are decoupled” survive contact with reality. It is a centralized service that every producer must clear a schema through before it can publish, and that every consumer fetches schemas from to deserialize. Its job is not to store schemas - a key-value store does that. Its job is to refuse the schema changes that would break a reader, at registration time, before a single bad message is ever written. And then, because messages live for years in a durable log, to guarantee that a consumer reading a message written in 2023 can always fetch the exact schema that message was encoded with, even after the schema has evolved fifteen times since. That second guarantee is why every message carries a tiny schema ID in its envelope and why the registry is, functionally, immutable append-only storage with a compatibility gate bolted to the front.

Let me do it properly.

Functional Requirements (FR)

In scope:

  • Register a schema under a subject. A producer submits an Avro or Protobuf schema for a logical stream (a “subject”, usually one per topic). The registry validates it, checks it against the subject’s history, and either assigns it a globally unique schema ID and version number or rejects it. This is the write/control path and the heart of the system.
  • Enforce compatibility at registration time. Before a new schema version is accepted, the registry checks it against the configured compatibility rule (backward, forward, full, or transitive variants) for that subject. An incompatible schema is rejected with a specific reason - which field, which rule. This is the hard part: the gate that stops a break before it happens, not after.
  • Serve a schema by ID. A consumer that reads a message extracts its embedded schema ID and asks the registry “give me the exact schema for ID 4471.” The registry returns it. This must work for any ID ever issued, forever - the message outlives the producer’s current schema.
  • Version and list schema history. Each subject has an ordered list of versions. Clients can fetch the latest, a specific version, or the whole history. Versions are immutable once assigned.
  • Multi-format support (Avro and Protobuf). Both formats are first-class. Each has its own canonical form, its own compatibility semantics, and its own wire-serialization, but they share the registration/versioning/serving machinery. (JSON Schema is the common third; we design so it slots in.)
  • Compatibility configuration per subject. The compatibility level is configurable per subject (and a global default), because different streams have different evolution needs - an append-only event may only ever need backward compatibility, a request/response pair may need full.
  • Schema references. A schema can reference another (a shared Address type used by five event schemas). The registry resolves and version-pins references so a composite schema is reproducible.

Explicitly out of scope (name it so you own the scope):

  • The message bus itself. We do not design Kafka/Pulsar/Kinesis. The registry is an adjacent service; messages flow through the broker, and only a schema ID rides in the envelope. We define the envelope and the client-side serializer/deserializer hook, nothing more about the broker.
  • Runtime payload validation on the broker. The broker does not parse payloads against schemas on every message - that would put a CPU-heavy validation in the hottest path in the system. Validation happens at registration (once per schema) and deserialization is a client concern. We will justify this split hard; it is the central performance decision.
  • Data/content validation. The registry checks structural compatibility (does the shape evolve safely), not semantic validation (is amount positive, is this a valid email). Business rules are the application’s job.
  • Schema authoring / IDL tooling / codegen. Generating Java classes from Avro, protoc plugins, the developer’s build - adjacent tooling. We serve schemas; what you compile them into is yours.
  • Encryption, field-level masking, PII governance. Real and often co-located with a registry, but a separate concern. We note where tags/metadata hook in.

The one decision that drives everything: the registry is a compatibility gate in front of immutable, versioned schema storage, and the contract is enforced at write time, not read time. A producer that passes the gate is promised that every consumer bound by the subject’s rule can still read what it writes; a consumer is promised it can always fetch the exact schema any message was encoded with. Everything below is a consequence of those two promises.

Non-Functional Requirements (NFR)

  • Scale: this is a metadata service, not a data-plane service - and that reframe is the whole sizing story. Even a massive event platform has only thousands to low tens of thousands of subjects and maybe hundreds of thousands of total schema versions accumulated over years. The data is small. But the read traffic is large and concentrated: every producer and consumer client resolves schema IDs constantly, so reads can be hundreds of thousands per second cluster-wide even though they hit a tiny set of hot IDs. Writes (registrations) are rare - tens to hundreds per day, driven by human deploys.
  • Latency: schema lookup by ID must be fast and effectively free, because it sits in the serialization path of every message: p99 in the low single-digit milliseconds, and in practice served from a client-side cache in microseconds after the first fetch. Registration can be slow (tens of ms to a second) - it is rare and human-paced, and correctness matters far more than speed there.
  • Availability: extremely high for reads (99.99%+). If the registry is unreachable and a consumer cannot fetch a schema it does not have cached, it cannot deserialize - the data pipeline stalls. Reads must survive the loss of nodes and even partial outages (served from caches and read replicas). Writes can tolerate lower availability - if registration is briefly down, deploys wait; nothing in production breaks.
  • Consistency: strong and linearizable on the write path. Compatibility checking is a read-modify-write against the subject’s version history; two concurrent registrations of conflicting schemas must be serialized, or you could admit two versions that are each compatible with the old latest but mutually incompatible, corrupting the history. There must be a single writer / single source of truth per subject. Reads can be eventually consistent (a newly registered schema propagating to a replica a few ms late is fine) except the serving-by-ID path, which must never return a wrong or stale-missing schema for an ID that was issued.
  • Durability: absolute, and permanent. A schema ID, once issued and embedded in even one message, can never be deleted or reused, because that message may be read years later. Schema storage is effectively write-once, retain-forever. Losing a schema means a swath of historical messages become permanently undeserializable.
  • Immutability: a (subject, version) and a schema ID are immutable once assigned. You never edit a schema in place; you register a new version. This is non-negotiable and shapes the storage model.

Back-of-the-Envelope Estimation (BoE)

Let me ground the design in numbers - and the headline is that the dataset is tiny and the read rate is huge, which is an unusual and important shape.

Schema corpus (the data at rest):

Subjects:                 ~10,000 (roughly one per topic on a big platform)
Versions per subject:     ~20 on average over years of evolution
Total schema versions:    10,000 * 20 = ~200,000 schemas
Average schema size:      ~4 KB (a rich Avro/Protobuf record, pretty-printed)
Total raw schema storage: 200,000 * 4 KB = ~800 MB

With references, metadata, indexes, history: call it a few GB, once.

A few gigabytes. The entire corpus of every schema version ever registered fits in RAM on a single node with room to spare. This is the first and most important number: the data is small enough to fully cache everywhere. That single fact drives the whole architecture - this is not a sharding-and-partitioning problem, it is a replicate-everywhere-and-cache-aggressively problem.

Write traffic (registrations):

New schema versions:  driven by deploys - tens to low hundreds per day.
Peak:                 maybe a handful per minute during a big coordinated rollout.
Write QPS:            effectively ~0 on average; single-digit at peak.

Writes are so rare that a single writer serializing all registrations is not a bottleneck - it is a feature, because it gives us the linearizable compatibility check for free.

Read traffic (lookups by ID and by subject):

Every producer serializing a message needs the schema ID for its schema.
Every consumer deserializing a message needs the schema for an embedded ID.

Platform message rate:   say 2,000,000 messages/sec across all topics.
Naive: 2M schema lookups/sec on produce + 2M on consume = 4M/sec. Catastrophic.

Reality with client caching:
  A producer uses the SAME schema for millions of messages -> caches the ID.
  A consumer sees a SMALL set of IDs (the few versions live on its topics)
     -> caches schema-by-ID after first fetch.
  Cache hit rate in steady state: >99.99%.

Registry-facing read QPS (cache MISSES only):
  cold starts, new deploys, newly-seen IDs, cache evictions
  -> realistically HUNDREDS to low THOUSANDS/sec cluster-wide, not millions.

The arithmetic that matters: the demand is millions of lookups per second, but client-side caching collapses it to a trickle of cache misses, because schema IDs are extraordinarily cache-friendly - a client touches only a handful of IDs and reuses each for the lifetime of the schema. The registry is protected by the clients’ caches; it is not and must not be in the per-message hot path.

Bandwidth:

Serving a cache miss returns ~4 KB of schema.
At even 2,000 misses/sec: 2,000 * 4 KB = ~8 MB/sec. Trivial.
Registration uploads ~4 KB a few times a day. Rounding error.

Envelope overhead (the per-message cost we DO pay everywhere):

Every message carries a schema ID in its envelope.
ID size: 4-byte integer (+ a 1-byte magic marker) = 5 bytes per message.
At 2M messages/sec: 10 MB/sec of ID bytes across the platform.
Per message of ~1 KB: 5 bytes = 0.5% overhead. Negligible, and non-negotiable.

The headline shape: a few GB of write-once data, near-zero write rate, a read demand of millions/sec that client caches collapse to a few thousand misses/sec, and a fixed 5-byte tax on every message for the embedded ID. This is a small, strongly-consistent, cache-everywhere metadata service with a tiny permanent footprint - size it for availability and correctness, not throughput.

High-Level Design (HLD)

The system is a small, strongly-consistent metadata service fronting durable schema storage, with the real work pushed to client-side serializers and deserializers that cache aggressively. The registry has a single-writer leader that serializes registrations (so the compatibility check is linearizable) and read replicas that serve lookups. Schemas live in a durable, immutable store. Crucially, the registry is not on the per-message path: clients embed a schema ID in each message and resolve IDs through local caches, hitting the registry only on a cache miss.

   PRODUCER APP                                              CONSUMER APP
  ┌───────────────────────────┐                            ┌───────────────────────────┐
  │ app obj ─► SERIALIZER      │                            │ DESERIALIZER ─► app obj    │
  │   1. schema known?         │                            │  5. read 5-byte envelope   │
  │   2. look up / register    │                            │     -> schema ID = 4471    │
  │      -> get schema ID      │                            │  6. ID in local cache?     │
  │   3. encode payload (Avro/ │                            │     yes -> decode (µs)      │
  │      Proto) + prepend ID   │                            │     no  -> fetch by ID ─┐   │
  │   [ local schema CACHE ]   │                            │   [ local schema CACHE ]│   │
  └──────────┬────────────────┘                            └─────────────────────┬───┘   │
             │ 4. publish                                        read message     │       │
             ▼          ┌──────────────── MESSAGE BUS (Kafka/Pulsar) ─────────────┘       │
        ┌────────────── topic "orders": [ [ID 4471|avro bytes] [ID 4471|...] [ID 4472|..] ]
        │                    (schema ID travels WITH every message, forever)              │
        │                                                                                 │
        │ register (miss, rare)                              fetch by ID (miss, rare) ◄────┘
        ▼                                                              │
 ┌──────────────────────────── SCHEMA REGISTRY ─────────────────────────────────────────┐
 │                                                                                        │
 │   ┌── WRITE PATH (single leader) ──────────┐    ┌── READ PATH (replicas) ───────────┐ │
 │   │  POST /subjects/{s}/versions           │    │  GET /schemas/ids/{id}            │ │
 │   │   1. canonicalize + parse (valid?)     │    │   -> served from in-memory map    │ │
 │   │   2. dedup: seen this exact schema?    │    │      (whole corpus fits in RAM)   │ │
 │   │   3. COMPATIBILITY CHECK vs history     │    │  GET /subjects/{s}/versions/{v}   │ │
 │   │   4. assign version + global schema ID │    │  GET /subjects/{s}/versions/latest│ │
 │   │   5. durably append, replicate         │    └──────────────┬────────────────────┘ │
 │   └───────────────┬────────────────────────┘                   │                       │
 │                   │ leader election via consensus (Raft)       │ replicate (async)     │
 │   ┌───────────────▼───────────── DURABLE STORE (immutable, append-only) ─────────────┐ │
 │   │  schema_by_id: id -> { format, canonical_schema, hash }      (write-once)         │ │
 │   │  subject_versions: (subject, version) -> schema_id           (immutable)          │ │
 │   │  subject_config: subject -> compatibility_level                                   │ │
 │   │  schema_hash_index: sha256(canonical) -> id   (dedup + "already registered?")     │ │
 │   └──────────────────────────────────────────────────────────────────────────────────┘ │
 └────────────────────────────────────────────────────────────────────────────────────────┘

Request flow - registering a schema (the write path, rare but critical):

  1. A producer (usually at deploy/startup, or a CI check) submits its schema for subject orders-value: POST /subjects/orders-value/versions with the Avro/Protobuf schema text.
  2. The request goes to the single leader. The leader canonicalizes the schema (strips whitespace, normalizes field ordering and defaults into a format-specific canonical form) and parses it - a malformed schema is rejected immediately.
  3. Dedup check: hash the canonical form and look it up. If this exact schema is already registered under this subject, return the existing ID and version - registration is idempotent, and re-deploying the same code must not create a new version.
  4. Compatibility check (the gate): load the subject’s existing version(s) and run the configured compatibility rule (backward/forward/full, transitive or not). If the new schema would break a reader under that rule, reject with a precise reason. This is the entire point of the service. Nothing gets past here that violates the contract.
  5. If it passes: assign the next version number for the subject and a globally unique schema ID, durably append the schema to the store, replicate to followers, and return { id, version }. The ID is now permanent and will outlive this producer.

Request flow - producing a message (client-side, per message, registry usually untouched):

  1. The serializer has the schema for the object it is encoding. On first use it resolves the schema to its ID (register-or-lookup), then caches that ID keyed by the schema. Every subsequent message reuses the cached ID with no registry call.
  2. It encodes the payload with Avro/Protobuf and prepends the envelope: a 1-byte magic marker plus the 4-byte schema ID. The message on the wire is [magic][schema_id][serialized payload].
  3. It publishes to the broker. The broker stores opaque bytes; it neither knows nor cares about the schema. The ID rides along permanently.

Request flow - consuming a message (client-side, per message):

  1. The deserializer reads the message’s first 5 bytes: magic marker + schema ID (say 4471). This tells it exactly which schema version the message was written with.
  2. It checks its local cache for schema 4471. In steady state this hits essentially always (a consumer sees only the handful of IDs live on its topics), and it decodes in microseconds with zero network calls.
  3. On a cache miss (cold start, a newly-seen ID, an eviction) it calls GET /schemas/ids/4471, which a read replica serves from its in-memory map of the whole corpus. The deserializer caches it and decodes. For Avro it uses the writer’s schema (ID 4471, exactly what the producer used) together with its own reader’s schema to resolve the data - which is how Avro reads old data with new code. For Protobuf the tag numbers in the bytes map to fields directly.

The key architectural insight: the registry’s two promises - “nothing that breaks a reader gets written” and “the exact writer schema is always fetchable by ID” - are enforced at completely different times. The first is a one-time check at registration, paid rarely. The second is a tiny ID embedded once at produce time and a cached lookup at consume time, paid per message but collapsed to near-zero by caching. The registry is never in the hot path; it is a gate at the front and a lookup table on the side.

Component Deep Dive

Three hard parts: (1) the compatibility gate - how you decide, at registration time, whether a schema change is safe, and what “safe” even means; (2) the envelope and ID resolution - how a message carries its schema identity for years and how clients resolve it without hammering the registry; and (3) the storage and consistency model - immutable, write-once, linearizable registration. I will walk each from naive to correct.

1. The Compatibility Gate: Deciding What Breaks a Reader

This is the reason the service exists. We must decide, when a new schema version is submitted, whether accepting it could make any reader fail. Get this wrong and the registry is theater.

Approach A: Store schemas, check nothing (the naive registry)

Treat the registry as a versioned key-value store. A producer POSTs a schema, you assign it the next version, you store it, done. Consumers fetch whatever they ask for.

register(subject, schema) -> version = last + 1; store; return version

Where it breaks: immediately and exactly where it matters. This registry documents schemas; it does not protect anyone. A producer renames amount to total, registers version 5, starts producing. Every consumer compiled against version 4 that reads amount by name gets a null or an error. The registry happily recorded the break. All you have built is a schema museum. The entire value of a registry is in the check this approach skips - without it, you have paid for a service that gives false confidence, which is worse than nothing.

Approach B: Compatibility rules enforced against version history

Before accepting a new schema, check it against the subject’s existing schema(s) under a declared compatibility rule. The rules are defined by who must be able to read what:

Terminology:
  "reader" schema = the schema the consuming code was built with
  "writer" schema = the schema a message was actually encoded with

BACKWARD  : new schema can read data written with the OLD schema.
            -> upgrade CONSUMERS first. The classic default for event streams:
               deploy new consumers, then new producers.
FORWARD   : OLD schema can read data written with the NEW schema.
            -> upgrade PRODUCERS first; old consumers keep working on new data.
FULL      : both backward AND forward. Safe to upgrade either side first.
*_TRANSITIVE : the check runs against ALL prior versions, not just the latest.

The check reduces to a structural diff of the two schemas against a set of rules about what each format permits. The rules are not arbitrary - they fall directly out of how each format resolves data:

Backward compatibility (new reader reads old data) permits:

ChangeBackward-safe?Why
Add a field with a defaultYesOld data lacks it; reader fills the default.
Add a field without a defaultNoOld data lacks it; reader has no value to use.
Remove a fieldYesOld data has it; reader ignores the extra.
Rename a fieldNo (Avro)Reader looks up by name, finds nothing. (Use aliases.)
Widen a type (int -> long)SometimesAllowed where the format defines a promotion.
Change a type incompatiblyNoReader cannot interpret the bytes.

Forward compatibility flips the “add/remove with default” rules: adding a field is forward-safe (old reader ignores it), removing a field without a default is not (old reader expected it). Full compatibility is the intersection: you may only add or remove fields that have defaults. This table is the compatibility engine in miniature, and knowing why each row is what it is - trace it back to “what does the reader do when the field is present/absent” - is the depth an interview is probing for.

Avro vs Protobuf - same idea, different mechanics:

AVRO: data is written WITHOUT field tags; decoding REQUIRES the writer's schema
      to even parse the bytes, then resolves against the reader's schema by
      field NAME + default. This is WHY the registry must serve the exact writer
      schema by ID - you literally cannot decode Avro without it. Compatibility
      is checked field-by-field with Avro's schema-resolution rules (defaults,
      aliases, type promotion, union handling).

PROTOBUF: every field has a numeric TAG in the bytes. Unknown tags are skipped,
      missing fields take type defaults. Rules are tag-based: NEVER reuse or
      change a field's tag number or type; adding a new tag is safe; removing a
      field is safe if you RESERVE its tag so it is never reused. Compatibility
      checking walks the message/enum tree comparing tags, types, labels.

The compatibility check for each format is a tree walk comparing the candidate schema to the prior one(s), accumulating violations, each with a human-readable reason (“field region added without a default, breaks BACKWARD”). On any violation under the subject’s rule, reject. Transitive vs non-transitive is the subtle, must-mention choice: non-transitive checks only against the latest version, which is cheaper but can let you drift into breaking an older message still sitting in the retention window; transitive checks against every prior version, which is the correct choice when your retention is long and old messages are still being read - exactly the “read a 2023 message in 2026” scenario. For a durable event log, lean transitive.

The compatibility gate turns the registry from a passive store into an active contract-enforcer: a schema that passes is proven readable by everyone the rule protects, and the proof is a mechanical structural check run once, at registration, with a precise rejection reason when it fails.

2. The Envelope and ID Resolution: Carrying Schema Identity for Years

A message written today may be read in 2029, after its schema has evolved a dozen times. The reader must fetch the exact schema the message was written with. How does a message know which schema it used, and how do clients resolve that without calling the registry per message?

Approach A: Put the schema (or a version number) in the message

Option one: embed the full schema text in every message. Option two: embed a (subject, version) pair.

Where it breaks:

  • Full schema in every message is absurd at scale: a 4 KB schema prepended to a 1 KB payload is 400% overhead, multiplied by millions of messages per second and petabytes of retained log. You would store the same schema billions of times. Dead on arrival.
  • (subject, version) pair is small but ambiguous and fragile. Version numbers are per subject, so the same version number means different schemas in different subjects - you must carry the subject string too, bloating the envelope. Worse, it couples the message to a subject’s mutable naming; if a schema is shared across subjects or a subject is renamed, resolution breaks. And a version is a weaker identity than you want - you want to point at an immutable, global thing, not a per-subject counter.

Approach B: A globally unique schema ID in a fixed-size envelope

Every registered schema gets a globally unique, immutable integer ID (not per-subject - global). Every message carries a tiny fixed envelope:

Wire format (Confluent-style):
  byte 0        : magic byte (0x00) - format/version marker for the envelope itself
  bytes 1-4     : schema ID, 4-byte big-endian int  (the GLOBAL id)
  bytes 5..     : the Avro/Protobuf-serialized payload

Total envelope overhead: 5 bytes. Fixed. Payload-size-independent.

Why a global ID is the right identity:

  • Tiny and fixed. 5 bytes regardless of schema size - the 0.5% tax from the BoE, paid once per message and never renegotiated.
  • Immutable and unambiguous. An ID points at one exact schema, forever. No subject string needed in the envelope; the ID alone fully determines the bytes’ meaning. A 2023 message with ID 4471 resolves to schema 4471 in 2029 identically, no matter how many versions came after.
  • Decouples identity from naming. Subjects can be renamed, schemas shared across subjects, versions re-numbered in tooling - none of it touches the ID baked into old messages. Identity is the ID; subject/version are just a human-facing index on top.

Client-side ID resolution - the caching that keeps the registry out of the hot path:

PRODUCER (serializer) cache:   schema object  ->  schema ID
   first message of a schema: register-or-lookup -> get ID -> CACHE
   every later message:       cache hit -> prepend ID, no registry call
   (a producer uses one schema for millions of messages; ~1 miss ever)

CONSUMER (deserializer) cache: schema ID  ->  parsed writer schema
   read envelope -> ID -> cache hit -> decode in microseconds
   miss (cold start / new ID / eviction): GET /schemas/ids/{id} once -> CACHE
   (a consumer sees a handful of IDs; near-100% hit rate in steady state)

Both caches are correct to hold forever because the mapping is immutable - a schema ID never changes meaning, so a cached entry is never stale. This is the property that makes the aggressive caching safe: you can cache an immutable fact indefinitely with no invalidation logic. That is why the BoE’s millions-per-second demand collapses to a few misses per second. The registry is sized for cache misses, and cache misses are rare precisely because IDs are immutable and few-per-client.

Resolution at decode time, by format:

  • Avro: the deserializer fetches the writer’s schema (the exact ID in the envelope) - mandatory, because Avro bytes are untagged and un-decodable without the writer schema - and resolves the data against the consumer’s own reader’s schema using Avro’s resolution rules (by name, applying defaults for fields the reader added, ignoring fields the reader dropped). This reader/writer split is the mechanism by which old data flows into new code, and it is only possible because the registry can always hand back the exact writer schema by ID.
  • Protobuf: the envelope ID identifies the message type; the tagged bytes decode against the reader’s generated type directly (unknown tags skipped, missing fields defaulted). The writer schema fetch is used for validation/tooling rather than being strictly required to parse, because tags are self-describing - a real format difference worth naming.

The envelope-plus-global-ID design is what makes “decoupled producers and consumers, messages that live for years” actually work: a 5-byte immutable pointer travels with every message, resolves through forever-cacheable client maps, and lets any reader reconstruct the exact schema any writer used, across any amount of subsequent evolution.

3. Storage and Consistency: Immutable, Write-Once, Linearizable

Registration is a read-modify-write (read history, check compatibility, append) that must be serialized, and the stored schemas must be durable and immutable forever. How do we store this and guarantee two concurrent registrations cannot corrupt a subject’s history?

Approach A: A plain database, concurrent writers, last-write-wins (naive)

Put schemas in a SQL table. Any registry node handles any registration: read the subject’s latest, check compatibility in app code, insert the new version.

nodeA: read latest(orders) = v4; check candidate X vs v4 -> ok; insert v5 = X
nodeB: read latest(orders) = v4; check candidate Y vs v4 -> ok; insert v6 = Y

Where it breaks: a race that corrupts the compatibility invariant. Node A and node B both read latest = v4 concurrently. X is compatible with v4; Y is compatible with v4; both pass their checks and both insert. But X and Y may be mutually incompatible - and now the subject’s history contains two sibling versions that each looked fine against v4 but violate the rule against each other. If the rule is transitive, the history is now internally inconsistent; a later version checked against “all prior” sees a contradiction, and worse, you may have already told two producers their schema is safe when together they are not. The compatibility check is a read-modify-write that must be atomic across the whole subject, and concurrent writers with per-node checks cannot provide that. Last-write-wins on inserts does not help - the damage is admitting both.

Approach B: Single-writer leader, immutable append-only store, strong consistency

Serialize all registrations through a single leader elected by consensus (Raft), and store schemas in an immutable, append-only structure.

The single writer (correctness, and it is cheap):

  • All register requests route to the current leader. The leader does the whole read-modify-write - load history, check compatibility, assign version + global ID, append - with no other registration interleaving. This makes the compatibility check linearizable: every registration is checked against a consistent, fully-committed history, so the mutual-incompatibility race is impossible by construction.
  • This is affordable only because writes are rare (BoE: tens to hundreds per day). A single writer would be a disaster for a data-plane service; for a metadata service with near-zero write rate it is the ideal - you buy perfect consistency for a throughput price you will never notice.
  • The leader is elected via Raft/consensus over a small cluster (3 or 5 nodes). If the leader dies, a follower is elected in seconds; registrations (rare) briefly pause; reads (served from replicas/caches) never stop. A clean, well-worn pattern: single logical writer, HA via consensus failover.

The store (immutability and durability):

schema_by_id        : id        -> { format, canonical_text, sha256 }   WRITE-ONCE
subject_versions    : (subject, version) -> id                          IMMUTABLE
subject_config      : subject   -> compatibility_level                  mutable (rare)
schema_hash_index   : sha256(canonical) -> id        (dedup / idempotent register)
id_sequence         : monotonic global counter       (leader-assigned)
  • Write-once, retain-forever. A row in schema_by_id is never updated or deleted - an ID issued once is served identically forever, because messages carrying it are immortal. There is no “delete a schema” operation in the normal API; even “soft delete” only hides a subject version from listings and never frees the ID or its bytes. This is the durability NFR made concrete: the store is an immutable ledger.
  • Dedup via content hash. schema_hash_index makes registration idempotent - the same canonical schema submitted twice to a subject returns the existing ID/version, so redeploying unchanged code never bloats history. Canonicalization before hashing is what makes “semantically identical but differently formatted” schemas dedup correctly.
  • The storage engine is deliberately boring. A few GB of immutable, mostly-read data. You can back this with a replicated SQL database, or - the common real pattern - with a compacted log topic on the message bus itself (the registry stores its own state as events in a dedicated topic, and every node materializes the full corpus into an in-memory map by replaying it). The log-as-store approach is elegant here: it gives you durability, ordering (hence the single writer via “only the leader appends”), and trivial full-replication to every node, and the in-memory materialization is why reads are a map lookup served in microseconds.

Read serving (availability and speed):

  • Because the whole corpus is a few GB, every node holds the entire dataset in memory. A GET /schemas/ids/{id} is a hash-map lookup, not a database query. Read replicas can be scaled out horizontally and placed close to clients; they serve lookups even if the leader is down (immutable data cannot go stale), which is how reads hit 99.99%+ while writes tolerate the leader being briefly unavailable.
  • Reads are allowed to be eventually consistent for newly registered schemas (a replica may lag the leader by milliseconds) - harmless, because a consumer only asks for an ID after it has seen a message carrying it, and that message could only exist if registration already committed. The causal ordering (register -> produce -> the ID appears in a message -> consume -> fetch by ID) guarantees the ID is committed before anyone asks for it, so read-your-writes is satisfied by the message flow itself without needing linearizable reads.

Single-writer registration gives linearizable compatibility checks without locks sprawling across the system; an immutable, fully-replicated, in-memory-materialized store gives permanent durability and microsecond reads; and the rarity of writes is what makes this otherwise-expensive strong-consistency posture essentially free.

API Design & Data Schema

Registration and configuration API (the write/control plane)

POST /subjects/{subject}/versions          # register a schema (idempotent by content)
  { "schemaType": "AVRO",                   # AVRO | PROTOBUF | JSON
    "schema": "{...avro json or proto text...}",
    "references": [ { "name": "Address",
                      "subject": "address-value", "version": 3 } ] }
  -> 200 { "id": 4471 }                      # existing ID if already registered
  -> 409 Conflict                            # INCOMPATIBLE: with a precise reason
     { "error_code": 409,
       "message": "Schema being registered is incompatible with an earlier
                   schema for subject 'orders-value', details:
                   field 'region' added without default violates BACKWARD" }

POST /compatibility/subjects/{subject}/versions/latest   # DRY-RUN check (CI gate)
  { "schemaType":"AVRO", "schema":"{...}" }
  -> { "is_compatible": true }               # check WITHOUT registering - used in CI

PUT  /config/{subject}                       # set compatibility level for a subject
  { "compatibility": "BACKWARD_TRANSITIVE" } # or FORWARD, FULL, NONE, *_TRANSITIVE
PUT  /config                                 # set the GLOBAL default level

The /compatibility/... dry-run endpoint is the quiet hero: teams wire it into CI so an incompatible schema fails the pull request, long before deploy - the gate moves left, and the registration at deploy time becomes a formality that cannot fail.

Lookup API (the read plane - the hot path, cache-fronted)

GET /schemas/ids/{id}                        # THE per-message lookup (by GLOBAL id)
  -> { "schemaType":"AVRO", "schema":"{...}" }   # exact writer schema, forever
     served from an in-memory map; cached on the client; this is the core read.

GET /subjects/{subject}/versions             # list version numbers for a subject
  -> [ 1, 2, 3, 4, 5 ]
GET /subjects/{subject}/versions/{version}   # a specific version (immutable)
  -> { "subject":"orders-value", "version":4, "id":4470, "schema":"{...}" }
GET /subjects/{subject}/versions/latest      # newest version for producers
GET /subjects                                # list all subjects

DELETE /subjects/{subject}/versions/{version}  # SOFT delete (hide from listing)
  # NEVER frees the schema ID or its bytes - messages with that ID still resolve.
  # A "hard delete" exists for compliance only and is guarded + exceptional.

Data schema: the stored model

The store is deliberately small and relational-shaped, but the message store it protects is not relational at all. SQL vs NoSQL:

TABLE schemas            -- the immutable ledger of distinct schemas
  id             BIGINT PRIMARY KEY          -- global, monotonic, write-once
  schema_type    ENUM('AVRO','PROTOBUF','JSON')
  canonical_text TEXT                         -- canonicalized schema source
  fingerprint    CHAR(64)                     -- sha256(canonical_text)
  created_at     TIMESTAMP
  UNIQUE INDEX (fingerprint)                  -- dedup / idempotent registration

TABLE subject_versions   -- the per-subject ordered history (immutable rows)
  subject        VARCHAR
  version        INT
  schema_id      BIGINT  REFERENCES schemas(id)
  deleted        BOOLEAN DEFAULT false        -- soft-delete flag only
  PRIMARY KEY (subject, version)
  INDEX (schema_id)                           -- "which subjects use this schema"

TABLE subject_config     -- per-subject compatibility (one of the few mutable things)
  subject        VARCHAR PRIMARY KEY
  compatibility  ENUM('BACKWARD','BACKWARD_TRANSITIVE','FORWARD',
                      'FORWARD_TRANSITIVE','FULL','FULL_TRANSITIVE','NONE')

TABLE schema_references  -- a schema that embeds another (version-pinned)
  schema_id      BIGINT REFERENCES schemas(id)
  ref_name       VARCHAR          -- the name used inside the schema
  ref_subject    VARCHAR
  ref_version    INT              -- PINNED version -> reproducible composite
  PRIMARY KEY (schema_id, ref_name)

Why this storage split - a small relational/log store for metadata, nothing on the broker:

StoreHoldsWhy this choice
Replicated log (or SQL) of schemasthe immutable schema ledgertiny, write-once, needs ordering + strong consistency on append, fully replicable to memory
In-memory map on every nodeid -> schema, materializedmicrosecond lookups; the whole corpus fits in RAM; reads survive leader loss
Client-side cachesid -> schema, schema -> idcollapse millions/sec of demand to a trickle; immutable data -> cache forever, no invalidation
The message bus (not the registry)the actual messages + 5-byte IDregistry is NOT in the data path; only an immutable ID rides the wire

SQL vs NoSQL, decided: the metadata store is small, relational (subjects, versions, references, a global ID sequence), strongly consistent, and append-mostly - a single relational database (or a compacted log that materializes into one) is exactly right, and the single-writer leader makes its concurrency story trivial. You do not reach for a sharded NoSQL store: there is nothing to shard (a few GB), and you would be throwing away the easy strong consistency you need for the compatibility check to buy a scale you do not have. The one place NoSQL-style thinking wins is the serving layer, which is just an in-memory key-value map - but that is a cache materialized from the relational truth, not the system of record.

Bottlenecks & Scaling

Where it breaks first, in order, and the fix for each. Note that several “classic” bottlenecks (sharding, write throughput) barely apply here - naming why is itself the senior insight.

1. The registry in the per-message path (the catastrophic naive failure). If serializers/deserializers call the registry for every message, you need millions of lookups/sec and the registry becomes a hard dependency in the hottest path on the platform - one blip stalls every pipeline. Fix: client-side caching of immutable mappings. Producers cache schema->ID, consumers cache ID->schema, both forever (the data never changes meaning). Demand collapses to cache misses only - thousands/sec, not millions. This is not an optimization; it is the architecture. The registry is a control-plane/metadata service that must never be load-bearing per message.

2. Read availability - registry down stalls consumers. A consumer that hits a cache miss and cannot reach the registry cannot deserialize, and the pipeline halts. Fix: replicate the (tiny) corpus to every node and serve reads from in-memory maps on horizontally-scaled read replicas, decoupled from the leader. Because schemas are immutable, replicas never serve stale/wrong data and keep serving even when the write leader is down. Add client cache warming at startup (pre-fetch the IDs a consumer’s topics use) so cold starts do not stampede.

3. Concurrent-registration race corrupting history. Two compatible-with-latest-but-mutually-incompatible schemas both get admitted (the Approach-A failure). Fix: single-writer leader elected by consensus so the read-modify-write compatibility check is linearizable. Cheap because writes are rare; correct because nothing else can interleave. HA via Raft failover, not via multiple concurrent writers.

4. Write availability / leader as a single point of failure. The single writer dies; registrations stop. Fix: consensus-based leader election (Raft, 3-5 nodes). A new leader is elected in seconds. Registrations (human-paced, rare) tolerate a brief pause; nothing in the running data plane depends on the leader because reads come from replicas and client caches. This is the right place to spend the single-writer’s one weakness - it only ever affects rare writes.

5. Compatibility checks getting slow (transitive against long history). A *_TRANSITIVE check on a subject with hundreds of versions compares against every prior version on every registration. Fix: this is rare-path work (a few registrations/day) so modest cost is fine, but cap it: limit version history retained for transitive checks to the retention window of the underlying topic (you only need compatibility with versions whose messages could still be read), and cache canonicalized/parsed prior schemas so each check is CPU-bound in-memory, not re-parsing text. Correctness over speed here, always.

6. Hot schema IDs. A few IDs (the current versions of the busiest topics) account for nearly all lookups. Fix: this is a non-problem and worth saying why: hot IDs are the most-cached IDs, so they almost never reach the registry; when they do, every replica already holds them in memory. There is no hot-key storage problem because there is no sharding - every node has everything. The skew is absorbed entirely by caching.

7. Schema corpus growth over many years. Decades of evolution accumulate versions. Fix: barely a concern - the BoE says a few GB after years. Soft-deleted/hidden versions can be excluded from working indexes; the raw immutable ledger is retained forever (cheap) because old IDs must always resolve. If it ever mattered, archive cold schema bytes to object storage while keeping the id->location index hot - but you will likely never need to.

8. Multi-region / multi-datacenter latency. Clients in a remote region pay cross-region latency on cache misses. Fix: replicate the corpus to a read replica in every region (immutable data replicates trivially and can never conflict), serving local misses with local latency. Keep a single global writer (or a single primary region for registration) so the linearizable compatibility check stays globally serial - acceptable because registration is rare and latency-insensitive. Reads local and fast, writes global and rare: the perfect split for this workload.

9. A bad schema slips past because the rule was too lax (NONE) or non-transitive. Someone set compatibility to NONE for convenience, or non-transitive compatibility let a change break an old-but-still-retained message. Fix: policy, not just mechanism. Default subjects to a strict transitive rule; require explicit, audited sign-off to weaken it; wire the dry-run compatibility endpoint into CI so breaks fail the PR; and set the transitive window to match topic retention so “compatible” always means “every message a consumer could still read is safe.” The registry enforces the rule; governance sets the rule correctly.

10. Envelope/ID coupling to one registry’s ID space. Schema IDs are only meaningful within one registry; replicating messages across clusters (mirror) can collide ID spaces. Fix: keep a single global ID authority (one logical registry, replicated) so an ID means one thing everywhere messages flow; when bridging truly independent registries, translate IDs at the mirror boundary (re-register the schema in the target and rewrite the envelope ID) or run a shared registry across clusters. Never let two registries mint overlapping IDs into the same message population.

Wrap-Up

The trade-offs that define this design:

  • Enforce at write time, resolve at read time. The two promises - “nothing that breaks a reader is ever written” and “the exact writer schema is always fetchable” - are kept at different moments: a one-time compatibility check at registration, and a 5-byte immutable ID embedded per message resolved through forever-caches. The registry is a gate at the front and a lookup table on the side, never in the per-message hot path. That placement is the entire performance story.
  • A metadata service, not a data service. The corpus is a few GB, write rate is near zero, read demand is millions/sec that client caches collapse to a trickle. So the answer is replicate-everywhere-and-cache-forever, not shard-and-partition - and because the data is immutable, caches never need invalidation, which is what makes the collapse safe.
  • Single writer for correctness, cheap because writes are rare. The compatibility check is a read-modify-write over a subject’s whole history and must be linearizable, so one consensus-elected leader serializes all registrations. A disastrous choice for a data plane; the ideal choice for a metadata plane with a few writes a day.
  • Immutable, write-once, retain-forever storage. A schema ID, once issued and embedded in any message, can never be deleted or reused, because messages outlive schemas by years. The store is an append-only ledger; “delete” only ever hides, never frees.
  • Compatibility rules are mechanical but governance is not. Backward/forward/full and their transitive variants fall directly out of what a reader does with a present or absent field; the engine is a structural diff. But choosing the right rule per subject, defaulting to strict and transitive, and shifting the check left into CI is policy work the registry enables but does not decide.

One-line summary: a small, strongly-consistent, cache-everywhere metadata service that gates every schema registration through a format-aware compatibility check against the subject’s version history behind a single consensus-elected writer, stores accepted schemas as an immutable write-once ledger keyed by a global ID, and embeds that 5-byte ID in every message envelope so any consumer - years and many evolutions later - can fetch the exact writer schema and deserialize, all without the registry ever sitting in the per-message path.