Skip to content
Gold 7 min read · Joins 2 practice problems ↓

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

Read first: Watermarks and late data · join (skip if you know them)

In plain words first

Stream-static: a phone book

A call comes in, you look the caller up in the phone book and note their name. The phone book is a normal table; you check it again for every new call.

Stream-stream: a coat check

A coat is handed in now; its owner comes back later with the ticket. The cloakroom must keep each coat until its owner returns, and it needs a closing time, or the room fills up forever. In a stream-stream join, the closing time is the watermarkwatermark: In streaming, how late data may arrive. Spark uses it to know when old state can be dropped. Learn more → plus a time limit in the join condition.

Stream-static: enrich each event

PySpark · Sales enriched with store data
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 typeStream-staticStream-stream
InnerYesYes; watermarks and a time condition bound state
Left outerYes, with the stream on the leftYes, needs watermarks and a time condition
Right outerYes, with the stream on the rightYes, needs watermarks and a time condition
Full outerNoYes, needs watermarks and a time condition
Left semiYes, with the stream on the leftYes, 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.

PySpark · Ad clicks within 10 minutes of the impression
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 clicks watermark says no click older than (latest click - 20 minutes) will still arrive.

The condition · clicks come at most 10 minutes after a show

A show can only match clicks up to 10 minutes after it. Once the clicks watermark is past shown_at + 10 minutes, no future click can match that show.

The result · old shows leave state

Spark removes such shows from state. The same reasoning with the shows watermark removes old clicks. State now holds roughly the watermark delay plus the 10-minute range, instead of everything.

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.

Production patternPySpark · Ads clicked within 10 minutes of being shown: a stream-stream join
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_id alone 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_id still never drop a row. Add click_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?"

Watermarks on both streams sized from their lateness, and a join condition that bounds time: ad_id equal and click_time between impression_time and impression_time + 10 minutes. Without the time bound Spark cannot drop rows from state, whatever the watermarks. For "impressions with no click", use a left outer join and expect those rows only after the watermark passes impression_time + 10 minutes. Also mention monitoring state size per operator, since a join keeps both sides.

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?"
The latest one for each micro-batch: the static side is re-planned every batch. Rows already joined are not revised when the dimension changes later, and caching the static side freezes it.
Scenario"Find impressions that got no click within 10 minutes. How, and when do the results appear?"
A left outer stream-stream join with watermarks on both sides and a time condition (click between impression and impression + 10 minutes). Unmatched impressions come out with null clicks once the watermark passes impression time + 10 minutes, not immediately.
Trap"A stream-static join keeps the static table in state."
It keeps nothing in state; it joins each micro-batch against the static side as it is at that moment.

Check yourself

3 questions

A 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 read
Custom state with transformWithState
Typed state per key, timers and TTL for rules that windows and joins cannot express.

Related lessons

Previous: Bad records and dead-letter queues

Primary sources: Join operations