Stream joins
Joining a stream is like joining two tables, with one twist: rows keep arriving, so a match may show up later. This lesson covers the easy case, adding details from a lookup table to each event, and the hard one, matching two streams, where Spark has to know how long to wait for a partner.
Step 4 · Structured Streaming · Gold · Joins and custom state, lesson 1 of 2
On this page
Read first: Watermarks and late data · join (skip if you know them)
In plain words first
Stream-static: a phone book
Stream-stream: a coat check
Stream-static: enrich each event
stores = spark.read.table("silver.stores") # a static DataFrame enriched = (spark.readStream.table("bronze.sales") .join(stores, "store_id", "left")) # stream on the left
The static side is not snapshotted when the query starts. Each micro-batchmicro-batch: One small round of a stream: Spark takes the data that arrived since the last round, processes it like a little batch job, and saves its progress. Learn more → runs the join again, so a Delta table on the static side is read at its latest version for every batch: an update to a store shows up in the next batch. Nothing is kept in state. Two limits follow: a change to the static side never revises sales that were already joined, and a cache() on the static side freezes it at whatever it held when it was cached.
| Join type | Stream-static | Stream-stream |
|---|---|---|
| Inner | Yes | Yes; watermarks and a time condition bound state |
| Left outer | Yes, with the stream on the left | Yes, needs watermarks and a time condition |
| Right outer | Yes, with the stream on the right | Yes, needs watermarks and a time condition |
| Full outer | No | Yes, needs watermarks and a time condition |
| Left semi | Yes, with the stream on the left | Yes, needs watermarks and a time condition |
Stream-stream: both sides wait for each other
When both inputs are streams, a row that arrives on one side may meet its match on the other side in a later batch. So Spark buffers every row of both sides in state. Without limits that buffer grows forever. Two things together let Spark forget rows: a watermark on each side, and a join condition that bounds how far apart in time matching rows can be.
shows = shows_stream.withWatermark("shown_at", "20 minutes").alias("s") clicks = clicks_stream.withWatermark("clicked_at", "20 minutes").alias("c") joined = shows.join(clicks, F.expr(""" s.ad_id = c.ad_id AND c.clicked_at BETWEEN s.shown_at AND s.shown_at + INTERVAL 10 MINUTES"""))
The promise · from the clicks watermark
The condition · clicks come at most 10 minutes after a show
The result · old shows leave state
Outer joins emit late
In a left outer join, a show without a click must eventually be written with a null click. Spark can only do that once it is sure no click can still match: when the watermark passes the end of the show's match range. So matched rows appear as soon as both sides have arrived, while unmatched rows appear after the range plus the watermark delay. A larger delay means more complete matches and later null rows.
Try it yourself
Each example says what it shows, then the output from a real run and what to notice in it, so you can follow without running anything. To try one yourself, paste it into a local Spark session, with spark already created: each builds its own data.
Goal: Join two streams: ads that were clicked within 10 minutes of being shown.
import json, os from pyspark.sql import functions as F for side in ["shows", "clicks"]: os.makedirs(f"lab/join/{side}", exist_ok=True) def land(side, name, rows): with open(f"lab/join/{side}/{name}.json", "w") as f: rows = [{"ad": a, "ts": f"2026-01-01 {t}"} for a, t in rows] f.write("\n".join(json.dumps(r) for r in rows)) land("shows", "a", [("ad1", "10:00:00"), ("ad2", "10:01:00"), ("ad3", "10:02:00")]) land("clicks", "a", [("ad1", "10:04:00"), ("ad2", "10:30:00")]) # ad2: far too late shows = (spark.readStream.schema("ad STRING, ts TIMESTAMP").json("lab/join/shows") .withWatermark("ts", "20 minutes").alias("s")) clicks = (spark.readStream.schema("ad STRING, ts TIMESTAMP").json("lab/join/clicks") .withWatermark("ts", "20 minutes").alias("c")) joined = shows.join(clicks, F.expr(""" s.ad = c.ad AND c.ts BETWEEN s.ts AND s.ts + INTERVAL 10 MINUTES""")) (joined.select("s.ad", F.date_format("s.ts", "HH:mm").alias("shown"), F.date_format("c.ts", "HH:mm").alias("clicked")) # memory sink: keeps the result in a temp table named "ad_clicks" .writeStream.format("memory").queryName("ad_clicks") .option("checkpointLocation", "lab/join/_chk") .trigger(availableNow=True) .start().awaitTermination()) spark.table("ad_clicks").show()
Output from a real run
+---+-----+-------+ | ad|shown|clicked| +---+-----+-------+ |ad1|10:00| 10:04| +---+-----+-------+
What to notice:
- Only ad1 matched: shown 10:00, clicked 10:04.
- ad2 was clicked 29 minutes after it was shown, outside the 10-minute range. ad3 was never clicked.
- The time range lets Spark forget old shows: once the watermark is past a show's time plus 10 minutes, no click can match it.
Common mistakes
- A stream-stream join without watermarks or a time condition — Joining impressions to clicks on
ad_idalone keeps every row of both streams in state: after a week, the state holds a week of both. Add a watermark on each side and a time-range condition. - Caching the static side of a stream-static join — With
stores.cache(), a store renamed at 10:00 keeps its old name in every later batch. Leave it uncached: Spark reads the static side again for each batch. - Expecting unmatched outer rows right away — A show with no click is written with a null click only after the watermark passes the end of its match range (for a 10-minute range, 10 minutes plus the watermark delay).
- Joining on keys only, with watermarks — Watermarks on both sides with only
ad_id = ad_idstill never drop a row. Addclick_time BETWEEN impression_time AND impression_time + INTERVAL 10 MINUTES.
Key takeaways
- Enrich events with a lookup table through a stream-static join; join two streams only when both sides keep arriving.
- A change on the static side never revises rows that were already joined.
- Full outer joins need two streams; in a stream-static outer join, the stream must be the outer side.
- Size each side's watermark from its measured lateness: a larger delay gives more complete matches and later unmatched rows.
Interview prep
THE QUESTION
"Join ad impressions with clicks that happen within 10 minutes, in a stream. What do you have to get right?"
Avoid: a stream-stream join with watermarks but an equality-only condition. Without a time range, Spark cannot tell when a row can no longer match, and state still grows.
Follow-ups · answer out loud, then open
Follow-up"Which version of a Delta dimension table does a stream-static join use?"
Scenario"Find impressions that got no click within 10 minutes. How, and when do the results appear?"
Trap"A stream-static join keeps the static table in state."
Check yourself
3 questionsA Delta customers table is updated while a stream-static join runs. When does the stream see the change?
Show the answer
In the next micro-batch. The static side is read again for every micro-batch.
What lets Spark remove old rows from a stream-stream join's state?
Show the answer
Watermarks plus a time-range join condition. The time condition turns the watermark into a point after which no match is possible.
In a left outer stream-stream join, when is an unmatched left row written?
Show the answer
Once the watermark passes the end of its match range. Only then can Spark be sure no match will arrive.
Practise this
Problems that use this, graded on hidden tests
Keep going
Up next · Joins and custom state · lesson 2 of 2 · 6 min readCustom state with transformWithState
Typed state per key, timers and TTL for rules that windows and joins cannot express.
Related lessons
Watermarks and late dataSpark internals · 8 min read
Join strategiesStructured Streaming · 7 min read
Event-time windows
Previous: Bad records and dead-letter queues
Primary sources: Join operations