AlgoViz

Apache Spark Streaming

medium 28 min

Spark 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

Kafkaup to 500Driverbatch 7?Executorstasks, stateCheckpointbatch 6 doneSinkresults

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

KafkaordersDriverplansExecutorstasks, stateCheckpointbatch 6 doneSinkresults
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

    critical

    A repeated batch adds its numbers a second time.

    Wrong
    UPDATE t SET total = total + batch_total
    Right
    UPSERT t SET total = new_total-- or check batch_id in the same transaction
  • Two queries, one checkpoint

    critical

    They overwrite each other's offsets and state.

    Wrong
    checkpointLocation = "/cp"  # both
    Right
    checkpointLocation = "/cp/" + query_name
  • State without a watermark

    major

    Nothing may ever be removed.

    Wrong
    df.groupBy(window("at", "5 minutes")).count()
    Right
    df.withWatermark("at", "10 minutes")  .groupBy(window("at", "5 minutes")).count()
  • Starting new work on DStreams

    major

    It is legacy and gets no updates.

    Wrong
    ssc = StreamingContext(sc, 1)
    Right
    spark.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.