Skip to content
Bronze 7 min read · availableNow 2 practice problems ↓

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

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

The bus leaves again the moment it gets back. Passengers barely wait, but the bus never rests.

Every minute

A bus leaves once a minute and takes whoever is waiting. Fewer trips, a little more waiting.

availableNow

One special service: it takes everyone waiting right now, in several trips if they do not fit in one bus, and then stops for the day. Run it again tomorrow and it takes only the new passengers.

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.

TriggerWhat it doesUse it for
None set (the default)Starts the next round as soon as the last one finishesThe freshest results, on a cluster that runs all the time
processingTime="1 minute"Starts one round every minuteData fresh within about a minute, with fewer and larger writes
availableNow=TrueProcesses all the data waiting when it starts, a limited amount per round, then stops. The next run picks up only what arrived sinceA job that a scheduler starts every hour or every day
once=TrueThe old version of availableNow: one single round with everything that is waiting, however much that isNothing: 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 savedExperimental. 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

The round starts at 10:00 and takes 20 seconds. Spark waits until 10:01 to start the next one.

10:01 · a slow round

This round has a lot of data and takes 90 seconds, so it ends at 10:02:30. The 10:02 start time has already passed.

10:02:30 · no overlap

The next round starts straight away, at 10:02:30. Two rounds never run at the same time, and missed start times are not made up later. Spark logs that the query fell behind.

Every time? · the warning sign

If rounds keep taking longer than the interval, the stream is running non-stop and still falling behind. Compare 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.

Tip: availableNow replaced 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 withinTriggerWhat it costs
SecondsThe default, or a short processingTimeA cluster running all the time, and many small files to tidy up
A few minutesprocessingTime of 1 to 5 minutesStill always running, but fewer and larger files
An hour or a dayavailableNow, started by a schedulerA cluster only while the job runs
MillisecondsContinuous processing, or a platform's real-time modeFewer 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.

Production patternPySpark · A scheduled incremental job: availableNow, in bounded batches
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?"

A scheduled job with trigger(availableNow=True) every 10 minutes is usually right: the same code and checkpoint as a stream, exactly-once, but the cluster only runs while there is work, and each run writes fewer, larger files. An always-on stream earns its cost when freshness has to be seconds or when the start-up time of a job is a large share of the interval. I would also say how I would size each run (maxOffsetsPerTrigger) so a catch-up after an outage stays predictable.

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?"
Nothing runs in parallel: the next batch starts as soon as the late one finishes, and missed slots are not made up. If that happens every time, the query is running back to back and falling behind.
Scenario"You move a stream from an always-on cluster to an hourly availableNow job. What changes in the code?"
Only the trigger. The source, the logic, the sink and the checkpoint stay the same, so the job continues exactly where the stream stopped. Add a batch size limit so each hourly run is predictable.
Trap"Continuous processing is the low-latency version of micro-batches, so turn it on everywhere."
It is experimental, supports only map-like queries (no aggregations), and is at-least-once. Use it only when milliseconds matter and the query qualifies.

Check yourself

3 questions

With 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 read
Output modes: append, update, complete
What each mode writes after a batch, which queries allow which mode, and what the sink must support.

Related lessons

Previous: foreachBatch: write a stream anywhere

Primary sources: Triggers