Apache Spark Structured Streaming
Lesson opener
In one line: Structured Streaming treats the stream as a table that grows. A checkpoint is how the query remembers where it was.
Why it matters: Northline's minute totals for FX-100 died when the Spark driver restarted. The job started again at the beginning of stock.picked and added the same picks into a new folder. Figures are illustrative. The Python below models the checkpoint. It does not start a cluster.
Before this lesson: Lesson 5. You can bucket event time.
What you will be able to do
- Name a source, a transformation, a sink, and a checkpoint.
- Say what
append,update, andcompleteoutput modes are for. - Resume from a checkpoint instead of from offset zero.
- Refuse a query that changes its logic and reuses an old checkpoint blindly.
Prerequisites
The guide for this lesson is Spark 4.0.1 Structured Streaming (https://spark.apache.org/docs/4.0.1/structured-streaming-programming-guide.html). Kafka input uses the spark-sql-kafka module described there. pip install of a driver does not create that cluster or that checkpoint directory. Examples here are the recovery rules, in Python.
A query that can resume
Plain English: You read a source with a streaming read, transform it as a table, and write it with a streaming write. The checkpoint location stores offsets and state. On restart, the query loads that location. Without it, Spark has nothing to resume from.
Output modes, as the guide defines them:
- Append. Write only rows that will not change. A tumbling count that can still receive a late event is a poor fit for append until the window closes.
- Update. Write rows that changed.
- Complete. Write the whole aggregation each time. That fits a small total, not an unbounded row-level dump.
A watermark on event time, plus a window, lets state expire. The delay is the one you set in the query. This course's example allowance stays 2 minutes unless the query says otherwise.
Fault tolerance here means: the source can be replayed, the checkpoint remembers the offsets you completed, and the sink must tolerate a replay. A sink that only inserts will duplicate if a batch is written and the checkpoint update fails afterward. Prefer a sink that overwrites a window key, or keep the pick id.
Do not point a changed query at an old checkpoint. The guide's recovery section is about what happens after you change a streaming query. Stop, write a new checkpoint location, and replay on purpose.
Teacher walkthrough: resume past offset 2
All figures are illustrative.
The topic offsets already applied are 0 and 1. The checkpoint stores next offset 2. A restart must not re-add those picks.
- Read the checkpoint before you add.
- Apply only offsets at or after that number.
- Advance the checkpoint to one past the last applied offset.
- Validation: picks at offsets 0 and 1 do not change a total that already includes them. Offset 2 does.
def resume(total, records, checkpoint):
for offset, qty in records:
if offset < checkpoint:
continue
total += qty
checkpoint = offset + 1
return total, checkpoint
total, checkpoint = resume(4, [(0, 2), (1, 1), (2, 2)], 2)
assert total == 6
assert checkpoint == 3The checkpoint is 2, so offsets 0 and 1 are skipped. Offset 2 adds 2 to the starting total of 4, which becomes 6. It does not become 4 + 2 + 1 + 2.
A second workplace case
A window row is overwritten by key (sku, window_start). A replay of the same closed window replaces 2 with 2. It does not become 4.
def upsert(table, key, qty):
table[key] = qty
return table
table = {}
upsert(table, ("FX-100", 10), 2)
upsert(table, ("FX-100", 10), 2)
assert table[("FX-100", 10)] == 2Failure example: the new code used yesterday's checkpoint
Symptom: After a logic change, the job fails on startup or silently ignores the new watermark.
Diagnosis: The checkpoint belongs to the previous query plan. The root cause is reusing that directory for a different query. An empty checkpoint is a different bug: the job would reread the topic.
Correction: Keep the old checkpoint for the old query. Start the new query with a new checkpoint directory. Decide the start offset on purpose. Do not delete the old directory until you have the serving numbers you can rebuild.
Validation: A new checkpoint at offset 2 skips 0 and 1. A missing checkpoint modeled as 0 re-adds them, which is the failure you are refusing.
def added(records, checkpoint):
return sum(qty for offset, qty in records if offset >= checkpoint)
records = [(0, 2), (1, 1), (2, 2)]
assert added(records, 2) == 2
assert added(records, 0) == 5Guided practice: mode and checkpoint
Scenario: You publish one row per closed minute per SKU. The row's quantity can still be corrected until the watermark passes. Figures are illustrative.
Hints:
- Will that row change after it is first emitted?
- Which output mode fits a row that can change?
- What directory must survive a restart?
Complete solution:
A row that can change is not append-only. Use update (or complete, if the whole small aggregation is what you rewrite). The checkpoint directory is required. Overwrite the serving row by (sku, window_start) so a replay does not add.
def mode_for(row_can_change):
return "update" if row_can_change else "append"
assert mode_for(True) == "update"
assert mode_for(False) == "append"Independent practice
Describe one streaming query you could run on stock.picked.
Acceptance criteria:
- You name the source topic, the transformation, and the sink key.
- You choose an output mode and say whether the row can change.
- You name a checkpoint directory that a restart will find.
- You show one offset the restart will skip.
- You do not reuse a checkpoint after you change the query.
Common mistakes
- Running without
checkpointLocationand expecting resume. - Using append on a window that is still open.
- Letting the sink insert on every replay.
- Editing the query and keeping the old checkpoint path.
Quick check
- What does the checkpoint remember?
- What does append write?
- Why did offset 0 stay out of the resumed sum?
- What should a replay do to an existing window row?
- When do you open a new checkpoint directory?
Answers:
- Offsets and state so the query can resume.
- Rows that are not supposed to change later.
- It was below the checkpoint.
- Replace that key, not add a second copy.
- When the query changes.
Quiz alignment
The quiz asks you to resume from a checkpoint, to pick an output mode, and to refuse an old checkpoint on a new query.
Lesson summary
Structured Streaming is a growing table with a checkpoint. Append, update, and complete are different promises. The sink must survive a replay. A new query gets a new checkpoint.
Bridge to the next lesson
The next lesson puts ingest, enrich, and the quality gate in one pipeline, and says what happens when the pick file is empty or the enrich lookup misses. Bring the checkpoint rule.