Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Lab · 25 min · revision 2

Lab: Schema Evolution and Replaying a Topic

Run a Confluent-compatible schema registry, watch BACKWARD compatibility reject a breaking Avro change and accept a safe one, see why consumers upgrade before producers, then fix a bug in the lab 4 job, find that the old checkpoint cannot be reused, replay the topic into a new table, compare and swap.

Contentsand lesson path

What you will learn

  • Evolve event schemas under registry compatibility rules and replay a topic to recompute results after a bug fix.

Prerequisites: Messaging & Event Streaming

01. Goal and setup

Events outlive the code that writes them. Producers add fields, consumers are deployed on their own schedule, and a topic holds records written with several versions of a schema at once. A schema registry stores every version of a schema under a name, called a subject, and checks each new version against a compatibility rule before producers may use it. In the first half of this lab you register an Avro schema, try a breaking and a safe change, and see in which order producers and consumers must upgrade.

In the second half you fix a bug in the page-view job from lab 4 and recompute the past, the kappa way from lesson 1: replay the topic with the fixed job into a new table, compare, and switch readers over.

You need the stream-lab/ folder at the end of lab 4, with the stream-kafka container still running. The registry is Confluent Schema Registry 8.4.1 from the Confluent Community tarball, which runs on the same Java 17 or 21 as Spark and stores its schemas in a Kafka topic, _schemas. The tarball is 441 MB and Schema Registry is under the Confluent Community License. With Docker Compose you would use the image confluentinc/cp-schema-registry:8.4.1 instead; this lab was not tested with it.

02. Step 1: Start the schema registry

schema.compatibility.level=backward is the registry's default, written out here so that you can see it. BACKWARD means that a consumer using the new schema can read data written with the previous one.

Properties · stream-lab/registry.properties
listeners=http://127.0.0.1:38081
kafkastore.bootstrap.servers=PLAINTEXT://127.0.0.1:39092
kafkastore.topic=_schemas
schema.compatibility.level=backward
Terminal
curl -O https://packages.confluent.io/archive/8.4/confluent-community-8.4.1.tar.gz
tar xzf confluent-community-8.4.1.tar.gz
export LOG_DIR=$PWD/registry-logs
confluent-8.4.1/bin/schema-registry-start registry.properties > registry.out 2>&1 &
echo $! > registry.pid
until curl -s 127.0.0.1:38081/config; do sleep 2; done; echo
Expected output
{"compatibilityLevel":"BACKWARD"}

03. Step 2: Register version 1 and test two changes

schemas.py defines four versions of a page-click record. v2-bad adds a required field referrer; v2 adds it as optional, a union of null and string, with the default null; v3 also removes user_agent. registry_check.py calls the registry's REST API. With the default TopicNameStrategy, the value schemas of topic page-clicks live under the subject page-clicks-value.

Python · stream-lab/schemas.py
"""Four versions of the page-click Avro schema."""
import json

BASE = [
    {"name": "event_id", "type": "string"},
    {"name": "user_id", "type": "string"},
    {"name": "page_id", "type": "string"},
    {"name": "event_time", "type": {"type": "long", "logicalType": "timestamp-millis"}},
]
AGENT = {"name": "user_agent", "type": "string"}
REFERRER_REQUIRED = {"name": "referrer", "type": "string"}
REFERRER_OPTIONAL = {"name": "referrer", "type": ["null", "string"], "default": None}


def record(fields):
    return json.dumps({"type": "record", "name": "PageClick",
                       "namespace": "lab.clicks", "fields": fields})


SCHEMAS = {
    "v1": record(BASE + [AGENT]),
    "v2-bad": record(BASE + [AGENT, REFERRER_REQUIRED]),   # new field, no default
    "v2": record(BASE + [AGENT, REFERRER_OPTIONAL]),       # new field with a default
    "v3": record(BASE + [REFERRER_OPTIONAL]),              # user_agent removed
}
Python · stream-lab/registry_check.py
"""Ask the schema registry whether each schema version may follow the latest one."""
import json
import sys
import textwrap
import urllib.error
import urllib.request

from schemas import SCHEMAS

REGISTRY = "http://127.0.0.1:38081"
SUBJECT = "page-clicks-value"      # TopicNameStrategy: <topic>-value


def call(method, path, body=None):
    request = urllib.request.Request(
        REGISTRY + path,
        method=method,
        data=json.dumps(body).encode() if body is not None else None,
        headers={"Content-Type": "application/vnd.schemaregistry.v1+json"},
    )
    try:
        with urllib.request.urlopen(request) as response:
            return json.load(response)
    except urllib.error.HTTPError as error:
        return json.load(error)


command, versions = sys.argv[1], sys.argv[2:]
for version in versions:
    if command == "register":
        result = call("POST", f"/subjects/{SUBJECT}/versions",
                      {"schema": SCHEMAS[version]})
        print(f"register {version}: schema id {result['id']},"
              f" subject version {result['version']}")
    elif command == "check":
        path = f"/compatibility/subjects/{SUBJECT}/versions/latest?verbose=true"
        result = call("POST", path, {"schema": SCHEMAS[version]})
        print(f"{version} compatible: {result['is_compatible']}")
        for message in result.get("messages", [])[:1]:     # the first reason
            print(textwrap.fill(message, 86, initial_indent="  ",
                                subsequent_indent="  "))
    elif command == "level":
        result = call("PUT", f"/config/{SUBJECT}", {"compatibility": version})
        print("subject level:", result["compatibility"])
Terminal
docker exec stream-kafka /opt/kafka/bin/kafka-topics.sh \
  --bootstrap-server localhost:9092 --create --topic page-clicks --partitions 1
python registry_check.py register v1
python registry_check.py check v2-bad v2
Expected output
Created topic page-clicks.
register v1: schema id 1, subject version 1
v2-bad compatible: False
  {errorType:"READER_FIELD_MISSING_DEFAULT_VALUE", description:"The field 'referrer'
  at path '/fields/5' in the new schema has no default value and is missing in the old
  schema", additionalInfo:"referrer"}
v2 compatible: True

The registry rejects v2-bad. A new consumer reading an old record finds no referrer in it, and the Avro rules of schema resolution say that a field missing from the writer's data takes the reader's default, or is an error if there is none. v2 passes because its default fills the gap. Note that BACKWARD checks only against the latest version; BACKWARD_TRANSITIVE checks against all of them.

04. Step 3: Produce and consume with each version

avro_clients.py produces two clicks with one schema version, or reads every record of the topic with another version as the reader schema. The serializer registers its schema if needed and starts each message with a version byte 0 and the 4-byte schema id; the deserializer fetches the writer's schema by that id and resolves it against the reader schema.

Python · stream-lab/avro_clients.py
"""Produce page clicks with one schema version, or read them all with another."""
import datetime as dt
import sys
import textwrap

from confluent_kafka import Consumer, Producer, TopicPartition
from confluent_kafka.schema_registry import SchemaRegistryClient
from confluent_kafka.schema_registry.avro import AvroDeserializer, AvroSerializer
from confluent_kafka.serialization import MessageField, SerializationContext

from schemas import SCHEMAS

TOPIC, BROKER = "page-clicks", "127.0.0.1:39092"
registry = SchemaRegistryClient({"url": "http://127.0.0.1:38081"})
action, version = sys.argv[1], sys.argv[2]
context = SerializationContext(TOPIC, MessageField.VALUE)

if action == "produce":
    serialize = AvroSerializer(registry, SCHEMAS[version])   # registers if needed
    producer = Producer({"bootstrap.servers": BROKER})
    for n in (1, 2):
        click = {"event_id": f"{version}-{n}", "user_id": "u01", "page_id": "p3",
                 "event_time": dt.datetime(2026, 11, 2, 11, n, tzinfo=dt.UTC),
                 "user_agent": "Firefox/140", "referrer": "newsletter"}
        try:
            value = serialize(click, context)
        except Exception as error:                 # the registry said no
            text = str(error)
            reason = f"{version}: not produced: {text.split(', details')[0]}"
            print(textwrap.fill(reason, 86, subsequent_indent="  "))
            print("  " + text[text.rfind("(HTTP"):])
            break
        producer.produce(TOPIC, value=value)
        print(f"{version}: produced {click['event_id']} with schema id"
              f" {int.from_bytes(value[1:5], 'big')}")
    producer.flush(10)

elif action == "consume":                           # read every record with one schema
    deserialize = AvroDeserializer(registry, SCHEMAS[version])   # the reader schema
    consumer = Consumer({"bootstrap.servers": BROKER, "group.id": f"reader-{version}"})
    _low, high = consumer.get_watermark_offsets(TopicPartition(TOPIC, 0))
    consumer.assign([TopicPartition(TOPIC, 0, 0)])
    print(f"reader {version}:")
    for _ in range(high):
        message = consumer.poll(10)
        writer_id = int.from_bytes(message.value()[1:5], "big")
        try:
            click = deserialize(message.value(), context)
            agent, referrer = click.get("user_agent"), click.get("referrer")
            print(f"  offset {message.offset()} (writer id {writer_id}): ok,"
                  f" user_agent={agent}, referrer={referrer}")
        except Exception as error:
            print(f"  offset {message.offset()} (writer id {writer_id}): FAILED")
            print(f"    {error}")
    consumer.close()
Terminal
python avro_clients.py produce v1
python avro_clients.py produce v2-bad
python registry_check.py register v2
python avro_clients.py produce v2
python avro_clients.py consume v1
Expected output
v1: produced v1-1 with schema id 1
v1: produced v1-2 with schema id 1
v2-bad: not produced: Schema being registered is incompatible with an earlier schema
  for subject "page-clicks-value"
  (HTTP status code 409, SR code 40901)
register v2: schema id 2, subject version 2
v2: produced v2-1 with schema id 2
v2: produced v2-2 with schema id 2
reader v1:
  offset 0 (writer id 1): ok, user_agent=Firefox/140, referrer=None
  offset 1 (writer id 1): ok, user_agent=Firefox/140, referrer=None
  offset 2 (writer id 2): ok, user_agent=Firefox/140, referrer=None
  offset 3 (writer id 2): ok, user_agent=Firefox/140, referrer=None

The producer with v2-bad fails before sending anything: the registry answered HTTP 409, so broken data never reached the topic. The old v1 consumer reads the new v2 records too, because Avro ignores a writer field that the reader does not know. Adding an optional field with a default is therefore both backward and forward compatible, called FULL, and the upgrade order does not matter.

05. Step 4: Remove a field and find the upgrade order

v3 removes user_agent, a field without a default. Check it under BACKWARD and under FORWARD, which means that old consumers can read data written with the new schema; then produce with v3 and read with both versions.

Terminal
python registry_check.py check v3
python registry_check.py level FORWARD
python registry_check.py check v3
python registry_check.py level BACKWARD
Expected output
v3 compatible: True
subject level: FORWARD
v3 compatible: False
  {errorType:"READER_FIELD_MISSING_DEFAULT_VALUE", description:"The field 'user_agent'
  at path '/fields/4' in the old schema has no default value and is missing in the new
  schema", additionalInfo:"user_agent"}
subject level: BACKWARD
Terminal
python avro_clients.py produce v3
python avro_clients.py consume v2
python avro_clients.py consume v3
Expected output
v3: produced v3-1 with schema id 3
v3: produced v3-2 with schema id 3
reader v2:
  offset 0 (writer id 1): ok, user_agent=Firefox/140, referrer=None
  offset 1 (writer id 1): ok, user_agent=Firefox/140, referrer=None
  offset 2 (writer id 2): ok, user_agent=Firefox/140, referrer=newsletter
  offset 3 (writer id 2): ok, user_agent=Firefox/140, referrer=newsletter
  offset 4 (writer id 3): FAILED
    No default value for field user_agent in lab.clicks.PageClick
  offset 5 (writer id 3): FAILED
    No default value for field user_agent in lab.clicks.PageClick
reader v3:
  offset 0 (writer id 1): ok, user_agent=None, referrer=None
  offset 1 (writer id 1): ok, user_agent=None, referrer=None
  offset 2 (writer id 2): ok, user_agent=None, referrer=newsletter
  offset 3 (writer id 2): ok, user_agent=None, referrer=newsletter
  offset 4 (writer id 3): ok, user_agent=None, referrer=newsletter
  offset 5 (writer id 3): ok, user_agent=None, referrer=newsletter

BACKWARD accepts v3, FORWARD does not, and the consumers show why. The v3 reader handles all six records, ignoring user_agent where it exists. The v2 reader fails on the v3 records, because they lack a field it requires. Under BACKWARD, therefore, upgrade every consumer first and the producers last. Under FORWARD the order is reversed, and old data must be gone before consumers switch; under FULL either order works.

06. Step 5: Fix the job and try the old checkpoint

Now the bug. Lab 4 counted user healthcheck, an uptime monitor, as a visitor. The product team also wants distinct visitors per window. policy_v2.py filters the monitor and adds approx_count_distinct("user_id"); job_v2.py takes the checkpoint and table as arguments and sets startingTimestamp, so that a new query starts reading at 09:00 on 2 November. Produce another half hour of clicks, then try the fixed job on the old checkpoint.

Python · stream-lab/policy_v2.py
"""Version 2 of the policy: health checks are not page views; count visitors too."""
from pyspark.sql import functions as F

EXCLUDED_USERS = ["healthcheck"]          # the uptime monitor, not a person


def count_views_v2(clicks, pages):
    return (
        clicks.where(~F.col("user_id").isin(EXCLUDED_USERS))
        .join(pages, "page_id", "left")
        .groupBy(
            F.window("event_time", "5 minutes"),
            "page_id",
            F.coalesce("category", F.lit("unknown")).alias("category"),
        )
        .agg(
            F.count("*").alias("views"),
            F.approx_count_distinct("user_id").alias("visitors"),
        )
        .select(
            F.col("window.start").alias("window_start"),
            F.col("window.end").alias("window_end"),
            "page_id",
            "category",
            "views",
            "visitors",
        )
    )
Python · stream-lab/job_v2.py
"""Run the fixed page-view job into a given checkpoint and table."""
import datetime as dt
import sys

from policy import on_time, parse
from policy_v2 import count_views_v2
from session import local_session

checkpoint, table = sys.argv[1], sys.argv[2]
replay_from = dt.datetime(2026, 11, 2, 9, 0, tzinfo=dt.UTC)   # first affected record
spark = local_session("page-views-v2", lakehouse=True)
raw = (
    spark.readStream.format("kafka")
    .option("kafka.bootstrap.servers", "127.0.0.1:39092")
    .option("subscribe", "clicks")
    .option("startingTimestamp", str(int(replay_from.timestamp() * 1000)))
    .load()
)
pages = spark.read.format("delta").load("lake/pages")
views = count_views_v2(
    on_time(parse(raw))
    .withWatermark("event_time", "10 minutes")
    .dropDuplicatesWithinWatermark(["event_id"]),
    pages,
)
query = (
    views.writeStream.format("delta")
    .outputMode("append")
    .option("checkpointLocation", checkpoint)
    .trigger(availableNow=True)
    .start(table)
)
query.awaitTermination()
for p in query.recentProgress:
    mark = p["eventTime"].get("watermark", "1970")
    mark = "none yet" if mark < "1971" else mark[11:19]
    print(f"batch {p['batchId']}: {p['numInputRows']} rows in, watermark {mark}")
spark.stop()
Terminal
python produce_clicks.py 3
python job_v2.py chk/page_views lake/page_views > v2-on-old.log 2>&1
echo "exit code $?"
grep -m1 -o "\[STATE_STORE[A-Z_]*\][^.]*\." v2-on-old.log | fold -s -w 80
Expected output (after the producer's two lines)
exit code 1
[STATE_STORE_VALUE_SCHEMA_NOT_COMPATIBLE] Provided value schema does not match 
existing state value schema.

The aggregation's saved state has one value per key, the count; the new query needs a count plus the sketch of distinct users. Spark's guide lists which changes a restart from the same checkpoint allows: adding or removing filters and some projection changes are allowed, while any change to the grouping keys or aggregates of a stateful operator is not. Spark checks the state schema when a batch runs, which is why this lab produced new clicks first; with no new data, the restart would have ended without an error and proved nothing.

Even a change that the checkpoint allows would not repair the past. A filter added to the old query applies only to records it reads from now on, and startingTimestamp or startingOffsets are used only when a query starts without a checkpoint.

07. Step 6: Replay the topic into a new table

Let the old job catch up, so that both versions cover the same data. Then run the fixed job with a fresh checkpoint into a new table. With a new checkpoint Spark starts a new query: it has a new query id, uses startingTimestamp, and rebuilds its state from the replayed records. Replay works only while Kafka still retains every record from the starting point, which is why clicks has unlimited retention.

Terminal
python job.py
python job_v2.py chk/page_views_v2 lake/page_views_v2
Expected output
page_views batch 4: 368 rows in, watermark 09:49:40
page_views batch 5: 0 rows in, watermark 10:19:46
late_clicks batch 2: 368 rows in
batch 0: 1103 rows in, watermark none yet
batch 1: 0 rows in, watermark 10:19:46

08. Step 7: Compare the versions and swap

Compare the two tables before anyone reads the new one. The views that disappeared must be exactly the health-check clicks that the old job counted. Then switch readers with a catalogue view: swap.py registers both tables in a local Hive metastore, kept in metastore_db/, and points the view page_views at one of them.

Python · stream-lab/compare_versions.py
"""Compare the table written by the old job with the replayed one."""
from pyspark.sql import functions as F

from policy import on_time, parse
from session import local_session

spark = local_session("compare", lakehouse=True)
old = spark.read.format("delta").load("lake/page_views")
new = spark.read.format("delta").load("lake/page_views_v2")
for name, table in (("old", old), ("new", new)):
    s = table.agg(F.count("*").alias("rows"), F.sum("views").alias("views"),
                  F.date_format(F.max("window_end"), "HH:mm").alias("last")).first()
    print(f"{name}: {s['rows']} rows, {s['views']} views, windows up to {s['last']}")

# What the fix should remove: on-time, deduplicated health checks in closed windows.
raw = (spark.read.format("kafka").option("kafka.bootstrap.servers", "127.0.0.1:39092")
       .option("subscribe", "clicks").load())
last_end = new.agg(F.max("window_end")).first()[0]
health = (
    on_time(parse(raw)).dropDuplicates(["event_id"])
    .where("user_id = 'healthcheck'")
    .where(F.window("event_time", "5 minutes").end <= F.lit(last_end))
)
print("health-check clicks in those windows:", health.count())
keys = ["window_start", "page_id"]
diff = (
    old.join(new.withColumnRenamed("views", "new_views"), keys, "left")
    .where(F.coalesce("new_views", F.lit(0)) != F.col("views"))
)
print("rows that changed:", diff.count())
(diff.select(F.date_format("window_start", "HH:mm").alias("window"), "page_id",
             "views", "new_views", "visitors")
 .orderBy("window", "page_id").show(4))
spark.stop()
Python · stream-lab/swap.py
"""Point the name that readers use, page_views, at one version of the table."""
import sys
from pathlib import Path

from session import local_session

target = sys.argv[1]                                  # "v1" or "v2"
spark = local_session("swap", lakehouse=True, catalog=True)
for name, folder in (("page_views_v1", "lake/page_views"),
                     ("page_views_v2", "lake/page_views_v2")):
    location = Path(folder).resolve()
    spark.sql(f"CREATE TABLE IF NOT EXISTS {name} USING DELTA LOCATION '{location}'")
spark.sql(f"CREATE OR REPLACE VIEW page_views AS SELECT * FROM page_views_{target}")
row = spark.sql("SELECT count(*) AS n, sum(views) AS views FROM page_views").first()
print(f"page_views -> page_views_{target}: {row['n']} rows, {row['views']} views")
print("columns:", ", ".join(spark.table("page_views").columns))
spark.stop()
Terminal
python compare_versions.py
python swap.py v1
python swap.py v2
Expected output
old: 107 rows, 886 views, windows up to 10:15
new: 107 rows, 847 views, windows up to 10:15
health-check clicks in those windows: 39
rows that changed: 31
+------+-------+-----+---------+--------+
|window|page_id|views|new_views|visitors|
+------+-------+-----+---------+--------+
| 09:00|     p1|   28|       27|      10|
| 09:00|     p4|    5|        4|       4|
| 09:00|     p5|    6|        4|       4|
| 09:05|     p2|   15|       14|       9|
+------+-------+-----+---------+--------+
only showing top 4 rows
page_views -> page_views_v1: 107 rows, 886 views
columns: window_start, window_end, page_id, category, views
page_views -> page_views_v2: 107 rows, 847 views
columns: window_start, window_end, page_id, category, views, visitors

The new table has 39 fewer views, exactly the health-check clicks in the closed windows, and 31 rows changed. Readers who query page_views now see version 2 without changing their code, and they gain the visitors column. Keep the old job and table for a while, so that python swap.py v1 can roll back; then stop the old job and delete chk/page_views and lake/page_views. In production, run the replay on separate compute, so that the live job keeps its latency while the copy catches up.

When you have finished the skill, stop the registry and remove the broker:

Terminal
kill $(cat registry.pid)
docker rm -f -v stream-kafka

09. Check your understanding

Practice check · 3 questions

Schemas and replays

Each question changes one detail of the lab. Pick the best answer.

Q1. The subject `page-clicks-value` uses BACKWARD and holds versions 1, 2 and 3. A new consumer on version 3 must read the whole topic, which still contains version 1 records. What has the registry checked for you?
Q2. You restart a job with a new aggregate on its old checkpoint while no new clicks arrive, and it ends without an error. What does that tell you about the change?
Q3. To recompute after a fix, a colleague adds `startingTimestamp` for 09:00 to the existing job and restarts it with its old checkpoint. What happens?
Practice only: not graded, not saved, not evidence.

10. Apply it

Finish the practice project with a replay runbook:

  1. Add the schema of your click events to the registry with BACKWARD_TRANSITIVE, and change the producer of lab 4 to Avro. Spark's from_avro expects plain Avro bytes, so remove the 5-byte prefix first, or decode with the registry client in foreachBatch.
  2. Write the replay steps for a bug found three days late: the starting timestamp, the retention it needs, the new checkpoint and table, the comparison you require before the swap, and how to roll back.
  3. Decide which late clicks in late_clicks the replayed job should also correct, and how.

11. Review prompt

Without looking back, explain in your own words:

  • what BACKWARD, FORWARD and FULL compatibility promise, and the upgrade order for each;
  • why adding a field without a default breaks BACKWARD, and why removing one breaks FORWARD;
  • which changes to a streaming query can keep their checkpoint, and which cannot;
  • why startingTimestamp needs a fresh checkpoint;
  • the steps of a replay, from the fixed job to the swap and the clean-up.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check