Apache Spark Streaming
medium 28 minSpark treats a stream as a table that keeps growing and runs your query again and again on the new rows, in small batches.
See it run
Plan a batch, crash it, watch the watermark close a window, and switch to the real-time trigger.
Operations
One micro-batch
Plan, run, commit.
Step 1 of 5
Ask for offsets
The driver asks Kafka how far the topic has grown.
Step 1: Ask for offsets
end = source.latest()checkpoint.offsets[b] = (start, end)rows = source.read(start, end)state[b] = update(state[b - 1], rows)sink.write(b, result(state[b]))checkpoint.commits.add(b)- Delay
- Wait plus processing time
- Protects
- A repeatable unit
- Record by record
- no wait, other recovery
The plan is durable before any row is read.
In the real world
The same spark structured streaming doing real jobs. Pick one and step through it.
A batch takes 14 seconds with a 10 second trigger.
Step 1 of 4
In time
- Batch time of the interval
- 60%
- Lag
- 5%
6 seconds of work, then 4 seconds of rest.
Step 1: In time
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Adding in foreachBatch
criticalA repeated batch adds its numbers a second time.
WrongUPDATE t SET total = total + batch_totalRightUPSERT t SET total = new_total-- or check batch_id in the same transactionTwo queries, one checkpoint
criticalThey overwrite each other's offsets and state.
WrongcheckpointLocation = "/cp" # bothRightcheckpointLocation = "/cp/" + query_nameState without a watermark
majorNothing may ever be removed.
Wrongdf.groupBy(window("at", "5 minutes")).count()Rightdf.withWatermark("at", "10 minutes") .groupBy(window("at", "5 minutes")).count()Starting new work on DStreams
majorIt is legacy and gets no updates.
Wrongssc = StreamingContext(sc, 1)Rightspark.readStream.format("kafka").load()
Interview tips
How to explain it
- A stream is a table that grows.
- Each step: plan, run, commit.
- A crash repeats the open step.
Memory trick
- The plan on the board comes first.
- Same trip, same riders.
- Done only after arrival.
Reach for it when
- You already run Spark.
- Seconds are fine.
- Data lands in a lake.
Be careful when
- Batch time nears the interval.
- The sink only appends.
- The state schema must change.