Skip to content
Tech Interview Prep
Technical interview guide

Schema Evolution & Versioning

Changing a shared schema without breaking every downstream consumer that depends on it.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v5
Editorial status
Reviewed
Relevant for
Data Architect

Scope: Apache Avro and Iceberg current specifications, Protobuf edition 2024 guidance, Confluent Schema Registry current compatibility modes, Delta Lake protocol, PostgreSQL 18, JSON Schema 2020-12, OpenAPI 3.1.1, and Parquet logical types current 2026-08-31.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-2

Choose a Schema Registry compatibility mode.

Answer

Core answer. Assume Confluent Schema Registry, Avro/Protobuf/JSON Schema subjects, and that you can choose the deploy order. The mode is not a preference: it is the direction of schema change you must survive, and that direction is fixed by two facts: which side you can upgrade first, and how far back your readers replay. The registry default is BACKWARD. Pick it when consumers can ship before producers. Pick FORWARD when producers must ship first (external producers, or a team you cannot coordinate with). Pick FULL when you cannot guarantee either order. Add the _TRANSITIVE variant when readers can be pinned to versions older than the latest: long retention, batch jobs, offline clients.

ModeRegistry accepts a new schema ifDeploy order it implies
BACKWARD (default)it can read data written by the previous versionconsumers first
BACKWARD_TRANSITIVEit can read data written by every previous versionconsumers first
FORWARDthe previous version can read data written by itproducers first
FORWARD_TRANSITIVEevery previous version can read data written by itproducers first
FULLboth directions, against the previous versioneither, but both sides must ship
FULL_TRANSITIVEboth directions, against every previous versioneither
NONEalwaysnone enforced

Non-transitive checks compare only against the latest registered version. That is the trap: a change can pass the check and still break a consumer that is two versions behind.

Worked trace (Avro). Start with Order{orderId: string, amountCents: long}.

  • Add currency: string with default: "USD". New reader reads old data (default fills in); old reader ignores the unknown field. Passes BACKWARD and FORWARD → FULL.
  • Remove amountCents. New reader ignores it, so BACKWARD passes. Old reader now expects a field the writer no longer emits and has no default → FORWARD fails.
  • Add region: string with no default. New reader cannot read old data that lacks region → BACKWARD fails.

So "add an optional field" is the only one of the three that is safe in both directions. Protobuf behaves similarly: a new field with a fresh tag number is compatible both ways; changing a field to a different wire type is not. JSON Schema: adding an optional property is backward compatible, adding a required one is not.

Failure modes.

  1. BACKWARD (non-transitive) with a consumer pinned to v1 while the producer moves to v3. Registering v3 checks only against v2 and passes. The v1 consumer throws an Avro deserialization error on the first v3 record. Detection: consumer deserialization error rate and DLQ depth, both of which jump within one produce-to-consume cycle. Cost: the consumer stops advancing and lag grows until you roll the producer back or upgrade the consumer.
  2. FORWARD with a producer that adds a required field. Old consumers fail immediately after the producer deploy. Same detection signal, but it appears in the same deploy window as the change, so attribution is easy.
  3. NONE. An incompatible schema registers cleanly and nothing fails until a consumer reads a record written with it. Detection is read-time only. Cost: the failure is decoupled from the change, so the deploy that caused it is no longer in the window when you are debugging.
  4. FULL_TRANSITIVE cost. It blocks removing a field nobody reads, because removal is not forward compatible. You keep the field forever or fork the subject.

The pre-deploy signal is the registry returning HTTP 409 with an incompatible-schema error on register; check before you register with POST /compatibility/subjects/<subject>/versions/latest. The post-deploy signal is consumer-side deserialization exceptions.

Scope and change control. Compatibility is per subject; the default subject is <topic>-value under TopicNameStrategy, so a key schema and a value schema are checked independently. Override the global level with PUT /config/<subject>. Setting a subject to NONE disables the check for every later registration on it, so treat it as a time-boxed change with a ticket and an expiry, not a default.

What would change the decision. A 30-day replay window or an offline consumer makes non-transitive unsafe: move to _TRANSITIVE. If you cannot coordinate deploys at all, FULL. If you own both ends and ship them atomically, NONE is defensible for the duration of that release.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-1

Plan an additive field change on an event schema.

Answer

Core answer

Assume Avro on Confluent Schema Registry over Kafka, and the subject's compatibility is the default BACKWARD. If it's Protobuf the plan has the same shape but different mechanics (field numbers, unknown-field preservation).

The plan: add the field as optional with an explicit default, register the new schema, deploy consumers that understand it, then deploy producers that emit it. Never the reverse.

  1. Write the field with a default: {"name":"ingest_ts_ms","type":["null","long"],"default":null,"doc":"producer clock at emit"}. The default is what makes the change backward compatible.
  2. POST the schema to the registry. If the subject is BACKWARD_TRANSITIVE, it must be readable by every prior version, not just the last.
  3. Deploy readers first: they decode old records because the default fills the missing field.
  4. Canary producers, watch the null-rate of the new field.
  5. Keep the previous schema ID for rollback.

Why the ordering works

Avro resolution is reader-schema-driven. The reader walks its own schema; for each field it looks for a match in the writer's schema. If absent, it uses the reader's default. So a new reader reading an old record gets null: no error. An old reader reading a new record never looks at the unknown field: also no error. Adding a field with a default is therefore both backward and forward compatible; adding one without a default breaks backward compatibility, because the new reader has nothing to fill in.

Protobuf: new field number, optional (or a wrapper type if you need presence). Unknown fields are retained on the wire and preserved through re-serialization since proto3 3.5, so old services pass the field through untouched. Never reuse a retired field number: mark it reserved 7;.

Registry modes

ModeAdd field with defaultAdd field without default
BACKWARD (default)passesfails
FORWARDpassespasses
FULLpassesfails
BACKWARD_TRANSITIVEpassesfails
NONEpassespasses, and that's the danger

NONE is the mode that lets a broken schema into production. Check it with GET /config/<subject> before you plan anything.

Trade-offs

  • Default value vs nullable union. ["null","long"] with default: null is honest: absence is representable. A fabricated default like 0 or "" makes old records indistinguishable from records where the producer genuinely sent zero. Prefer null unless the field is truly non-nullable.
  • New field vs new topic. If the semantics change (units, meaning, cardinality), a new field on the same topic forces every consumer to reason about two meanings. A new topic costs a new consumer group, ACLs, and a dual-write window, but it keeps the old contract frozen.
  • Protobuf optional vs wrapper. optional int64 gives presence in proto3; google.protobuf.Int64Value gives presence plus a nullable-shaped API. Pick based on whether your generated code can express "unset".

Failure modes

  • Missing default. Registration fails under BACKWARD with Schema being registered is incompatible with an earlier schema. If the mode is NONE, it registers and consumers throw an AvroTypeException at decode. Detect: consumer error rate, DLQ depth.
  • Default masking a bug. A producer that never populates the field looks identical to one that legitimately sends null. Detect: per-field null-rate metric, alert if it stays at 100% after the writer rollout.
  • Unknown-field drop. A Protobuf service that rebuilds messages from a hand-written field list loses the new field. Detect: CI round-trip test that serializes, deserializes, re-serializes, and diffs bytes.
  • Semantic drift. The registry checks structure, not meaning. A field named latency in ms vs µs passes every compatibility check. Detect: contract test against a known fixture.

Rollback

Keep the previous schema ID; rolling back producers is safe because readers already tolerate both shapes. Rolling back readers is not: do it only after producers stop emitting the field.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

How do you evolve schemas in streaming and batch pipelines without breaking downstream consumers?

Answer

Core answer (first 90 seconds). Treat the serialized payload as a public API with a versioned contract, and make every change additive. Three rules do the work: enforce compatibility in the registry rather than in code review; sequence deploys by the direction of compatibility; and for batch tables, resolve columns by immutable field ID, never by name or position. If a change genuinely cannot be additive, do not mutate the schema: publish a new subject (orders-v2) and dual-write until consumers migrate.

Compatibility direction decides deploy order.

ModeGuaranteeDeploy orderSafe mutations
BackwardNew reader parses old writerConsumers firstAdd field with default; delete field
ForwardOld reader parses new writerProducers firstDelete optional field; add optional field
FullBothAnyAdd with default; delete optional with default
Full TransitiveNew schema vs. all historical versionsAnySame as Full, checked against every version

Set the subject to FULL_TRANSITIVE and gate CI on POST /compatibility/subjects/orders-value/versions/latest with the candidate schema; it returns {"is_compatible": false} plus the offending path. Plain BACKWARD only checks the previous version, which is not enough when a consumer replays a 3-day backlog: at an illustrative 20k msg/s that is ~5.2 billion records spanning every schema version written in the window.

Avro: the default is the contract. Payloads carry a 5-byte prefix (magic byte 0x0 + 4-byte big-endian schema ID). The consumer fetches the writer schema by ID and projects it onto its reader schema. Adding a field without a default breaks that projection:

JSON
// v1 writer
{"type":"record","name":"OrderEvent","fields":[
  {"name":"order_id","type":"string"},
  {"name":"amount_cents","type":"long"}]}

// v2 reader, field added WITH default -> old records decode as currency="USD"
{"name":"currency","type":"string","default":"USD"}

Drop the default and decoding a v1 record throws AvroTypeException: Found OrderEvent, expecting OrderEvent, missing required field currency. That is a runtime failure on the consumer, not a registry rejection, unless you run the compatibility check first.

Protobuf: tags are the identity. Field numbers 1–536,870,911 (19000–19999 reserved) define the wire contract; names are irrelevant. Reusing a tag is the classic silent corruption. If v1 has int64 amount_cents = 3 and v2 reuses tag 3 as int32 quantity = 3, a v1 record with amount_cents = 4999 decodes in a v2 reader as quantity = 4999: same wire type, no error, wrong number. Retire tags explicitly:

Protobuf
syntax = "proto3";
message OrderEvent {
  string order_id = 1;
  reserved 2, 7;
  reserved "tax_amount", "internal_code";
  int64 amount_cents = 3;
}

proto3 preserves unknown fields (since 3.5), so a dropped field does not corrupt the payload, but readers fall back to zero values (0, "", false), which is indistinguishable from a real zero. Use optional and check presence when absence is meaningful.

Batch tables: field IDs, not names. Iceberg assigns immutable field IDs; renaming or reordering a column in table metadata leaves the Parquet files untouched, so engines reading by ID keep working. Delta Lake gives the same guarantee under delta.columnMapping.mode = id. The trap is drop-and-re-add: the new column gets a fresh field ID and every historical row reads as NULL.

Failure modes and detection.

  1. Compaction divergence. A streaming job appends Parquet files under schema-id X while compaction rewrites older files under schema-id Y. If the rewrite does not project by field ID, type mismatches surface as query failures. Detect by running a SELECT against the oldest snapshot in CI before committing the metadata update.
  2. Default swallowing. A field removed from the writer and read as a proto3 zero looks like valid data. Detect with a presence check on optional fields and a null-rate alert on the column.
  3. Registry bypass. A producer writing directly to the topic skips the compatibility check entirely. Detect by alerting on payloads whose schema ID is absent from the registry.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

How do you handle default values and schema evolution in columnar storage formats like Parquet and Delta Lake versus row-based formats like Avro?

Answer

Row-based Avro handles evolution at serialization boundaries using pairwise reader and writer schema resolution, whereas columnar formats like Parquet and table formats like Delta Lake separate physical column chunks from logical schema representation, shifting default values and resolution into query planning and table metadata.

Mechanism Breakdown

  1. Row-Oriented Resolution (Avro): Avro binary encoding omits field tags and types from the data stream. Deserialization requires traversing writer schema $S_w$ and reader schema $S_r$ simultaneously:
  • Identity Matching: Fields match by name, falling back to names declared in the reader field's aliases attribute.
  • Default Value Semantics: If $S_r$ contains a field not present in $S_w$, Avro checks $S_r$ for a default definition. If present, the decoder populates the field with that default value; if absent, deserialization fails immediately with an IncompatibleSchemaException. Defaults defined in $S_w$ are never consulted during resolution.
  • Skipping Unread Fields: If a field exists in $S_w$ but is absent from $S_r$, the decoder uses the type definitions in $S_w$ to skip the field's bytes. Variable-length primitives like string and bytes store their length as a leading varint, while fixed-width primitives have static byte lengths defined by their type.
  1. Columnar Storage (Raw Parquet): Parquet physically groups data into column chunks within row groups. Field matching relies on schema paths embedded in the file-level FileMetaData footer, or optionally on explicit field IDs assigned in schema metadata:
  • When a reader requests a column that does not exist in a Parquet file's schema, the reader engine synthesizes an in-memory vector filled entirely with NULLs for the affected row group batches.
  • The Parquet format specification defines encodings and logical types, but does not provide a native file-level mechanism to substitute arbitrary non-null literals into missing columns of existing files.
  1. Table Formats (Delta Lake): Delta Lake decouples the query engine's logical schema from physical Parquet file structures via an append-only JSON transaction log (_delta_log):
  • Schema additions (ALTER TABLE ADD COLUMN) commit a new metadata action to the log.
  • Non-null Defaults: Query engines (like Spark) inspect the Delta transaction log schema at plan time. If a file was written under a schema version that preceded an added column with a default value, the query optimizer injects the literal or expression directly into the physical scan projection as a synthetic column, avoiding data rewrites.
  • Field IDs and Column Mapping: Under delta.columnMapping.mode = 'name' or 'id', columns are assigned physical names or IDs (written into Parquet field IDs). Renaming or dropping a column only writes an updated metadata action to _delta_log; older Parquet files remain intact without schema mismatch.
Avro Decoding:
  Stream:       [val1: long][val2: bytes (len + data)]
  Resolution:   Decode val1 -> skip val2 -> inject default for missing field declared in S_r

Delta/Parquet Scan:
  Log (v2):     Schema contains [c1: INT, c2: STRING, c3: STRING DEFAULT 'pending']
  Parquet (v1): Chunks [c1], [c2]
  Execution:    Read [c1], [c2] from disk -> Project c3 = 'pending' in-memory vector

Comparison

DimensionApache AvroApache ParquetDelta Lake (over Parquet)
Identity ResolutionName + aliases (in reader schema)Field name path or Parquet field IDField ID or physical name mapping via transaction log
Missing Field FallbackReader schema default (fails if absent)Imputes NULL vectorProjects metadata-defined default or NULL at query planning
Writer Schema RoleSupplies types and byte lengths for skipsDefines column chunks present in row groupPreserved in immutable historical data files
Column RenamingReader specifies old name in aliasesEngine-dependent; re-encodes unless field IDs matchedMetadata-only commit via delta.columnMapping.mode

Failure Modes & Edge Cases

  • Silent NULL Assignment: Introducing a field intended to be non-nullable across a Parquet dataset without a governing table-format layer causes readers to produce NULL values when scanning pre-migration files, bypassing downstream application invariant assertions.
  • Planning Latency from Schema Merging: If a query engine accesses unmanaged Parquet directories with evolving schemas and sets mergeSchema=true, the engine must execute file footer reads across all matched files to unify schemas, causing query planning time to scale linearly with file counts ($O(N)$ S3 GET operations).

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Add an enum value used by many consumers.

Answer

Assume you own the schema and can coordinate a staged rollout across the consumer fleet. The core move is to make the change additive and backward-compatible: deploy readers that tolerate an unknown enum value first, then let producers emit it. If you emit before readers understand it, you get failures that range from silent data loss to hard crashes.

Why readers first? Because an enum is a closed set in most type systems. In Java, a switch expression over an enum is exhaustive: adding a new constant makes the code fail to compile until you handle it. That's a good forcing function, but only if you deploy the updated code before the producer starts sending the new value. If you use a switch statement without a default, the new value falls through and the method returns null or does nothing: a silent bug. In Avro, the reader's schema must contain the symbol or define a default. Without a default, resolving a record with an unknown symbol throws AvroTypeException. With a default, the reader maps the unknown symbol to the default, which may be acceptable if the default is a safe fallback like UNKNOWN or PENDING.

Here is a Java 17 switch expression that would break if you add a value:

Java
enum OrderStatus { PENDING, SHIPPED, DELIVERED }

String describe(OrderStatus s) {
    return switch (s) {
        case PENDING -> "waiting";
        case SHIPPED -> "in transit";
        case DELIVERED -> "done";
    };
}

Add CANCELLED and the compiler rejects it: "the switch expression does not cover all possible input values." That forces you to add a case. But if you had a switch statement with no default, it would compile and silently do nothing for CANCELLED.

Avro schema evolution works similarly. Suppose the producer schema is:

JSON
{
  "type": "enum",
  "name": "OrderStatus",
  "symbols": ["PENDING", "SHIPPED", "DELIVERED"],
  "default": "PENDING"
}

If you add "CANCELLED" to the producer's symbols, a reader with the old schema and default "PENDING" will map CANCELLED to PENDING. Without the default, it fails. So the default is your fallback, but it can hide errors if CANCELLED is semantically different from PENDING.

Databases add another constraint. If you store the enum as a string with a CHECK constraint, adding a value requires altering the constraint. If you use a lookup table, you need to insert the new row. Both must happen before producers emit, or inserts fail.

Trade-offs: You could avoid enums and use strings, but you lose type safety and exhaustive checking. You could version the enum, but that's complex. The decision point is whether you can coordinate all consumers. If not, you need a fallback that maps unknown to a safe default, but you must monitor it. Canary emission: send the new value to 1% of traffic for 24 hours (hypothetical), watch consumer error rates and unknown-value counters. Alert if unknown values exceed 0.1% of requests for 5 minutes.

Failure modes: silent mapping to the wrong category (e.g., CANCELLED mapped to PENDING) corrupts analytics. Consumer crashes if no default. Database constraint violations. Dashboards showing an "unknown" bucket. Detection: log the raw unknown symbol, monitor consumer error rates, and track canary metrics.

FormatAdding a valueReader behavior on unknown
AvroAdd symbol to producer schemaIf reader has default, maps to default; else throws
Protobuf (proto3)Add value to enumUnknown values preserved as int; client must handle
JSON/stringAdd stringNo schema enforcement; client must handle
Database CHECKAlter constraintInsert fails until constraint updated

Steps: 1) Define the new value's meaning and effective time. 2) Update readers: add a default or explicit mapping. Deploy readers. 3) Canary producers. 4) Monitor unknown/default paths and consumer errors. 5) Roll out producers. 6) Communicate versions.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

Rename an Avro field safely.

Answer

Clarify first. Two things decide the whole plan: is the rename cosmetic (same type, same meaning) or semantic, and can you redeploy every reader before the writer changes? If readers can't all move first, this is a dual-write, not a rename. Also check whether the field is in the key schema or a partition key, if it is, don't rename, cut a new topic.

The short answer. A rename is two schema changes, not one. First, add the new name to the reader schema with an alias for the old name, and leave the writer writing the old name. Second, once every reader is on the new schema, flip the writer. Between the steps, old data reads under the new schema and new data reads under the old schema: provided the old reader's field has a default.

Why it works. Avro resolves reader against writer at read time. Record fields match by name, or by a reader-side alias equal to the writer's field name. The spec's rule is that aliases rewrite the writer's schema using the reader's aliases, so aliases live only in the reader and only help in the reader direction. A writer field with no reader counterpart is dropped. A reader field with no writer counterpart takes its default, or the read fails if it has none. Aliases are not transitive: a reader aliasing B does not match a writer that wrote A, so a second rename silently breaks anyone still on the first name.

JSON
// writer v1 — unchanged
{"type":"record","name":"Order","namespace":"com.acme",
 "fields":[{"name":"user_id","type":"string"}]}

// reader v2 — rename with alias
{"type":"record","name":"Order","namespace":"com.acme",
 "fields":[{"name":"userId","type":"string","aliases":["user_id"]}]}
writer writesreader schemaresolution
user_iduserId + alias user_idmatched, value preserved
user_iduserId, no aliasreader field missing → default, else error
userIduser_id, no aliasreader field missing → default, else error

Registry gate. Confluent Schema Registry's default level is BACKWARD (new schema reads data written by the previous one). The alias version passes BACKWARD and fails FORWARD, because the old reader has no alias for userId. Under FULL the rename is rejected outright. Confirm your registry's checker actually honors aliases before trusting a green check: some versions treat any rename as incompatible. Note the parsing canonical form strips aliases, so an alias-only edit doesn't change the wire format.

Failure modes.

  • Old reader, new writer, no default: AvroTypeException: ... missing required field user_id the moment the producer flips. Detection is a consumer error-rate spike on that topic.
  • Alias chain: A→B→C doesn't compose, so a second rename breaks readers still on A. Detection: replay archived data through the current reader in CI.
  • Alias collision: an alias equal to another field's name is a parse error and registration fails.
  • Generated code: old jars expose getUser_id(), the new schema generates getUserId(). Code compiled against the old schema won't see the field even though the data is there: caught at compile time, which is the cheap one.
  • Downstream sinks keyed on the name (Hive/Parquet column, Flink SQL DDL): the column silently goes null. Detection: null-count on that column.

What changes the decision. Adding a default just to make FORWARD pass is a semantic change: a reader defaulting to null can't distinguish "absent" from "null". If readers can't all be redeployed, dual-write both names for a window, measure old-name reads, then drop the old field.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Remove a Protobuf field safely.

Answer

What a strong candidate says first

Assume proto2 or proto3 with protoc 3.21+, binary and JSON consumers, and stored messages you cannot rewrite. Removal is a staged rollout, not one edit: deprecate, stop writers, make readers tolerant, then delete the definition and reserve the number and name. Reserving is permanent: you can never reuse that tag.

Mechanism: why the order matters

Every field on the wire is a tag: (field_number << 3) | wire_type.

wire typepayloadfield types
0varintint32, int64, bool, enum
164-bitfixed64, double
2length-delimitedstring, bytes, message, packed repeated
532-bitfixed32, float

Reusing tag 4 is the failure that bites. An old reader still compiled with field 4 sees the new bytes. If the wire type matches (old int32, new int64: both varint), it decodes the new value as the old type: silent corruption, no error. If the wire type differs (old int32, new string), the reader skips it and keeps it as an unknown field, then re-emits it downstream. Either way the number is poisoned forever, which is why reserved is not optional.

Unknown fields are preserved because proto3 since 3.5 (and proto2 always) stores unrecognized fields in an UnknownFieldSet and re-serializes them. That is what lets a proxy that never heard of field 4 forward it intact, and why calling discardUnknownFields() anywhere in the path silently strips data.

Trade-offs

  • Deprecate vs delete: [deprecated = true] is reversible and generates warnings; deleting the definition is the point of no return. Do the first, then the second.
  • Staged vs big-bang: big-bang is acceptable only when you own every writer and reader, deploy atomically, and have no stored data or external consumers. Otherwise stage it.
  • Stopping writers: fine when you control all producers and can deploy them ahead of readers. Not fine with third-party producers or long-lived stored messages: there, readers must tolerate absence first.

Artefacts

Protobuf
message Order {
  reserved 4, 7 to 9;      // numbers; range is inclusive
  reserved "legacy_id";    // names
}

protoc fails the build if anyone reuses a reserved number or name.

Tolerant JSON reader (protobuf-java 3.25.x):

Java
JsonFormat.parser()
    .ignoringUnknownFields()   // old producers still send "legacy_id"
    .merge(json, Order.newBuilder());

Binary readers need no change: generated parsers preserve unknown fields by default. Just never call builder.discardUnknownFields().

Failure modes and detection

  • Tag reuse with a matching wire type → silent value corruption. Detect with golden-message round-trips across schema versions.
  • JSON reader without ignoringUnknownFields() → 400s on old payloads. Detect with a contract test replaying a pre-removal payload.
  • A proxy calling discardUnknownFields() → field vanishes, downstream reads the default. Detect with a proxy round-trip test.

Keep descriptor history and a rollback path; monitor per-field usage before you delete.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Tighten an optional field to required.

Answer

First I'd clarify: which database, how big is the table, and what does null mean today? Assuming Postgres 12+ and a 200M-row table with live traffic, the core answer is: don't run ALTER TABLE ... SET NOT NULL directly. It takes an ACCESS EXCLUSIVE lock and scans the whole table, blocking reads and writes for minutes. Instead, add a NOT VALID CHECK constraint, backfill in batches, validate the constraint, then set NOT NULL, which can skip the scan because the validated constraint proves no nulls exist.

Deploy readers that tolerate nulls first. During backfill, some rows still have null. If you flip producers to always write non-null before readers are updated, old readers that assume non-null will break on rows not yet backfilled. So: dual-read (handle both), then start writing non-null, then backfill, then enforce, then remove null-handling code.

Backfill in batches of 10k rows with a 100ms sleep between batches. Use a partial index on id WHERE col IS NULL so the batch select is fast. Set lock_timeout='2s' and statement_timeout='30s' on the backfill session so it never blocks a critical write for long. Monitor replication lag via pg_stat_replication; if it exceeds 5s, pause.

The constraint dance:

SQL
ALTER TABLE t ADD CONSTRAINT t_col_not_null CHECK (col IS NOT NULL) NOT VALID;
-- fast, no scan, brief ACCESS EXCLUSIVE
-- backfill here
ALTER TABLE t VALIDATE CONSTRAINT t_col_not_null;
-- SHARE UPDATE EXCLUSIVE, allows reads and writes, scans table
ALTER TABLE t ALTER COLUMN col SET NOT NULL;
-- uses the valid constraint to skip the scan, brief ACCESS EXCLUSIVE

Failure modes: If you skip NOT VALID, the ADD CONSTRAINT scans under ACCESS EXCLUSIVE, blocking all writes for minutes. Detect via pg_locks and lock_timeout. If backfill runs in one transaction, it holds row locks and bloats WAL; detect via pg_stat_activity and replication lag. If producers still write null after SET NOT NULL, they get a 23502 not-null violation; monitor error rates. If readers aren't updated, they may throw NPEs on null; monitor application logs.

Trade-offs: When not to do this: if null means 'not applicable' or 'unknown' and that distinction matters, forcing required destroys information. Better to keep nullable and enforce at the application layer, or add a separate status column. Also, if the table is small (<1M rows) and you can take a maintenance window, a direct ALTER is simpler. Deciding criteria: does an authoritative source exist to backfill? If not, you're choosing a sentinel value, which is a product decision, not just a migration.

For a schema registry (Avro/Protobuf), making an optional field required is a breaking change. You need a new schema version, a migration period where consumers accept both, and a producer rollout that always sets the field. The same reader-before-writer rule applies.

approachlockscanwhen
direct SET NOT NULLACCESS EXCLUSIVEfull tablesmall table, maintenance window
NOT VALID + VALIDATE + SET NOT NULLbrief ACCESS EXCLUSIVE, then SHARE UPDATE EXCLUSIVEno scan on SET NOT NULLlarge table, live traffic

That's the core. The key is to separate the data backfill from the constraint enforcement, and to make every step reversible.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

How do you add, rename, or retype a field inside a nested record without breaking consumers that read the parent record?

Answer

Core answer (first 90 seconds)

Treat a nested field change as a change to a leaf path, not to the parent record. Compatibility is evaluated per leaf path. A consumer that projects user.id is unaffected by adding user.email, but breaks if you rename user.id to user.uid: even though the user record's shape is otherwise identical. So the first move is to enumerate which leaf paths each consumer reads, then apply the format's identity rule at that path.

Assumptions: Avro or Protobuf on the wire, Parquet/Iceberg on storage, Schema Registry in BACKWARD mode unless stated.

Identity rules decide everything

FormatNested identityAdd nested fieldRename nested fieldRetype nested field
Avroname + aliases, resolved recursivelyreader schema needs default at the nested levelalias on the nested field itselfnot allowed; resolution fails
Protobuffield numbernew number, safesafe (name is cosmetic)safe only within wire-compatible groups (int32/int64/uint32/uint64/bool; string/bytes if UTF-8)
Parquetfield path or field IDold files project NULLsafe with field IDs; breaks with path-onlyonly spec promotions: int32→int64, float→double, decimal precision up
Icebergfield IDsafe, old files nullsafe, ID preservedsafe within promotion rules

Avro's default propagation gotcha

Adding a nested field with a default is not enough if the parent field itself has a default. The parent default is a JSON object that must match the new nested schema.

json // v1 {"type":"record","name":"Event","fields":[ {"name":"user","type":{"type":"record","name":"User","fields":[ {"name":"id","type":"string"} ]},"default":{"id":""}} ]}

Add email with default "" inside User. The nested default is valid, but the parent user default {"id":""} no longer matches User, so the schema fails to parse at registration. You must update it to {"id":"","email":""}. This is the most common nested-evolution failure I've seen in Avro: the change looks additive, but the parent default makes it a breaking schema edit.

Projection blast radius

A reader that selects only user.id reads one leaf column. In Parquet, that's one column chunk; in Iceberg, one field ID. Adding user.email doesn't touch it. Renaming user.id does: with field IDs the reader still resolves by ID, but any name-based access (Spark SQL user.id, a JSON Schema required path, an OpenAPI property) breaks. Retyping user.id from string to int breaks the reader's decoder even if the parent record is unchanged. So the compatibility check must recurse into every struct and report per leaf path, not per top-level field. Confluent Schema Registry does recurse for Avro and Protobuf; a top-level-only check will pass a change that breaks a nested consumer.

Failure modes and detection

  • Avro: IncompatibleSchemaException at deserialization when a nested field is added without a default; schema parse error when the parent default is stale. Detect in CI by registering the new schema against the old one in BACKWARD mode.
  • Protobuf: wire-type mismatch on a nested retype; the parser skips the field or throws. Detect with a golden old-binary fixture decoded by the new code.
  • Parquet without field IDs: rename returns null for the renamed column. Silent, not an error. Detect by comparing non-null counts per leaf path before and after.
  • Iceberg: rename is safe for ID-based readers but breaks name-based queries. Detect by running the top N queries that reference the old path.

What I'd do

Add nested fields with defaults, update parent defaults, and never rename or retype a nested leaf in place unless the format tracks identity by ID and every consumer resolves by ID. Otherwise add a new leaf, dual-write, and deprecate the old path.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Change a field from milliseconds to seconds.

Answer

What I'd say first

Assumptions: the field is a duration, say a request timeout, written by one producer service and read by several consumers (an API, a billing job, a dashboard) that deploy on their own schedules, with a schema registry in front of the topic. If instead producer and consumer ship in the same binary and nothing is persisted, the calculus changes; I come back to that at the end.

I would not reinterpret the existing field. I'd add a new field whose name carries the unit, dual-write both for a support window, migrate readers, then delete the old one.

Why not just change the value

Nothing on the wire encodes a unit. {"timeout": 30} is 30 ms or 30 s depending on who wrote it, and Avro, Protobuf and JSON Schema all type it as an integer either way. So a registry compatibility check passes while the meaning changes underneath every reader. That's the trap: BACKWARD compatibility is a statement about schema shape, not about semantics.

The change, concretely

Avro:

JSON
// v1
{"name": "timeout", "type": "long"}                 // milliseconds
// v2
{"name": "timeout_ms",      "type": "long"},        // kept, deprecated
{"name": "timeout_seconds", "type": "long", "default": 0}

Adding a field with a default is backward compatible. Renaming timeout to timeout_ms without an alias is not: readers still asking for timeout get the default. Keep the old name until the window closes.

Protobuf:

Protobuf
int64 timeout_ms      = 3 [deprecated = true];
int64 timeout_seconds = 7;   // new tag; never reuse 3

Rounding and event time

30,000 ms → 30 s is clean. 1,500 ms is not: floor gives 1 s, round-half-up gives 2 s. Pick per field. For a timeout, floor: you never want to wait longer than intended. For a billing duration, flooring loses up to 999 ms per event; at 10M events/day that's up to 2,775 hours of billable duration gone per day, ~1,388 hours at the average 500 ms. Round-half-up, or keep ms internally and convert only at the edge.

If the field is a window boundary or a join key, the conversion changes cardinality. Two streams joined on window_start_ms and window_start_s simply don't match; a 1 s bucket has 1000× fewer keys than a 1 ms bucket. Convert both sides in the same release, or join on the ms field until both are migrated.

Failure modes and how you catch them

  • Double conversion: a reader that takes timeout_seconds and multiplies by 1000 again sets a 30,000 s timeout. Detect with a parity assertion, timeout_seconds * 1000 == timeout_ms within rounding tolerance, run on boundary values 0, 1, 999, 1000, 1500, 2^31-1.
  • Billing 1000×: the job reads the new field but the rate table is still per-ms. Detect with a daily revenue reconciliation against a control total; a 1000× jump is not subtle.
  • Dashboard silently off: it reads the old field and shows 30000 where the operator expects 30. Detect by putting the unit in the axis label and running a canary panel that plots both fields.
  • Registry green, values wrong: the compatibility check passes because the shape is fine. It is not evidence about units. Only the parity check is.

Alternatives

approachwins whencost
new field + dual writedefault; independent deploy schedulestwo fields to maintain during the window
in-place reinterpret, big-bangone deployable, no persisted dataany missed reader is silently 1000× wrong
read-time conversion shimproducer can't change, few readersshim becomes permanent; every new reader must know
new contract version (v2 topic)breaking change beyond unitsduplicate topic, migrate every consumer

The cheap option wins exactly when producer and consumer ship together and nothing is persisted, then a coordinated deploy is fine and the only risk is the overlap window. Otherwise dual-write.

Closing the window

Dual-write from one authority: the producer computes ms and derives seconds by integer division, so the two can't drift. Publish both, migrate readers, watch per-field read counts, and delete the old field only after a full window (90 days or two release cycles, whichever is longer) with zero reads. Backfill history with provenance so a later reader knows which unit each row was written in.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Change a decimal field's precision or scale.

Answer

First, clarify direction and engine. Widening (more precision or scale) and narrowing are different operations with different costs. I'll assume PostgreSQL 15, a 50M-row payments table with amount numeric(10,2), and the business needs numeric(14,4) to store interest to four decimal places.

In PostgreSQL, widening a numeric typmod is a catalog-only change. ALTER TABLE payments ALTER COLUMN amount TYPE numeric(14,4) updates pg_attribute.atttypmod and does not rewrite the table, because the stored values already fit the wider constraint. It still takes an ACCESS EXCLUSIVE lock briefly and invalidates cached plans, so run it in a low-traffic window, but it is seconds, not hours. The same is true of increasing a varchar length.

Narrowing is a data migration. numeric(10,2) allows at most 8 integer digits and 2 decimal digits. A value like 123456789.12 overflows; PostgreSQL raises ERROR: numeric field overflow and aborts the ALTER. A value like 1.235 rounds to 1.24 (PostgreSQL rounds half away from zero). Because the coercion runs on every row, you must audit first:

SQL
-- PostgreSQL 15: find rows that will overflow or round
SELECT count(*) FILTER (WHERE abs(amount) >= 100000000) AS overflow,
       count(*) FILTER (WHERE amount <> round(amount, 2)) AS rounds
FROM payments;

If either count is non-zero, decide the policy before touching the schema: reject the migration, or convert with an explicit USING clause and accept the rounding. Never let the default cast silently truncate.

Storage: numeric is stored as 2 bytes per group of 4 decimal digits plus 3-8 bytes overhead, and the declared precision is a maximum, not a fixed allocation. Widening the typmod does not change the bytes stored per row, because the values are unchanged. So the storage argument for or against a change is usually a red herring; the real cost is the rewrite on narrowing and the lock on either.

When not to change the schema: if you only need more decimals for display, format in the application. If you need exact decimal arithmetic and fixed scale, store integer minor units (cents) in a bigint instead of numeric.

Failure modes and detection:

FailureSymptomDetection
Overflow on narrowingALTER aborts, no rows changedERROR: numeric field overflow in the migration log
Silent roundingAggregates drift after cutoverSUM(amount) before vs after must match exactly
Lock contentionWrites block during the ALTERpg_locks shows ACCESS EXCLUSIVE waiters
Replication lagRead replicas fall behindpg_stat_replication; pause if lag exceeds 1s

Trace, PostgreSQL 15, amount numeric(14,4):

  • Row 123456789.1234: widening to numeric(16,4) is catalog-only, value unchanged. Narrowing to numeric(10,2) has 9 integer digits, so it raises numeric field overflow and the whole ALTER rolls back.
  • Row 1.2345: narrowing to numeric(10,2) rounds to 1.23 (third decimal is 4, round down). Row 1.235 rounds to 1.24 (third decimal is 5, round half away from zero). Both are silent data changes.

So: widen freely with a single ALTER; narrow only after an audit, an explicit rounding policy, and a checksum that proves the aggregates survived.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Migrate a database column to a new type.

Answer

What I'd say first

The decision that matters is whether the type change is binary-coercible or forces a table rewrite. In Postgres, varchar(50) -> varchar(200) and varchar -> text are metadata-only: ALTER TABLE takes ACCESS EXCLUSIVE for milliseconds and touches no rows. int4 -> int8, text -> varchar(n), and numeric precision changes are not coercible, so Postgres rewrites every row and rebuilds every index under one ACCESS EXCLUSIVE lock. On a 2 TB table that is hours of blocked reads and writes, not seconds.

So: small table, coercible change, or a real maintenance window -> in-place ALTER. Large table under write load with no downtime budget -> new column, backfill, cut over.

changerewrite?lock held
varchar(50) -> varchar(200)noACCESS EXCLUSIVE, ms
varchar -> textnoACCESS EXCLUSIVE, ms
text -> varchar(200)yesACCESS EXCLUSIVE, full scan
int4 -> int8yesACCESS EXCLUSIVE, full scan
numeric(10,2) -> numeric(12,2)yesACCESS EXCLUSIVE, full scan

Why the rewrite is the whole problem

A non-coercible ALTER COLUMN ... TYPE runs a full table rewrite while holding ACCESS EXCLUSIVE, blocking all reads and writes. If you don't set lock_timeout, the ALTER queues behind any long-running query and then blocks every query behind it: a 3-second ALTER can stall the app for minutes. Always SET lock_timeout = '3s' before DDL and retry on failure.

Arithmetic (hypothetical): 2 TB at ~150 MB/s rewrite throughput is ~3.7 hours, plus index rebuilds. That number decides the approach.

The new-column path

  1. ALTER TABLE accounts ADD COLUMN balance_big bigint;: metadata-only since PG 11 when the default is non-volatile. No rewrite.
  2. Backfill in bounded batches, one transaction each, so no long transaction holds back vacuum or bloats replication.
SQL
-- Postgres 16. One transaction per batch; COMMIT inside a procedure (PG 11+).
CREATE OR REPLACE PROCEDURE backfill_balance_big(batch_size int DEFAULT 10000)
LANGUAGE plpgsql AS $$
DECLARE
  last_id bigint := 0;
  n int;
BEGIN
  LOOP
    WITH batch AS (
      SELECT id FROM accounts
      WHERE id > last_id AND balance_big IS NULL
      ORDER BY id
      LIMIT batch_size
      FOR UPDATE SKIP LOCKED
    ), upd AS (
      UPDATE accounts a SET balance_big = a.balance::bigint
      FROM batch WHERE a.id = batch.id
      RETURNING a.id
    )
    SELECT count(*), max(id) INTO n, last_id FROM upd;

    EXIT WHEN n = 0;
    COMMIT;
    PERFORM pg_sleep(0.05);
  END LOOP;
END $$;
  1. Add the constraint without a long lock: ADD CONSTRAINT ... CHECK (balance_big IS NOT NULL) NOT VALID (brief lock), then VALIDATE CONSTRAINT (SHARE UPDATE EXCLUSIVE, scans without blocking writes).
  2. Dual-write or derive the new column from a trigger, then compare continuously.
  3. Cut readers over, stop old writes, drop the old column after the support window.

Failure modes and how I'd catch them

  • Skipped rows: FOR UPDATE SKIP LOCKED plus an advancing cursor means a row locked by a concurrent writer is passed over and never revisited. Detect with SELECT count(*) FROM accounts WHERE balance_big IS NULL AND balance IS NOT NULL;: must be 0 before cutover.
  • Replication lag: each batch is a transaction; if lag climbs, back off. Watch pg_stat_replication.replay_lag and pause the loop above ~5s.
  • Lock queue: the ALTER or VALIDATE waiting behind a long transaction. lock_timeout turns a stall into a retryable error.
  • Silent truncation on the reverse path: writing a bigint back into int4 errors or truncates above 2,147,483,647. Keep the old column until the support window closes.

Trade-offs

In-place is correct when the table is small, the change is coercible, or you have a window: it's one statement and no dual-write complexity. New-column costs a second column's storage, a backfill, and dual-write code, and buys a migration that never blocks writes and is trivially reversible: drop the new column and you're back.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Enable a Delta table feature safely.

Answer

I'd treat this as a protocol upgrade, not a table property toggle. Assume a production Delta table on Databricks or open-source Delta Lake, read by multiple engines: Spark, a legacy Hive connector, and a nightly job. The core answer: inventory every reader and writer, upgrade them to the minimum protocol version the feature requires, test on a clone, then enable and monitor. The one-way nature of protocol upgrades and the risk of silent wrong results are what make it unsafe if you skip steps.

Delta protocol versions are monotonic. The transaction log records minReaderVersion and minWriterVersion in the deltaProtocol action. Table features each require specific versions. Deletion vectors require reader version 3 and writer version 7. Liquid clustering requires reader version 3 and writer version 7. Column mapping requires reader version 2 and writer version 2. TimestampNtz requires reader version 3 and writer version 7. Enabling a feature raises the table's protocol. Older clients that only support reader version 1 or 2 throw ProtocolVersionUnsupportedException on read. That's the loud failure. The dangerous case is a reader that doesn't check the feature list and reads the data files anyway: for deletion vectors, it returns deleted rows as present. That's a silent correctness bug.

Concrete example. Table events is read by Spark 3.4 with Delta Lake 2.4 and a legacy Hive connector. You enable deletion vectors:

SQL
ALTER TABLE events SET TBLPROPERTIES ('delta.enableDeletionVectors' = 'true');

DESCRIBE DETAIL events now shows minReaderVersion 3, minWriterVersion 7. The Hive connector fails with a protocol error. If it didn't fail, it would return deleted rows. So you must upgrade or block it.

Test on a clone first:

SQL
CREATE TABLE events_clone SHALLOW CLONE events;

Run the feature on the clone, then run every reader and writer against it. Check for protocol errors and row count mismatches. Test downgrade: try to read with an old client and confirm it fails loudly, not silently.

When not to enable: if you can't upgrade all readers, or if you share the table with external systems that only support older protocol versions, don't enable. Alternatives: use a separate table for the new feature, use a materialized view, or migrate to a new table. Enabling a feature on a new table and migrating data avoids the in-place protocol upgrade.

Failure modes and detection. Protocol error at read time: detect ProtocolVersionUnsupportedException in job logs. Silent wrong results: compare row counts or checksums between old and new readers. Rollback failure: you can't unset the property if the log already contains new actions; you must restore from a backup or rewrite the table. Operational cost: a job that was working now fails, breaking downstream dashboards.

Record the feature and minimum client versions in the catalog and runbooks. Preserve a recovery copy before enabling. Monitor for protocol errors and row count mismatches after enabling.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Evolve an Iceberg table schema.

Answer

What I'd say first. Before touching anything I'd ask two things: what exactly is the change, and which engines read this table. Iceberg schema evolution is metadata-only for add, drop, rename, reorder and a small set of type promotions: no data files are rewritten, so it commits in milliseconds and is safe under concurrent reads. Anything outside that set is a rewrite, which is a different operation with a different cost. I'll assume format v2, a table that already has field IDs, and a reader fleet of Spark, Trino and Flink.

Why it's safe: field IDs, not names or positions. Every column gets a field ID when it's created, drawn from the table's last-column-id counter. Parquet, ORC and Avro footers store that ID, not the column name or its ordinal. So:

  • Rename: change the name in the schema; the ID is untouched; old files still resolve. Metadata-only. In Spark: ALTER TABLE t RENAME COLUMN a TO b.
  • Reorder: readers project by ID, so schema order is cosmetic. Metadata-only.
  • Add: a fresh ID from the counter. Old files have no value for it, so they read as null in v2, or the column's initial-default in v3. In Spark: ALTER TABLE t ADD COLUMN c bigint.
  • Drop: the ID leaves the current schema but is never reused. The bytes stay in old files until compaction rewrites them.

Type promotion: the only changes that don't rewrite data:

fromto
intlong
floatdouble
decimal(P,S)decimal(P2,S), P2 > P

Everything else (long→int, string→int, changing a decimal's scale, a struct field's type) is not a promotion and requires rewriting the data files.

The trap. Never emulate a rename as drop + add. Drop+add mints a new field ID, so the old files' values no longer map to the new column: you get nulls where the data was, and the old bytes are orphaned. Re-adding a dropped column has the same problem: it gets a fresh ID, not the old one.

Partition spec interaction. If the column is a partition source, you must evolve the partition spec to remove the field before dropping the column; Iceberg rejects dropping a column still referenced by the spec.

Failure modes and how I'd detect them.

  1. A v1 reader on a v2 table with delete files. v2 introduced position and equality delete files; a v1 reader ignores them and returns deleted rows. Detect by running the old client against a table that has deletes and comparing row counts. Fix: don't downgrade the format version, and keep v1 readers off v2 tables.
  2. An engine that doesn't implement a promotion. A reader version that predates the promotion may fail or silently misread the column. Detect by reading the promoted column with each engine version in the fleet and checking the returned type.
  3. Drop + re-add name collision. Detect by comparing the field IDs in the schema before and after; if the ID changed, the data association is gone.
  4. Metadata growth. Each schema change appends to the schemas list in metadata.json; write.metadata.previous-versions-max (default 100) bounds how many metadata files are retained.

Trade-offs. If the change is a promotion, do it in place. If it's a demotion or a scale change, either rewrite the files (expensive but correct) or add a new column and backfill. Dropping a column doesn't reclaim space: you only get it back when rewrite_data_files rewrites the files, so the decision is when to run it: after consumers stop reading the old column, and after the snapshot retention window (history.expire.max-snapshot-age-ms, default 5 days) so time-travel still works. Bumping the format version is one-way for readers: plan the client upgrade first.

Commit. Schema changes go through the catalog's atomic commit under optimistic concurrency; a concurrent writer causes a retry, not a lost update.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Evolve partitioning without changing logical schema.

Answer

Assume an Iceberg-style table format: that's the case where this is a metadata operation rather than a migration. The short answer: partition evolution changes the transform that maps rows to files, and because that transform lives in table metadata and is recorded per file, the table's columns and every query against them are untouched.

Why it works. Table metadata holds a list of partition specs plus a default-spec-id. Every data file's manifest entry records the spec_id it was written under. A reader resolves each file against its own spec, so files written under spec 0 and spec 1 sit in the same snapshot and the same scan. Partition columns are hidden: days(event_ts) and bucket(16, user_id) are transforms over existing columns, not columns you add. SELECT * returns the same columns before and after: that is the "logical schema unchanged" guarantee.

SQL
-- Spark 3.5 + Iceberg 1.5
ALTER TABLE prod.db.events ADD PARTITION FIELD days(event_ts);
-- a new spec id is created; new writes use it, existing files keep spec 0
SELECT count(*) FROM prod.db.events.files WHERE spec_id = 0;  -- old files

The catch. Evolution does not rewrite data. A query WHERE event_ts >= '2024-06-01' prunes new files through the days transform, but old files carry no day partition value: they are pruned only by file-level column stats (min/max on event_ts in the manifest). Pruning is weaker for old data, not absent. If the old files are large and unpartitioned, you scan them.

The fix is to rewrite to the current spec:

SQL
CALL prod.system.rewrite_data_files(table => 'db.events');

New files land under the current spec. The cost is a full read and write of the affected data: for a 10 TB table that is hours and real money, so schedule it rather than assuming it is free.

Alternatives.

approachrewrite neededlogical schema changesupport
Iceberg partition evolutionno, lazy (pruning degrades until rewritten)noneSpark, Flink, Trino
Delta liquid clustering (3.x)no; OPTIMIZE reclusters incrementallynoneDelta 3.x
Hive-style repartitionyes, full copyyes: partition column is realany engine

Delta's ALTER TABLE t CLUSTER BY (event_ts) changes clustering keys without a rewrite, but the mechanism differs: there is no per-file spec, layout is decided at OPTIMIZE time. Hive-style partitioning is the thing to avoid: dt is a real column, so changing it changes the schema and every query.

Failure modes.

  • Pruning silently degrades. Latency jumps after evolution because old files are not pruned. Detect by comparing bytes-scanned per query and the files/partitions metadata tables before and after.
  • Concurrent writers split across specs. A writer that cached the old spec keeps writing old-spec files. Iceberg tolerates this, each file records its spec, but check the spec_id distribution in files to confirm writers picked up the new default.
  • Rollback. Snapshots reference specs. Iceberg retains specs a live snapshot still points at, but do not hand-edit metadata; drop a spec only after the snapshots referencing it expire.
  • Compaction under a new spec. rewrite_data_files changes file layout; verify row counts and snapshot lineage afterward.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Migrate a schema-registry subject naming strategy.

Answer

The subject naming strategy is a client-side setting. value.subject.name.strategy on the serializer decides which subject string a producer registers under; the registry itself only stores subjects and issues globally unique, monotonically increasing schema IDs. The Confluent wire format is a magic byte 0x00 followed by a 4-byte big-endian schema ID: no subject name travels with the message. That is the whole reason this migration is survivable: a consumer that deserializes by ID keeps working after the producer changes strategy, because ID lookup is subject-independent. What breaks is registration, ACLs, and any consumer that resolves schemas by subject name.

Assumptions: Confluent Schema Registry, Confluent serializers, today's default TopicNameStrategy, target RecordNameStrategy. If you're on TopicRecordNameStrategy the same reasoning holds with a different subject string.

The three strategies

StrategySubject for record com.acme.Order on topic ordersWins when
TopicNameStrategy (default)orders-valueOne record type per topic; topic is the unit of ownership
RecordNameStrategycom.acme.OrderSame record reused across topics; schema evolves once
TopicRecordNameStrategyorders-com.acme.OrderSame record on many topics but you want per-topic evolution

Worked trace: migrating orders from TopicNameStrategy to RecordNameStrategy:

  1. Before: producer registers com.acme.Order v1 under orders-value → schema ID 41.
  2. Migration tool registers the identical schema under com.acme.Order → ID 42. IDs are global and monotonic; the registry does not dedupe a schema across subjects, so 41 and 42 are distinct IDs for identical bytes.
  3. Producer flips value.subject.name.strategy to RecordNameStrategy and restarts. Next send resolves subject com.acme.Order, finds 42, writes 00 00 00 00 2A.
  4. An old consumer still on TopicNameStrategy reads ID 42, fetches schema 42 by ID, deserializes fine.
  5. A new consumer on RecordNameStrategy resolves com.acme.Order → 42. Same bytes, same schema.

So the cutover is safe for ID-based consumers. The failure surface is elsewhere.

Failure modes and how you see them

  • Subject-scoped lookups. A consumer with use.latest.version=true, or tooling calling getLatestSchemaMetadata(subject), now resolves a different subject and may get a different version. Symptom: SerializationException or a silently missing field. Detect by diffing the resolved schema ID against the producer's before flipping.
  • ACLs. Schema Registry ACLs are per-subject (SUBJECT resource). orders-value ACLs do not cover com.acme.Order; the producer's first registration returns 403. Detect: 403s in registry logs, RestClientException on the producer.
  • Compatibility. If the new subject inherits a stricter global level (default is BACKWARD), the first auto-registration can 409. Set the new subject's compatibility explicitly before the flip, or pre-register with auto.register.schemas=false.
  • Cache cold start. The serializer caches by schema, so the first message per schema after the flip pays a registry round trip; if the registry is unreachable the send fails. Detect: a latency blip on first produce, registry request-rate spike.

Order of operations: pre-register under the new subject, set compatibility and ACLs, flip producers per topic, keep old subjects registered until the last old consumer is gone, then delete. Roll back by flipping the strategy back: the old subject and ID are still there.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Evolve a JSON Schema API contract.

Answer

Assumptions. OpenAPI 3.1, so the dialect is JSON Schema 2020-12. Clients are generated Java models (Jackson) and TypeScript, and a subset validate responses. On OpenAPI 3.0.x the dialect is a draft-04 subset: unevaluatedProperties doesn't exist there, and nullable replaces type: ["string","null"].

Core answer. Make every change additive and optional first, deploy readers that tolerate the new shape, then tighten to required only after telemetry shows no old writer is still sending. A field never becomes required in the same release that introduces it.

Mechanism: why "add a required field" breaks. Requiredness is enforced on the writer's side of the direction it lives in. A required field in a request schema means the server rejects any request missing it: old clients that don't send it get 400s. A new field in a response schema means old clients that reject unknown fields throw: Jackson's FAIL_ON_UNKNOWN_PROPERTIES is enabled by default, so a generated model deserializing a response with an extra property fails unless the client set @JsonIgnoreProperties(ignoreUnknown = true). That asymmetry is why request and response changes are sequenced separately.

Mechanism: open vs closed. additionalProperties: false only sees properties and patternProperties in the same schema object. Under allOf composition it rejects fields the subschemas legitimately define:

JSON
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "properties": { "id": { "type": "string" } },
  "allOf": [ { "properties": { "amount": { "type": "integer" } } } ],
  "additionalProperties": false
}

{"id":"a","amount":5} fails: amount isn't in the top-level properties, so additionalProperties rejects it. Swap the last line for "unevaluatedProperties": false and it passes: unevaluatedProperties collects annotations from all in-place applicators (allOf, $ref, if/then/else) and only rejects what nothing evaluated. Put unevaluatedProperties at the composition root; additionalProperties inside a subschema is a footgun.

Sequencing trace.

stepschemaserverold clientnew client
1currency optional, default: "USD"treats missing as USDworksworks
2unchangedunchangedworkssends currency
3currency requiredrejects missing400 if still deployedworks

Ship step 3 only when request telemetry shows 100% of traffic carries currency for a full deploy window.

Trade-offs. Tolerant reading is wrong where the field is security- or money-bearing. If currency decides which ledger an amount posts to, defaulting a missing value silently misroutes funds: there you make it required immediately and version the endpoint (/v2) instead of defaulting. Same for auth scopes and classification labels: never infer a default.

Failure modes. (1) Validators disagree: ajv in strict mode and a Java validator can differ on format and on unevaluatedProperties support; pin the dialect and test both. (2) Generated models drift from the schema because the generator ignores a keyword it doesn't implement: review the generated diff, not just the spec. (3) Removing a field: deprecate, keep it optional in the schema, watch for zero reads, then delete.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

How do you handle schema drift, an unplanned schema change detected from a source system mid-pipeline, as opposed to a planned schema evolution?

Answer

Core (first 90 seconds). Drift is a writer that changed shape without registering, so the registry's compatibility mode never saw it: the guarantee you rely on for planned changes is void here. Detection therefore has to be a runtime check at the ingestion boundary: canonicalize the observed schema, fingerprint it, compare against the fingerprints registered for that subject. Unknown fingerprint = drift. Then decide per batch: absorb if every deployed reader schema can resolve the observed writer schema, otherwise quarantine the raw payload with its fingerprint and keep the pipeline moving.

Detection. Avro: Parsing Canonical Form strips docs, aliases and defaults, so two schemas differing only in documentation hash the same; compare fingerprint64(PCF(observed)) against the subject's registered set. Protobuf: hash the FileDescriptorProto; unknown field numbers are the drift signal at decode time. JSON Schema: canonicalize key order and compare. For files, compare the Parquet footer schema or the Iceberg/Delta table schema against the catalog's expected schema before the write commits.

Absorb or quarantine. Absorb only if the resolution check passes for every reader you have deployed. Avro's rules are concrete: a writer field absent from the reader is skipped using the writer's type metadata; a reader field absent from the writer needs a default in the reader schema or resolution fails; promotions are limited to int→long, float→double, string↔bytes. So a new writer field is absorbed for free; a removed field is not, unless your reader declares a default.

DriftResolution outcomeAction
field added by writerreader skips itabsorb, register observed schema first
field removed by writerreader needs defaultquarantine if no default
int → longallowed promotionabsorb
long → intnot promotablequarantine
enum symbol addedreader needs default symbolquarantine if none
timestamp ms → µsno schema signal at allquarantine; semantic check

Quarantine. Write raw bytes + observed fingerprint + failing reader to a dead-letter table partitioned by fingerprint; emit a counter; alert on first sight of a new fingerprint, not on every record. Replay after a human registers the schema or ships a reader update. Sizing: 0.3% drift on 40M events/day is 120k records/day; at ~2 KB each that is ~240 MB/day, so 30 days of retention is ~7 GB. Keep it all.

Interaction with compatibility. The trap is absorbing silently. If the drifted shape lands in the lake without being registered, downstream readers that resolve against the registry cannot read it and you have broken BACKWARD/FULL for everyone else. Absorb means register the observed schema as a new version first, then write. Check direction too: a change that is backward-compatible for your reader may be forward-incompatible for a consumer still on the old schema.

Failure modes. Silent null projection: Iceberg/Parquet add a column and old files read NULL, so a SUM quietly drops; watch null-rate per column. Unit changes with no schema signal (ms→µs) corrupt values while the schema diff is empty; that needs a semantic check on ranges. An added enum symbol hitting a downstream switch default branch. All three pass a naive schema-diff check.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Decide when to create a new schema version or new resource.

Answer

The 90-second answer

Ask one question: does the meaning of a record change, or only its shape? Shape changes (add a field, widen a type, deprecate a column) are a new schema version on the same subject. Meaning changes (the grain, the identity, the authorization boundary, the delivery guarantee) are a new resource, because no compatibility mode makes a consumer that joined on order_id correct when the stream is now one row per order line.

Assume a Confluent Schema Registry with Avro, default compatibility BACKWARD, subject per topic (<topic>-value). Under BACKWARD, the new schema reads data written by the old one, so you deploy consumers first, then producers. FORWARD inverts that: producers first. FULL lets you deploy in any order at the cost of a narrower set of allowed changes. Get the direction wrong and consumers throw deserialization errors within one produce cycle: the 5-byte wire header (magic byte 0 plus a 4-byte schema ID) points at a schema the reader can't resolve.

Why grain forces a new resource

Take orders as one Avro record per order keyed on order_id. A consumer computes daily revenue with SELECT sum(amount) GROUP BY order_id. Now the business wants line items. Keep the same subject and emit one record per line, and order_id is no longer unique: the sum counts each line, inflating revenue by the average lines per order. 3.4x if the average order has 3.4 lines. Nothing in the registry flags this. The schema is still BACKWARD-compatible, field types are unchanged, the pipeline runs green, and the number is wrong. That is the case for a new resource (order_lines), a new key, and a deprecation window on the old one.

What each format actually lets you do

ChangeAvroProtobufJSON Schema
Add optional fieldOK (needs default)OK (new tag)OK
Remove fieldBreaks BACKWARD unless it had a defaultOK if tag reservedOK
Rename fieldBreaks unless aliasesN/A (tags, not names)OK
Change typeBreaksOK within the varint family (int32/int64/bool)Breaks if validation tightens
Change grain or keyNever compatibleNever compatibleNever compatible

Protobuf's rule that bites: never reuse a tag number. Delete a field and reserved 7; it, or a future field reusing tag 7 silently mis-decodes old data as the new type.

Identity and authorization shifts

If user_id moves from account ID to device ID, every dedup key and join fans out. Detection: a consumer's distinct-key count jumps while event volume is flat. Authorization is the same class of change, if a field moves from public to PII, a new resource with its own ACL is cheaper than retrofitting field-level policy onto a topic every team already reads.

When the safe default is wrong

Defaulting to a new resource every time is expensive: two pipelines, two on-call surfaces, a reconciliation job. If the change is additive and BACKWARD-compatible, version in place. If you genuinely need both shapes live through a long migration, a new resource beats a version because you can run them side by side and diff them.

Failure modes

  • Dual authority: both old and new resources accept writes. Detection: a nightly row-count diff; drift shows as a growing delta. Cost: reconciliation plus a manual backfill.
  • Bypassing checks: registering a new subject with compatibility NONE to push a breaking change. Detection: the registry audit log shows NONE where topic policy is BACKWARD. Cost: silent consumer breakage.
  • Stuck migration: the predecessor never retires because one consumer never moved. Detection: per-consumer offset lag on the old topic. Cost: permanent double storage and two code paths.

Retire on a date, not on "when everyone's ready."

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Handle old stored records after several schema versions.

Answer

Assumptions first. I'll take the common case: events serialized with Avro and written to Kafka through a schema registry, then landed as Parquet or Iceberg files in a lake. If your records are Protobuf or JSON with a self-describing envelope, the mechanism shifts but the shape of the answer doesn't.

The core answer. Avro binary carries no field names and no types: it's a positional encoding. What makes an old record decodable is the writer schema, and the pointer you rely on is the schema ID in the record header plus the registry entry it names. So the retention question isn't "do we keep the data", it's "do we keep the registry history for as long as the bytes exist". Confluent's wire format is one magic byte 0x00, a 4-byte big-endian schema ID, then the Avro payload. Delete that registry version and the payload is a byte blob.

Why old bytes fail, concretely. Resolution is name-based. The reader walks its own fields and, for each, looks for a writer field with the same name or one listed in the reader field's aliases. Writer-only fields are skipped; reader-only fields take the reader's default, and without one you get AvroTypeException: ... missing required field <name>. Enums resolve by symbol, falling back to the enum's default (Avro 1.9+) and erroring without one. Promotions are limited to int→long→float→double and string↔bytes.

Worked trace. v1 wrote {"userId": 42, "event": "click"}. On the wire that's 54 0A 63 6C 69 63 6B (zigzag varint 42, then length 5, then the bytes) behind a header naming schema ID 1. The current reader is v3, which renamed userId to accountId with "aliases": ["userId"] and added country with "default": "ZZ". Reading the v1 record: accountId matches the writer's userId through the alias → 42; event matches by name → "click"; country has no writer field → default "ZZ". Result: {"accountId": 42, "event": "click", "country": "ZZ"}. Now drop the default from country and the same read throws AvroTypeException: that's the failure you're testing for.

The transitive gap. Registry compatibility defaults to BACKWARD, which only checks a new schema against the immediately previous version. v3 can be backward-compatible with v2 and still unreadable against v1. If you retain 24 months of raw events and the oldest schema in that window is v1, BACKWARD doesn't cover you: set BACKWARD_TRANSITIVE or FULL_TRANSITIVE on the subject, and add a replay test that decodes the oldest retained partition with the current consumer build. That test, not the compatibility setting, is what proves the horizon.

Alternatives and when they're better. Protobuf puts field numbers on the wire and preserves unknown fields, so a reader that predates a field keeps it; the hazard is reusing a number or changing a field's wire type. Parquet and Iceberg are self-describing, the schema lives in the file footer or the table metadata, so old files decode without a registry, and Iceberg's field IDs make renames safe where Avro's name matching does not. The catch is logical types: legacy INT96 timestamps and millis-vs-micros are read differently by different engines, so pin the reader's interpretation, not just the schema.

Compaction. Rewriting old records to the current schema is fine if you validate row counts and checksums, write to a new location, swap atomically, and keep the source until the new one is verified. What you must not do is hard-delete registry versions (DELETE /subjects/{subject}?permanent=true) while bytes referencing them remain.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Find consumers before a breaking schema change.

Answer

Clarify first. "Breaking" is directional. A change that is safe for new readers can break old ones. So before anything: which schema, which registry, what compatibility level is committed, and what is the longest gap between two runs of the most dormant consumer you already know about.

Assumptions I would state: the schema is registered (Avro, Protobuf or JSON Schema in Confluent Schema Registry or Apicurio), consumers are a mix of Kafka consumer groups, batch SQL, BI extracts and file exports, and you cannot ask every owner.

The answer: no single source is sufficient. Run the registry compatibility check as a gate, then gather traffic evidence over a window longer than the longest dormant cycle, then sweep with static search and owner confirmation. Treat absence of traffic as unknown, not as proof.

Why each source finds what the others miss:

SourceFindsBlind spot
Schema Registry compatibility checkSchema-level breaks for registered subjectsOnly the configured direction; raw-byte readers
Kafka consumer groups (--describe)Live and recently-lagging groupsGroups idle past offsets.retention.minutes vanish
Query logs (Snowflake ACCESS_HISTORY, 365 days)SQL readers, including BIDynamic SQL, exports, retention window
Lineage/catalog (DataHub, OpenLineage)Downstream tables, dbt modelsUnregistered pipelines
Code search (GitHub, generated clients)Compile-time readersConfig-driven readers, dynamic SQL
Owner outreachHuman knowledge, dormant jobsSlow, and decays as people leave

The trap that catches most teams: Confluent Schema Registry's default compatibility level is BACKWARD. New consumers can read data written with the previous schema. It says nothing about old consumers reading new data; that is FORWARD. Drop a field and BACKWARD passes, while every deployed consumer still expecting it breaks at deserialization. If you need both directions, set FULL or FULL_TRANSITIVE, and remember the check only covers registered subjects: a service reading raw bytes off the topic is invisible to it.

Retention arithmetic decides your window. A quarterly finance report runs every 90 days. A 30-day query-log window never sees it. Kafka consumer groups with no active members lose their committed offsets after offsets.retention.minutes, default 10080 (7 days), and then disappear from kafka-consumer-groups.sh --list, so "no group listed" is not "no consumer." Snowflake's ACCOUNT_USAGE.ACCESS_HISTORY keeps 365 days; that is the floor for anything with an annual DR test, not the ceiling.

Trade-offs. The registry check is cheap, runs in CI, and catches schema-level breaks, but only in the configured direction and only for registered subjects. Traffic evidence is authoritative but bounded by retention. Static search (GitHub code search, generated-client directories, dbt manifest.json exposures) is fast and shallow: it misses dynamic SQL and config-driven readers. Owner outreach is the only thing that finds the job nobody instrumented, and it is slow and decays as people leave. Use registry plus traffic as the gate; static plus owners as the sweep.

Failure modes to name: registry pass read as safety; observation window shorter than the dormant cycle; expired consumer-group offsets; column names built by string concatenation; BI extracts and CSV exports to shared drives; and "no traffic" read as "no consumer." Keep a rollback path for the ones you cannot rule out.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Design dual-write during a schema migration.

Answer

Core answer (first 60–120 seconds)

Dual-write means the application writes both the old and the new representation for the length of the migration window. The rule that decides whether it survives contact with production: never issue two independent writes from application code. Pick one authoritative write and derive the second inside the same atomic boundary, or make the second write idempotent and replayable from a durable log.

Assumptions I'd state up front: Postgres 15 is the source of truth, a Kafka consumer builds the new representation, no XA/distributed transaction is available, the window is weeks not hours, and both representations must stay readable the whole time.

Mechanism

If both representations live in the same database, one transaction covers both: Postgres commits or rolls back every statement together, so a crash between the two writes leaves neither applied. If the second representation is a different system (search index, another service), atomicity across the boundary is impossible. Use a transactional outbox: write the row and an outbox event in one local transaction, let a relay publish, and have the consumer apply idempotently keyed on event_id.

Python
# Postgres 15, psycopg 3
with conn.transaction():                      # one COMMIT for all three
    cur.execute("UPDATE accounts SET balance = balance - %s WHERE id = %s", (amt, acct))
    cur.execute("""INSERT INTO accounts_v2 (id, balance, version)
                   VALUES (%s, %s, %s)
                   ON CONFLICT (id) DO UPDATE
                     SET balance = EXCLUDED.balance, version = EXCLUDED.version""",
                (acct, new_balance, version))
    cur.execute("INSERT INTO outbox (event_id, aggregate_id, payload) VALUES (%s, %s, %s)",
                (event_id, acct, json.dumps({"balance": new_balance, "version": version})))

Trace: the process dies after the UPDATE but before COMMIT. Postgres rolls back all three, no divergence. COMMIT succeeds but the relay hasn't published yet: the outbox row is durable and the relay picks it up on restart. The consumer redelivers an event: INSERT ... ON CONFLICT (event_id) DO NOTHING makes it a no-op.

Failure modes and how you catch them

failurehow it happensdetection signalcost
partial writetwo separate commits, second failsanti-join count of old rows with no new row > 0rows diverge until repaired
duplicate applyack lost, consumer redeliversunique violation on event_id, or new count > source countdouble-applied side effects
out-of-ordertwo updates, consumer processes v2 then v1new.version < old.versionstale value served
backfill clobberbackfill writes a stale snapshot over a live writeversion regression inside the backfill windowsilent data loss

Reconciliation is the detector for all four. A full anti-join over 50M rows takes tens of seconds; scoping it to updated_at > last_watermark keeps it sub-second, so run it every minute rather than nightly. (Figures illustrative.)

Trade-offs, when dual-write is the wrong tool

If the new representation is a pure function of the old, backfill-and-switch (expand/contract: build the new table, backfill, rename, cut over) is simpler and has no dual-write window at all. If the second store is a search index or cache, CDC, Debezium reading the Postgres WAL, avoids touching application code entirely. Dual-write earns its complexity only when both representations must be written by the app and neither is derivable from the other.

Cutover

Stop old writes when consumer lag on the new path is zero and reconciliation has been clean for N cycles (say 7 days). Keep the old table read-only for a retention window (say 30 days) before dropping it, so rollback is a config flip rather than a restore.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Design CI checks for schema evolution.

Answer

Core answer

Pin down three things first, because they change the design: which format and registry, what compatibility level is actually enforced today, and how long the data lives. If it's Kafka with Confluent Schema Registry, the default level is BACKWARD, and that default is the most common reason a schema change passes CI and still breaks production.

The check I'd build: before merge, hand the proposed schema to the registry and ask whether it's compatible with every version a consumer could still be pinned to. Not "does it parse." The registry already ships the compatibility engine; reimplementing it in CI is how you get drift between what CI believes and what the registry enforces.

What the levels actually guarantee

BACKWARD means a consumer on the new schema can read data written with the previous one. FORWARD is the mirror: a consumer on the previous schema can read data written with the new one. FULL is both. The _TRANSITIVE variants compare against all registered versions, not just the last.

That distinction is the whole ballgame. Register v1, v2, v3. If v3 is backward-compatible with v2 but not v1, plain BACKWARD passes. A Flink job still pinned to v1, not redeployed in eight months, now throws on every record. BACKWARD_TRANSITIVE catches it. The cost is O(versions) comparisons and a permanent ban on breaking changes for that subject, which is the point.

LevelGuaranteesBreaks when
BACKWARDnew reader reads old dataa consumer is pinned to an older schema
FORWARDold reader reads new dataa producer hasn't been upgraded
FULLboth directions, last version onlya consumer is two versions back
FULL_TRANSITIVEboth directions, all versionsnever, until you need a breaking change

A trace that shows why this matters

Protobuf, user.proto. v1 declares int32 user_id = 1;. v2 deletes field 1 and adds int32 account_id = 1;.

The wire format is identical: field 1, varint, same type. A consumer still on v1 decodes account_id's value as user_id. No exception, no dead-letter queue, no alert. Wrong joins in the warehouse three weeks later. buf breaking --against '.git#branch=main' fails this with FIELD_NO_DELETE; the fix is reserved 1; plus a fresh number.

Avro fails the other way. Rename user_id to userId with no alias and the reader's field has no match in the writer's schema; with no default, Avro's resolver throws AvroTypeException naming the missing field. Loud, but only at read time, in whichever consumer hits it first.

Trade-offs

FULL_TRANSITIVE is the right default for a topic with many independent teams. It's also the one that blocks legitimate changes, so you need a designed escape hatch rather than a CI bypass. Two options: a new subject (orders-v2) with a dual-write window, or an explicit exception carrying an owner and an expiry date. The migration window floor is your retention period, if Kafka keeps 7 days, the dual-write runs at least 7 days before you can drop the old schema, or you strand replay jobs.

Failure modes worth naming

  • The producer deploys before the registry check finishes, because registration and the CI gate are separate steps. Make registration itself the gate.
  • A consumer pinned to an old schema version that nobody redeployed. Detect it by auditing consumer group offsets against registered versions, not by hoping.
  • Someone with admin rights flips the subject to NONE. Assert the compatibility level in CI, don't just read it.

Wiring it up

Confluent: the kafka-schema-registry-maven-plugin test-local-compatibility goal, or POST /compatibility/subjects/<subject>/versions/latest?verbose=true against a staging registry. Protobuf: buf breaking. Also compile the generated clients for every language you ship: a schema can be wire-compatible and still fail codegen, say when a new field name collides with a reserved word in Java or Python. Iceberg is the one format where renames are free, because column IDs rather than names are the identity; there the check is whether anyone dropped or reused a column ID.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Test schema evolution before production.

Answer

The 90-second answer

Pin three things before testing: the format, the registry's compatibility level, and the real reader set. "Test schema evolution" means something different when the only consumer is a nightly batch job versus a fleet of long-lived services plus a Flink job plus an Iceberg table.

Assuming Avro on Confluent Schema Registry at the default BACKWARD level, the test is a compatibility matrix, every retained writer schema crossed with every reader schema, run first through the registry's checker, then through a real end-to-end path. The registry check is necessary and cheap; it is not sufficient, because it validates structural resolution, not meaning.

writer ↓ / reader →v1v2
v1baselineBACKWARD: new reader must read old data
v2FORWARD: old reader must read new databaseline

Run the diagonal too: a schema that cannot read its own output is a bug the off-diagonal hides.

Why it breaks

Avro resolves by field name against the writer schema embedded in the payload. Reader fields absent from the writer take their default; writer fields absent from the reader are dropped. So adding a field with a default is backward compatible, and because Avro ignores unknown fields it is also forward compatible: added fields roll back cleanly.

Trace it. Writer v1: {id: long, status: enum[ACTIVE, CLOSED]}. Reader v2 adds region: string = "unknown" and the enum symbol PENDING with default ACTIVE. Reading v1's {id: 7, status: CLOSED} with v2: region is missing in the writer, so the reader default "unknown" applies; status matches by name and stays CLOSED. Now reverse it: v2 writes status: PENDING, v1 has no PENDING symbol and no enum default, and resolution throws AvroTypeException. That asymmetry (added fields safe, new enum symbols and widened unions not) is exactly what the matrix catches and a schema diff does not.

Protobuf breaks differently: field numbers are the identity, so adding a field with a fresh number is safe both ways, but reusing a retired number or changing a wire-incompatible type corrupts silently. Reserve numbers and names on removal.

Trade-offs and where to spend

The registry check runs in milliseconds on every schema commit and catches structural breaks. The runtime matrix costs N×M fixture combinations to maintain but catches what the registry cannot see: semantic drift (a field that changed units from cents to dollars), intermediaries, and non-registry consumers. Deciding criterion: if the level is BACKWARD_TRANSITIVE and every consumer is a registry client, the registry check plus a smoke test is enough. The moment a Flink job, a Kafka Connect sink, or a table format reads the topic, that path needs its own matrix row: Flink with a fixed schema drops unknown fields, and Iceberg tracks renames by column ID, not name, so a rename that is fine in Avro is a new column there.

Failure modes and how you catch them

  • Dual-write divergence: during migration you write old and new topics; a consumer reading both sees duplicates. Detect with a reconciliation job comparing per-key counts and checksums over a window; the cost is a stalled cutover and manual dedup.
  • Rollback after new writes: fine for added fields, broken for new enum symbols or type changes. Replay the retained fixtures against the old binary to prove it before you need it.
  • Registry outage: Confluent clients cache schemas by ID, so a warm producer survives and a cold one with an empty cache cannot serialize. Kill the registry in staging and watch producer startup.
  • Unsupported cells: every matrix cell that fails needs a named owner and a decision (fix, pin the reader, or accept the break) otherwise the matrix rots.

Reconcile business outputs, not just structure: a schema-valid record with the wrong unit passes every check above.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Recover from an incompatible schema published to production.

Answer

Core answer (first 90 seconds)

I'd start by confirming the stack: Kafka with Confluent Schema Registry, Avro, and the subject's compatibility level. Assume the level was NONE, or the change was registered under a new subject, so an incompatible schema got through. A producer removed a required field, and consumers are throwing Avro deserialization errors. My first move is to freeze writes, stop the producer or route it to a quarantine topic, then answer three questions: has any message been written with the bad schema, which consumer groups are affected, and can I roll back the registry without breaking readers of the new data?

If no message has been written with the new schema, roll back the registry to the previous version and restart consumers. That's a five-minute fix. If messages exist, rollback alone is wrong: old consumers will fail on those messages. Then I choose between a tolerant reader and forward repair.

Mechanism: why compatibility modes matter

Schema Registry checks compatibility at registration time. BACKWARD (the default) means a new schema can read data written with the previous schema, so you upgrade consumers first. FORWARD means the previous schema can read data written with the new schema: upgrade producers first. FULL is both. NONE skips the check. An incompatible schema gets in when the level is NONE, when someone registers under a different subject, or when a client bypasses the registry.

Avro resolution uses the writer's schema and the reader's schema. If the reader has a field with a default that the writer didn't write, it's filled. If the writer wrote a field the reader doesn't have, it's ignored. If the reader expects a field with no default and the writer didn't write it, it throws. So a tolerant reader is a reader schema that has defaults for every field that might be missing and ignores extras. Protobuf is more forgiving: unknown fields are preserved and missing fields get type defaults, so added or removed fields are safe as long as field numbers aren't reused. JSON Schema needs additionalProperties: true and defaults.

A tolerant reader for the removed currency field looks like this:

JSON
{
  "type": "record",
  "name": "Order",
  "fields": [
    {"name": "id", "type": "string"},
    {"name": "amount", "type": "double"},
    {"name": "currency", "type": "string", "default": "USD"}
  ]
}

Old messages have currency; new messages don't, and the reader fills "USD".

Decision table

SituationActionCost
No messages written with bad schemaRoll back registry, restart consumersMinutes
Messages exist, a reader schema with defaults covers bothDeploy tolerant readerMinutes to hours
Messages exist, no compatible reader schemaForward repair: translate on read or reprocess to a new topicHours

Worked arithmetic

Topic has 4.2M messages, 3 consumer groups. Replay at 50k msg/s = 84s per group, 252s total. Reprocessing through a Flink job at 10k/s = 420s = 7 minutes, plus the cost of switching consumers to the new topic. A tolerant reader is minutes. That's why you prefer it when the schema allows.

Failure modes

  • Rolling back the registry while new-schema messages exist: old consumers crash on those messages. Detect via consumer error rate and DLQ depth.
  • Tolerant reader without defaults for all missing fields: still throws. Test with a sample of both old and new messages.
  • Confluent's Java client caches schemas in memory; a registry rollback isn't seen by a running consumer until it restarts. Restart or clear the cache.
  • Reprocessing without idempotence: duplicates. Use a new topic and switch consumers atomically.

Prevention

Set compatibility to BACKWARD_TRANSITIVE or FULL_TRANSITIVE. Run the registry's compatibility check in CI (e.g., the Confluent Maven plugin's test-compatibility goal) before merge. Restrict who can change the compatibility level with ACLs. Canary a new schema to one consumer group before rolling out.

Curated: · Written: · Reviewed:

Difficulty: Hard