Skip to content
GoldNEW 6 min read · Spark 4 2 practice problems ↓

Custom state with transformWithState

Typed state per key, timers and TTL for rules that windows and joins cannot express.

Step 4 · Structured Streaming · Gold · Joins and custom state, lesson 2 of 2

Read first: Checkpoints and state stores · Watermarks and late data (skip if you know them)

In plain words first

Picture a nurse with a notebook page per patient. Each time a patient's reading comes in, the nurse updates that page, and sets an alarm: "check on bed 7 in 10 minutes if nothing new arrives". If a reading arrives first, the alarm is reset; if the alarm rings, the nurse acts, even though no new data came. Pages of patients who left are torn out, so the notebook does not grow forever.

In Spark, the page is state per key, the alarm is a timer, and tearing out old pages is clear() or a TTL (time to live: delete it automatically after a while).

Unlock the full lesson

You have read the free part. The rest of this advanced lesson:

  • When you need custom state
  • A StatefulProcessor
  • Making state go away
  • Try it yourself
  • Common mistakes
  • Key takeaways
  • Interview prep with 3 follow-up questions
  • Check yourself: 3 questions

Unlock it with the Complete pass (every advanced problem and lesson) or on its own.

Practise this

Interview problems on streaming, graded on hidden tests

Keep going

Up next · new module: Running streams in production · 6 min read
Monitoring streams
The progress report, the four signals worth an alert, listeners and the Spark UI.

Related lessons

Previous: Stream joins

Primary sources: transformWithState · Arbitrary stateful operations