Sub topic 11
Deduplicating and joining streams
This chapter assumes you know PySpark joins and have read the chapters on watermarks, windows, and state. Deduplication and stream joins are both stateful. Spark must remember past rows to compare them with new ones. Without a watermark, that state grows forever.
Deduplicating a stream
Sources such as Kafka can deliver the same event more than once. Use dropDuplicates to keep the first row seen for each key.
events = spark.readStream.table("main.demo.orders_bronze")
deduped = (
events.withWatermark("event_time", "10 minutes")
.dropDuplicatesWithinWatermark(["order_id"])
)
(
deduped.writeStream
.option("checkpointLocation", "/Volumes/main/demo/chk/orders_dedup")
.toTable("main.demo.orders_silver")
)dropDuplicatesWithinWatermark stores each key only until the watermark passes it. Duplicates must arrive within the watermark delay of the first copy. A later duplicate is treated as a new row.
The older dropDuplicates(["order_id", "event_time"]) also works with a watermark. It requires the event time to be identical in every copy, because event time is part of the key. Without a watermark, dropDuplicates keeps every key forever.
Joining a stream with a static table
A stream-static join looks up each streaming row in a regular Delta table. It is stateless. Spark reads the latest version of the static table for each micro-batch.
customers = spark.read.table("main.demo.customers")
enriched = events.join(customers, "customer_id", "left")Inner and left outer joins work with the stream on the left side.
Joining two streams
A stream-stream join must buffer rows from both sides, because a matching row may arrive later. Add a watermark to each input and a time condition in the join. Together they tell Spark when a buffered row can no longer match.
from pyspark.sql import functions as F
orders = (
spark.readStream.table("main.demo.orders_bronze")
.withWatermark("order_time", "10 minutes")
.alias("o")
)
payments = (
spark.readStream.table("main.demo.payments_bronze")
.withWatermark("payment_time", "15 minutes")
.alias("p")
)
joined = orders.join(
payments,
F.expr("""
o.order_id = p.order_id AND
p.payment_time BETWEEN o.order_time AND o.order_time + INTERVAL 1 HOUR
"""),
"inner",
)Here a payment must occur within one hour after its order. Spark drops buffered orders once no later payment can fall in that range.
Common errors
| Problem | Cause | Fix |
|---|---|---|
| State grows until the cluster runs out of memory | No watermark, or no time bound in the join | Add watermarks and a time-range condition |
| Outer join results are delayed | Spark emits unmatched rows only after the watermark passes | Expect latency equal to the watermark plus the time range |
| Duplicates still appear in the sink | Duplicate arrives after the watermark delay | Increase the delay, or deduplicate again with a `MERGE` |
| Error about unsupported join | Outer join without watermark and time condition | Add both |
Exercise
You deduplicate orders on order_id with dropDuplicatesWithinWatermark and a 10-minute watermark. A duplicate arrives 30 minutes after the original. What happens, and how can you still prevent the duplicate in the Delta table?
Show answer
Spark has already dropped the key from state, so it treats the copy as a new row and writes it. To prevent it, write with foreachBatch and a MERGE INTO that matches on order_id and only inserts when no match exists. That makes the write idempotent regardless of arrival time.
Exercise
Why does a stream-stream inner join need both watermarks and a time-range condition to keep state bounded?
Show answer
The watermarks say how late each stream's data can be. The time-range condition says how far apart matching rows can be. Together they let Spark decide that a buffered row can no longer match anything and remove it from state.