Triggers
A stream does not handle each event the moment it arrives. It collects what is new and processes it in small rounds, called micro-batches. The trigger decides when each round starts. This lesson explains the options with a bus timetable, then shows which one to pick.
Step 4 · Structured Streaming · Bronze · First streams, lesson 5 of 5
On this page
Read first: Structured Streaming basics (skip if you know it)
In plain words first
Think of new data as passengers arriving at a bus stop, and 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 → as one bus that takes everyone waiting. The trigger is the timetable:
No trigger set
Every minute
availableNow
The size of the bus is a separate setting, such as maxFilesPerTrigger (at most this many new files per round). Spark remembers who has already travelled in the checkpointcheckpoint: In streaming, the folder where Spark records which input it has processed and its state, so a restarted query continues where it stopped. Learn more →, so nobody rides twice.
The triggers
The trigger is set on the writer, after writeStream. You can change it between runs of the same query: the checkpoint does not record it.
| Trigger | What it does | Use it for |
|---|---|---|
| None set (the default) | Starts the next round as soon as the last one finishes | The freshest results, on a cluster that runs all the time |
processingTime="1 minute" | Starts one round every minute | Data fresh within about a minute, with fewer and larger writes |
availableNow=True | Processes all the data waiting when it starts, a limited amount per round, then stops. The next run picks up only what arrived since | A job that a scheduler starts every hour or every day |
once=True | The old version of availableNow: one single round with everything that is waiting, however much that is | Nothing: it is deprecated. Use availableNow |
continuous="1 second" | No rounds at all: taskstask: The work for one partition in one stage, run on one CPU core. Learn more → keep running and handle rows as they come. "1 second" is how often progress is saved | Experimental. Only simple queries (select, filter), and rows can be repeated after a failure |
When a round takes longer than the interval
10:00 · a quick round
10:01 · a slow round
10:02:30 · no overlap
Every time? · the warning sign
processedRowsPerSecond (how fast Spark gets through rows) with inputRowsPerSecond (how fast they arrive), then add resources or limit how much each round takes.availableNow: a stream on a schedule
Many pipelines only need fresh data every hour. Keeping a cluster running all day for that wastes money. With trigger(availableNow=True), the same streaming code becomes a job a scheduler (Airflow, a Databricks job, cron) starts every hour. Each run reads everything that arrived since the last run, in rounds no bigger than maxFilesPerTrigger or maxOffsetsPerTrigger, saves its progress in the checkpoint after each round, and stops. Nothing is read twice or missed, and you pay for the cluster only while it runs.
once=True for one reason. After a long outage, once tries to read the whole backlog in one enormous round, which can run out of memory. availableNow splits the same backlog into normal-sized rounds.Choosing a trigger
| Data must be fresh within | Trigger | What it costs |
|---|---|---|
| Seconds | The default, or a short processingTime | A cluster running all the time, and many small files to tidy up |
| A few minutes | processingTime of 1 to 5 minutes | Still always running, but fewer and larger files |
| An hour or a day | availableNow, started by a scheduler | A cluster only while the job runs |
| Milliseconds | Continuous processing, or a platform's real-time mode | Fewer operations allowed and weaker guarantees: check your query fits |
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: Run a stream as a scheduled job: process everything new in bounded batches, then stop.
import json, os os.makedirs("lab/trig/in", exist_ok=True) def land(n): # a producer drops one file path = f"lab/trig/in/f{n}.json" with open(path, "w") as f: f.write(json.dumps({"id": n})) os.utime(path, (1_700_000_000 + n, 1_700_000_000 + n)) # read in this order def scheduled_run(): # what the scheduler runs, e.g. hourly q = (spark.readStream.schema("id INT") .option("maxFilesPerTrigger", 1) .json("lab/trig/in") .writeStream.format("parquet") .option("path", "lab/trig/out") .option("checkpointLocation", "lab/trig/_chk") .trigger(availableNow=True) # everything new, then stop .start()) q.awaitTermination() return [p["numInputRows"] for p in q.recentProgress] for n in range(3): land(n) print("run 1, rows per micro-batch:", scheduled_run()) land(3) print("run 2, rows per micro-batch:", scheduled_run()) print("run 3, rows per micro-batch:", scheduled_run())
Output from a real run
run 1, rows per micro-batch: [1, 1, 1] run 2, rows per micro-batch: [1] run 3, rows per micro-batch: [0]
What to notice:
- Run 1 found a backlog of 3 files and processed it as 3 batches of 1.
- Run 2 read only the one new file; run 3 found nothing.
- The checkpoint is what makes each scheduled run pick up only new data.
Common mistakes
- Using trigger(once=True) to catch up — After an outage it reads everything in one huge round. Use availableNow.
- A very short processingTime into a Delta table — Thousands of small writes and files a day. Use a longer interval, or compact the table.
- An always-on stream for hourly reports — You pay for a cluster that sits idle. availableNow on a schedule gives the same result.
- Ignoring rounds that take longer than the interval — The stream is quietly falling behind.
Key takeaways
- The trigger decides when each micro-batch (round) starts: back to back by default, or on a fixed interval with processingTime.
- A round that runs late is followed straight away by the next; rounds never overlap.
- availableNow processes what is waiting in limited rounds and stops: a stream that a scheduler can run like a batch job. once is deprecated.
- Pick the trigger from how fresh the data must be and what an idle cluster costs.
Interview prep
THE QUESTION
"A dashboard needs data that is at most 15 minutes old. Would you run an always-on stream or a scheduled job?"
Avoid: "use trigger(once=True) for a nightly job". once is deprecated and reads a whole backlog in one unbounded batch; availableNow does the same job in bounded batches.
Follow-ups · answer out loud, then open
Follow-up"What exactly happens when a batch takes longer than its processingTime interval?"
Scenario"You move a stream from an always-on cluster to an hourly availableNow job. What changes in the code?"
Trap"Continuous processing is the low-latency version of micro-batches, so turn it on everywhere."
Check yourself
3 questionsWith processingTime="1 minute", a round starts at 10:00 and takes 90 seconds. When does the next one start?
Show the answer
10:01:30, right after it finishes. Rounds never overlap; a late round is followed straight away by the next.
What does availableNow do after a long outage?
Show the answer
Works through the backlog in normal-sized rounds, then stops. It respects maxFilesPerTrigger / maxOffsetsPerTrigger, unlike once.
Can you change a query's trigger and keep its checkpoint?
Show the answer
Yes. The trigger is not part of what the checkpoint records.
Practise this
Interview problems on streaming, graded on hidden tests
Keep going
Up next · new module: Output modes and checkpoints · 6 min readOutput modes: append, update, complete
What each mode writes after a batch, which queries allow which mode, and what the sink must support.
Related lessons
Sources and sinksStructured Streaming · 7 min read
Incremental file ingestionStructured Streaming · 6 min read
Monitoring streams
Previous: foreachBatch: write a stream anywhere
Primary sources: Triggers