Lab: Kafka to a Lakehouse Table with Structured Streaming
Produce seeded clicks with late, out-of-order and repeated events to Kafka, stream them with Spark into Delta Lake tables for page views and late clicks, kill the job mid-batch and restart it, prove that the Delta sink skips a repeated batch, match the result against a batch oracle and compact the small files.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Start Kafka and create the topic
- Step 2: Check Python, Java and the Spark helper
- Step 3: Produce the first half hour of clicks
- Step 4: Write the job and run it once
- Step 5: Kill the job in the middle of a batch
- Step 6: Restart and let the checkpoint finish the work
- Step 7: Lose a commit and watch the Delta sink skip the batch
- Step 8: Compare with a batch oracle
- Step 9: Compact the small files
- Check your understanding
- Apply it
- Review prompt
Lessons of Stream Processing
- Streams, Tables and Two Kinds of Time Concept · 20 min
- Windows and Watermarks, Event by Event Worked example · 25 min
- State, Checkpoints and Delivery Guarantees Concept · 25 min
- Lab: Kafka to a Lakehouse Table with Structured Streaming Lab · 30 min
- Lab: Schema Evolution and Replaying a Topic Lab · 25 min
- Check: Streaming Correctness Scenarios Knowledge check · 8 questions
What you will learn
- Explain how stream processors keep state and checkpoints, and choose a delivery guarantee for a sink (at-least-once with idempotent writes or exactly-once transactions).
- Implement a streaming job (Spark Structured Streaming or Flink) that reads Kafka, enriches events with a stream-table join and writes to a lakehouse table.
Prerequisites: Messaging & Event Streaming
01. Goal and setup
In this lab you build the core of the skill's practice project. A Spark Structured Streaming job reads clicks from Kafka, enriches each one with its page category from a Delta table (a stream-static join), counts page views in 5-minute event-time windows with a 10-minute watermark, and writes the counts to a Delta Lake table. Clicks that arrive too late go to a second table instead of being lost. Then you test the delivery contract from lesson 3: you kill the job in the middle of a batch, restart it, fake a crash between the sink write and the checkpoint commit, and compare the result with a batch recomputation.
The lab was tested with the apache/kafka:3.7.2 image in KRaft mode, Eclipse Temurin JRE 21, Python 3.12, PySpark 4.2.0, Delta Lake 4.4.1 and confluent-kafka 2.16.1. Kafka 4.x runs only in KRaft mode, as this lab does. One 4.x change matters here because the lab sets record timestamps: message.timestamp.after.max.ms now defaults to 1 hour, so a 4.x broker rejects records stamped more than an hour in the future. Work in stream-lab/ with the virtual environment from lesson 2 active; the first Spark start downloads about 100 MB of jars into stream-lab/.ivy/.
stream-lab/
├── session.py local Spark session (from lesson 2)
├── versions.py step 2: print the package versions
├── produce_clicks.py step 3: seeded clicks to the topic `clicks`
├── make_pages.py step 4: the page dimension as a Delta table
├── policy.py step 4: lateness rule, parsing, enrichment, counting
├── job.py step 4: the streaming job
├── show_tables.py step 4: summary of the output tables
├── inspect_checkpoint.py step 5: offsets, commits and Delta versions
├── oracle.py step 8: batch recomputation and comparison
├── compact.py step 9: OPTIMIZE the page-view table
├── lake/ Delta tables: pages, page_views, late_clicks
└── chk/ one checkpoint folder per streaming query02. Step 1: Start Kafka and create the topic
The broker has two client listeners: localhost:9092 for tools inside the container, and 127.0.0.1:39092 for Spark and the producer on your machine. Clients connect to the address that KAFKA_ADVERTISED_LISTENERS gives them, so it must match the published port.
The topic gets retention.ms=-1. Kafka deletes old log segments by the timestamps of their records, and this lab stamps its records with fixed times on 2 November 2026 so that every run gives the same results. With the default retention of seven days, those records could be deleted soon after you produce them.
MAP=PLAINTEXT:PLAINTEXT,CONTROLLER:PLAINTEXT,HOST:PLAINTEXT
docker run -d --name stream-kafka -p 127.0.0.1:39092:39092 \
-e KAFKA_NODE_ID=1 -e KAFKA_PROCESS_ROLES=broker,controller \
-e KAFKA_LISTENERS=PLAINTEXT://:9092,CONTROLLER://:9093,HOST://:39092 \
-e KAFKA_ADVERTISED_LISTENERS=PLAINTEXT://localhost:9092,HOST://127.0.0.1:39092 \
-e KAFKA_LISTENER_SECURITY_PROTOCOL_MAP=$MAP \
-e KAFKA_CONTROLLER_LISTENER_NAMES=CONTROLLER \
-e KAFKA_CONTROLLER_QUORUM_VOTERS=1@localhost:9093 \
-e KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR=1 \
-e KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR=1 \
-e KAFKA_TRANSACTION_STATE_LOG_MIN_ISR=1 \
apache/kafka:3.7.2
until docker exec stream-kafka /opt/kafka/bin/kafka-topics.sh \
--bootstrap-server localhost:9092 --list > /dev/null 2>&1; do sleep 2; done
docker exec stream-kafka /opt/kafka/bin/kafka-topics.sh \
--bootstrap-server localhost:9092 --create --topic clicks --partitions 3 \
--config retention.ms=-1Created topic clicks.03. Step 2: Check Python, Java and the Spark helper
If you are starting with this lab, create the environment now; otherwise just check the versions. Spark needs Java 17 or 21: check with java -version. The session helper is the one from lesson 2; lakehouse=True adds the Kafka connector and Delta Lake through spark.jars.packages and keeps Ivy's download cache in stream-lab/.ivy/ instead of your home folder.
"""Print the versions this lab was tested with."""
from importlib.metadata import version
import platform
for package in ("pyspark", "delta-spark", "confluent-kafka", "fastavro"):
print(f"{package} {version(package)}")
print("python", ".".join(platform.python_version_tuple()[:2]))python3.12 -m venv .venv && source .venv/bin/activate
pip install "pyspark==4.2.0" "delta-spark==4.4.1" \
"confluent-kafka[avro,schemaregistry]==2.16.1"
python versions.py"""Local Spark sessions for the stream-processing lessons."""
from pathlib import Path
from pyspark.sql import SparkSession
LAB = Path(__file__).resolve().parent
PACKAGES = [
"io.delta:delta-spark_4.2_2.13:4.4.1",
"org.apache.spark:spark-sql-kafka-0-10_2.13:4.2.0",
]
def local_session(app_name, lakehouse=False, catalog=False):
"""Spark in local mode. lakehouse=True loads Kafka and Delta Lake; catalog=True
keeps table and view names in a local Hive metastore (folder metastore_db)."""
builder = (
SparkSession.builder.master("local[2]")
.appName(app_name)
.config("spark.driver.host", "127.0.0.1")
.config("spark.driver.bindAddress", "127.0.0.1")
.config("spark.ui.enabled", "false")
.config("spark.sql.session.timeZone", "UTC")
.config("spark.sql.shuffle.partitions", "4")
.config("spark.local.dir", str(LAB / ".spark-tmp"))
)
if lakehouse:
builder = (
builder.config("spark.jars.packages", ",".join(PACKAGES))
.config("spark.jars.ivy", str(LAB / ".ivy"))
.config("spark.sql.extensions", "io.delta.sql.DeltaSparkSessionExtension")
.config(
"spark.sql.catalog.spark_catalog",
"org.apache.spark.sql.delta.catalog.DeltaCatalog",
)
)
if catalog:
builder = builder.config("spark.sql.warehouse.dir", str(LAB / "warehouse"))
builder = builder.enableHiveSupport()
spark = builder.getOrCreate()
spark.sparkContext.setLogLevel("ERROR")
return sparkpyspark 4.2.0
delta-spark 4.4.1
confluent-kafka 2.16.1
fastavro 1.13.1
python 3.1204. Step 3: Produce the first half hour of clicks
The producer writes 360 clicks for one half hour of arrival time, one every 5 seconds, and sets each Kafka record timestamp to that arrival time. Each click's event time is its arrival time minus a seeded random delay: most delays are under a minute, about 12% are 1 to 8 minutes (out of order), and about 4% are 12 to 40 minutes (late). About 3% of clicks are sent twice, as an app does when it retries after a timeout. User healthcheck is an uptime monitor that requests pages too; lesson 5 deals with it.
"""Produce half an hour of seeded clickstream events to the Kafka topic `clicks`."""
import datetime as dt
import json
import random
import sys
from confluent_kafka import Producer
PAGES = ["p1", "p2", "p3", "p4", "p5", "p6", "p7"] # p7 is missing from `pages`
WEIGHTS = [30, 20, 20, 10, 8, 9, 3]
START = dt.datetime(2026, 11, 2, 9, 0, tzinfo=dt.timezone.utc)
phase = int(sys.argv[1]) # 1: 09:00-09:30, 2: 09:30-10:00
rng = random.Random(40 + phase)
first = START + dt.timedelta(minutes=30 * (phase - 1))
records, kinds = [], {"on time": 0, "out of order": 0, "late": 0, "duplicate": 0}
for i in range(360): # one click every 5 seconds of arrival time
arrived = first + dt.timedelta(seconds=5 * i)
r = rng.random()
if r < 0.04:
delay, kind = rng.randint(12 * 60, 40 * 60), "late" # over 10 minutes
elif r < 0.16:
delay, kind = rng.randint(60, 8 * 60), "out of order" # 1 to 8 minutes
else:
delay, kind = rng.randint(0, 50), "on time"
user = "healthcheck" if rng.random() < 0.05 else f"u{rng.randint(1, 12):02d}"
click = {
"event_id": f"c{phase}{i:04d}",
"user_id": user,
"page_id": rng.choices(PAGES, WEIGHTS)[0],
"event_time": (arrived - dt.timedelta(seconds=delay)).isoformat()[:19] + "Z",
}
kinds[kind] += 1
records.append((arrived, click))
if rng.random() < 0.03: # the app retried: same click, a bit later
records.append((arrived + dt.timedelta(seconds=rng.randint(5, 30)), click))
kinds["duplicate"] += 1
producer = Producer(
{"bootstrap.servers": "127.0.0.1:39092", "enable.idempotence": True}
)
for arrived, click in sorted(records, key=lambda rec: rec[0]): # in arrival order
producer.produce(
"clicks",
key=click["user_id"],
value=json.dumps(click),
timestamp=int(arrived.timestamp() * 1000), # the record timestamp = arrival
)
left = producer.flush(30)
print(f"phase {phase}: produced {len(records)} records, {left} not delivered")
print(", ".join(f"{kind} {n}" for kind, n in kinds.items()))python produce_clicks.py 1phase 1: produced 370 records, 0 not delivered
on time 315, out of order 33, late 12, duplicate 1005. Step 4: Write the job and run it once
policy.py holds the rules that the streaming job and the batch oracle of step 8 share. The lateness rule is declared on the data: a click whose record reached Kafka more than 10 minutes after its event time is late. On-time clicks are counted; late clicks are quarantined to late_clicks for a later batch correction. Because the rule uses only fields of the record, a batch job can apply it exactly, which a watermark alone cannot promise: lesson 2 showed that its drops depend on how events fall into micro-batches.
In job.py, the watermark of 10 minutes matches the rule, so it bounds the state without dropping on-time clicks here: an on-time click is at most 10 minutes behind its own arrival, and earlier batches hold only clicks that arrived before it. dropDuplicatesWithinWatermark removes repeated clicks by event_id; it remembers each id for about the watermark delay, so copies that arrive within that time are removed. The join with pages runs per click, before the aggregation, and Spark reads the static Delta table again for every micro-batch. Each query writes a Delta table in append mode and has its own checkpoint.
"""Write the page dimension as a small Delta table."""
from session import local_session
spark = local_session("make-pages", lakehouse=True)
pages = spark.createDataFrame(
[
("p1", "Home", "landing"),
("p2", "Search results", "browse"),
("p3", "Product page", "browse"),
("p4", "Basket", "purchase"),
("p5", "Checkout", "purchase"),
("p6", "Help centre", "support"),
],
"page_id string, title string, category string",
)
pages.coalesce(1).write.format("delta").mode("overwrite").save("lake/pages")
spark.read.format("delta").load("lake/pages").orderBy("page_id").show()
spark.stop()"""The declared policy, shared by the streaming job and the batch oracle."""
from pyspark.sql import functions as F
SCHEMA = "event_id string, user_id string, page_id string, event_time timestamp"
LATE_AFTER_S = 600 # a click that reaches Kafka over 10 minutes after it happened
def parse(raw):
"""Kafka rows -> clicks, with the record timestamp as the arrival time."""
clicks = raw.select(
F.from_json(F.col("value").cast("string"), SCHEMA).alias("c"),
F.col("timestamp").alias("arrived_at"),
).select("c.*", "arrived_at")
late_by = F.col("arrived_at").cast("long") - F.col("event_time").cast("long")
return clicks.withColumn("late_by_s", late_by)
def on_time(clicks):
return clicks.where(F.col("late_by_s") <= LATE_AFTER_S).drop("late_by_s")
def too_late(clicks):
return clicks.where(F.col("late_by_s") > LATE_AFTER_S)
def count_views(clicks, pages):
"""Enrich with the page dimension and count views per page and 5-minute window."""
return (
clicks.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"))
.select(
F.col("window.start").alias("window_start"),
F.col("window.end").alias("window_end"),
"page_id",
"category",
"views",
)
)"""Stream clicks from Kafka into two Delta tables: page views and late clicks."""
import sys
from session import local_session
from policy import count_views, on_time, parse, too_late
trigger = sys.argv[1] if len(sys.argv) > 1 else "available-now" # or "10 seconds"
spark = local_session("page-views", lakehouse=True)
raw = (
spark.readStream.format("kafka")
.option("kafka.bootstrap.servers", "127.0.0.1:39092")
.option("subscribe", "clicks")
.option("startingOffsets", "earliest") # only used on the very first run
.load()
)
clicks = parse(raw)
pages = spark.read.format("delta").load("lake/pages") # static side of the join
views = count_views(
on_time(clicks)
.withWatermark("event_time", "10 minutes")
.dropDuplicatesWithinWatermark(["event_id"]),
pages,
)
def start(df, name):
writer = (
df.writeStream.format("delta")
.queryName(name)
.outputMode("append")
.option("checkpointLocation", f"chk/{name}")
)
if trigger == "available-now":
writer = writer.trigger(availableNow=True)
else:
writer = writer.trigger(processingTime=trigger)
return writer.start(f"lake/{name}")
queries = [start(views, "page_views"), start(too_late(clicks), "late_clicks")]
for query in queries:
query.awaitTermination()
for query in queries:
for p in query.recentProgress:
line = f"{query.name} batch {p['batchId']}: {p['numInputRows']} rows in"
mark = p["eventTime"].get("watermark") # only page_views has one
if mark:
line += ", watermark " + ("none yet" if mark < "1971" else mark[11:19])
print(line)
spark.stop()"""Summarise the two output tables."""
from pyspark.sql import functions as F
from session import local_session
spark = local_session("show", lakehouse=True)
views = spark.read.format("delta").load("lake/page_views")
late = spark.read.format("delta").load("lake/late_clicks")
summary = views.agg(
F.count("*").alias("rows"),
F.sum("views").alias("views"),
F.date_format(F.max("window_end"), "HH:mm").alias("last_window_end"),
).first()
print(f"page_views: {summary['rows']} rows, {summary['views']} views,"
f" windows up to {summary['last_window_end']}")
print(f"late_clicks: {late.count()} rows")
(
views.where("window_start = '2026-11-02 09:10:00'")
.select(F.date_format("window_start", "HH:mm").alias("window"), "page_id",
"category", "views")
.orderBy("page_id")
.show()
)
spark.stop()python make_pages.py
python job.py
python show_tables.py+-------+--------------+--------+
|page_id| title|category|
+-------+--------------+--------+
| p1| Home| landing|
| p2|Search results| browse|
| p3| Product page| browse|
| p4| Basket|purchase|
| p5| Checkout|purchase|
| p6| Help centre| support|
+-------+--------------+--------+page_views batch 0: 370 rows in, watermark none yet
page_views batch 1: 0 rows in, watermark 09:19:48
late_clicks batch 0: 370 rows inpage_views: 26 rows, 181 views, windows up to 09:15
late_clicks: 13 rows
+------+-------+--------+-----+
|window|page_id|category|views|
+------+-------+--------+-----+
| 09:10| p1| landing| 18|
| 09:10| p2| browse| 12|
| 09:10| p3| browse| 12|
| 09:10| p4|purchase| 6|
| 09:10| p5|purchase| 4|
| 09:10| p6| support| 1|
| 09:10| p7| unknown| 1|
+------+-------+--------+-----+The first run read all 370 records in batch 0. Batch 1 is a no-data batch that moved the watermark to 09:19:48, ten minutes behind the newest click, and emitted every window that ends by then. Later windows are still in state. Page p7 has no row in pages, so the left join gives it the category unknown instead of losing its views. late_clicks holds 13 rows for 12 late clicks, because the quarantine path keeps repeated copies; remove them when you correct.
06. Step 5: Kill the job in the middle of a batch
Produce the second half hour, start the job with a 10-second processing-time trigger in the background, and kill it with kill -9 as soon as batch 2 is planned, which is when offsets/2 appears.
"""Print what the checkpoint and the Delta log of page_views have recorded."""
import datetime as dt
import json
from pathlib import Path
def numbered(folder):
return sorted(int(p.name) for p in folder.iterdir() if p.name.isdigit())
chk = Path("chk/page_views")
planned, committed = numbered(chk / "offsets"), numbered(chk / "commits")
print("planned batches:", planned, "| committed:", committed)
_version, meta, offsets = (chk / "offsets" / str(planned[-1])).read_text().splitlines()
mark = dt.datetime.fromtimestamp(json.loads(meta)["batchWatermarkMs"] / 1000, dt.UTC)
print(f"batch {planned[-1]}: watermark {mark:%H:%M:%S}, Kafka offsets"
f" {json.loads(offsets)['clicks']}")
for log in sorted(Path("lake/page_views/_delta_log").glob("*.json")):
actions = [json.loads(line) for line in log.read_text().splitlines()]
batch = next(a["txn"]["version"] for a in actions if "txn" in a)
files = sum("add" in a for a in actions)
print(f"table version {int(log.stem)}: batch {batch}, {files} files added")python produce_clicks.py 2
python job.py "10 seconds" > run.log 2>&1 &
JOB=$!
until [ -f chk/page_views/offsets/2 ]; do sleep 1; done
kill -9 $JOB
python inspect_checkpoint.pyphase 2: produced 365 records, 0 not delivered
on time 312, out of order 43, late 5, duplicate 5planned batches: [0, 1, 2] | committed: [0, 1]
batch 2: watermark 09:19:48, Kafka offsets {'0': 117, '1': 307, '2': 311}
table version 0: batch 0, 0 files added
table version 1: batch 1, 4 files addedBatch 2 is planned, with its Kafka end offsets in the write-ahead log, but neither committed nor written to the table.
07. Step 6: Restart and let the checkpoint finish the work
Run the job again with the default available-now trigger. It finds offsets/2 without commits/2 and runs batch 2 again with exactly the recorded range, then a no-data batch that emits the windows up to 09:45.
python job.py
python inspect_checkpoint.pypage_views batch 2: 365 rows in, watermark 09:19:48
page_views batch 3: 0 rows in, watermark 09:49:40
late_clicks batch 1: 365 rows in
planned batches: [0, 1, 2, 3] | committed: [0, 1, 2, 3]
batch 3: watermark 09:49:40, Kafka offsets {'0': 117, '1': 307, '2': 311}
table version 0: batch 0, 0 files added
table version 1: batch 1, 4 files added
table version 2: batch 2, 0 files added
table version 3: batch 3, 4 files added08. Step 7: Lose a commit and watch the Delta sink skip the batch
Now fake the worst moment for a crash: after the sink has committed batch 3 but before the checkpoint has. Delete the commit file of batch 3 and its hidden checksum file, and run the job again. Spark must rerun batch 3, and a plain file append would write its windows twice.
rm chk/page_views/commits/3 chk/page_views/commits/.3.crc
python job.py
python inspect_checkpoint.py
python show_tables.py | head -2page_views batch 3: 0 rows in, watermark 09:49:40
late_clicks batch 2: 0 rows in
planned batches: [0, 1, 2, 3] | committed: [0, 1, 2, 3]
batch 3: watermark 09:49:40, Kafka offsets {'0': 117, '1': 307, '2': 311}
table version 0: batch 0, 0 files added
table version 1: batch 1, 4 files added
table version 2: batch 2, 0 files added
table version 3: batch 3, 4 files added
page_views: 66 rows, 540 views, windows up to 09:45
late_clicks: 18 rowsSpark reran batch 3, but the table still has four versions, 66 rows and 540 views. Each commit of the streaming sink records the query id and the batch id. Delta saw that this query had already committed batch 3 and skipped the write; the unchanged table is the evidence, since batch 3 was a no-data batch and its 0 rows prove nothing. This is the idempotent sink half of the exactly-once contract; the replayable Kafka source and the checkpoint are the other halves.
09. Step 8: Compare with a batch oracle
A batch oracle recomputes the expected result from all the data with a plain batch query and the same policy.py. It removes duplicates with dropDuplicates(["event_id"]), which is safe here because the copies are identical. It compares only windows that the stream has closed: those ending by the watermark stored in the last offsets file.
"""Recompute page views in batch from the whole topic and compare with the stream."""
import datetime as dt
import json
from pathlib import Path
from pyspark.sql import functions as F
from policy import count_views, on_time, parse, too_late
from session import local_session
# The stream has only written windows that its watermark has closed.
offsets = Path("chk/page_views/offsets")
last = max(int(p.name) for p in offsets.iterdir() if p.name.isdigit())
meta = json.loads((offsets / str(last)).read_text().splitlines()[1])
mark_ms = meta["batchWatermarkMs"]
mark = dt.datetime.fromtimestamp(mark_ms / 1000, dt.UTC)
spark = local_session("oracle", lakehouse=True)
raw = (
spark.read.format("kafka") # a batch read of every retained record
.option("kafka.bootstrap.servers", "127.0.0.1:39092")
.option("subscribe", "clicks")
.load()
)
clicks = parse(raw)
pages = spark.read.format("delta").load("lake/pages")
expected = count_views(on_time(clicks).dropDuplicates(["event_id"]), pages).where(
F.col("window_end") <= F.timestamp_millis(F.lit(mark_ms))
)
actual = spark.read.format("delta").load("lake/page_views")
late = spark.read.format("delta").load("lake/late_clicks")
print(f"stream watermark {mark:%H:%M:%S}: compare windows that end by then")
print("oracle rows:", expected.count(), "| stream rows:", actual.count())
print("only in oracle:", expected.exceptAll(actual).count())
print("only in stream:", actual.exceptAll(expected).count())
print("late clicks, oracle:", too_late(clicks).count(), "| stream:", late.count())
spark.stop()python oracle.pystream watermark 09:49:40: compare windows that end by then
oracle rows: 66 | stream rows: 66
only in oracle: 0
only in stream: 0
late clicks, oracle: 18 | stream: 18The stream and the oracle agree row for row, and the quarantine holds exactly the clicks that the rule calls late. This depends on the setup: with maxOffsetsPerTrigger, a micro-batch can hold newer records from one partition and older ones from another, so the watermark can pass clicks that the rule accepts and the stream drops them. Run the oracle after every change to the job.
10. Step 9: Compact the small files
Every micro-batch that emits windows writes new files, one per shuffle partition with rows. At one batch a minute, a table collects thousands of small files a day, and every query must open them. OPTIMIZE rewrites them into larger files in a new table version; old files stay for time travel until VACUUM removes them. Run it on a schedule, enable auto compaction with the table property delta.autoOptimize.autoCompact, or trigger less often.
"""Compact the small files that the micro-batches wrote into page_views."""
from delta.tables import DeltaTable
from session import local_session
spark = local_session("compact", lakehouse=True)
table = DeltaTable.forPath(spark, "lake/page_views")
def active_files():
return table.detail().first()["numFiles"]
before = active_files()
metrics = table.optimize().executeCompaction().first()["metrics"]
print(f"files before: {before}, after: {active_files()}")
print(f"removed {metrics['numFilesRemoved']}, added {metrics['numFilesAdded']}")
print("rows still:", spark.read.format("delta").load("lake/page_views").count())
spark.stop()python compact.pyfiles before: 8, after: 1
removed 8, added 1
rows still: 6611. Check your understanding
12. Apply it
Finish the practice project from here:
- Write a batch job that reads
late_clicksonce a day, counts them per window and page with the same rules, and merges the extra views into a corrected table. Decide which windows you will still correct after a week. - Run the oracle with
maxOffsetsPerTriggerset to 50 injob.pyand a fresh checkpoint, and explain any difference you see. - Write down the source, checkpoint and sink contract that makes your claim of exactly-once results true, and what would break it.
13. Review prompt
Without looking back, explain in your own words:
- why the lateness rule is based on the Kafka record timestamp, and what the watermark still does;
- what Spark did after the
kill -9, and which file told it to; - why the Delta table did not get the windows of batch 3 twice;
- what the batch oracle compares, and why it ignores windows after the watermark;
- why streaming writes create small files, and two ways to deal with them.
References
- Apache Spark 4.2.0: Structured Streaming + Kafka Integration Guide
- Apache Spark: Structured Streaming recovery semantics, joins and deduplication
- Delta Lake: Table streaming reads and writes
- Delta Lake: Optimizations (OPTIMIZE and auto compaction)
- Apache Kafka Documentation
- Apache Kafka 4.0: Upgrade notes (KRaft only, KIP-848, timestamp limits)
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.