Sub topic 4
Running continuously or as an availableNow job
This chapter covers how a trigger controls when an Auto Loader stream runs, and how to choose between a continuously running stream and a scheduled availableNow job. It assumes you can read basic Structured Streaming code (readStream, writeStream), you know what a checkpoint is from the previous chapter, and you have written to a Delta table before.
What a trigger decides
A trigger is the setting on writeStream that tells Spark when to start the next micro-batch. A micro-batch is one small unit of work: Spark finds the new input, processes it, writes the result, and records progress in the checkpoint.
The trigger does not change what Auto Loader reads. The cloudFiles source finds new files the same way under every trigger. The trigger changes three things:
- How long the query lives. Some triggers keep the query running until you stop it. Others stop it when the work is done.
- How much it costs. A query that runs all day holds a cluster all day.
- How fresh the data is. Frequent micro-batches give lower latency than a job that runs once an hour.
The default trigger: run continuously
If you set no trigger, Spark starts each micro-batch as soon as the previous one finishes. When no new files exist, Spark keeps polling. The query keeps running until it fails or you stop it.
df = (spark.readStream
.format("cloudFiles")
.option("cloudFiles.format", "json")
.option("cloudFiles.schemaLocation", "/Volumes/main/raw/_schemas/orders")
.load("/Volumes/main/raw/landing/orders"))
(df.writeStream
.option("checkpointLocation", "/Volumes/main/raw/_checkpoints/orders")
.toTable("main.bronze.orders"))This code starts the stream and returns right away. In a notebook, the cell keeps showing a running stream. In a job, the task never finishes on its own.
You can also set a fixed interval with processingTime:
(df.writeStream
.option("checkpointLocation", "/Volumes/main/raw/_checkpoints/orders")
.trigger(processingTime="1 minute")
.toTable("main.bronze.orders"))With processingTime, Spark starts a micro-batch at most once per interval. If a batch takes longer than the interval, the next one starts as soon as it ends. A longer interval means fewer, larger batches and fewer calls to list or query storage.
Use a continuously running stream when downstream consumers need data within seconds or a few minutes of arrival, and files arrive often enough to keep the cluster busy.
The availableNow trigger: process the backlog, then stop
The availableNow trigger makes the stream behave like a batch job. Spark finds all files that are pending at the moment the query starts, processes them in one or more micro-batches, and then stops the query.
df = (spark.readStream
.format("cloudFiles")
.option("cloudFiles.format", "json")
.option("cloudFiles.schemaLocation", "/Volumes/main/raw/_schemas/orders")
.load("/Volumes/main/raw/landing/orders"))
(df.writeStream
.option("checkpointLocation", "/Volumes/main/raw/_checkpoints/orders")
.trigger(availableNow=True)
.toTable("main.bronze.orders"))The next time you run this code, the checkpoint tells Spark which files it already handled. Only files that arrived since then are processed. You keep the exactly-once behavior of a stream and get the cost profile of a scheduled job: the cluster runs only while there is work.
The lifecycle of an availableNow run
The set of files to process is fixed when the run starts. Files that land during the run are picked up by the next run, not this one. That is a useful property for scheduled jobs, because each run has a clear scope.
Waiting for completion
toTable returns a StreamingQuery object. With availableNow, call awaitTermination() on it when later code depends on the data being written, for example a second step in the same notebook.
query = (df.writeStream
.option("checkpointLocation", "/Volumes/main/raw/_checkpoints/orders")
.trigger(availableNow=True)
.toTable("main.bronze.orders"))
query.awaitTermination()
print(spark.table("main.bronze.orders").count())Without awaitTermination(), the count() could run while the stream is still writing. In a Databricks job task, the task usually ends only when the stream ends, but waiting explicitly keeps notebooks that run interactively consistent with notebooks that run as jobs.
Comparing the options
| Trigger | Query lifetime | Typical latency | Cluster cost pattern | Typical use |
|---|---|---|---|---|
| None (default) | Runs until stopped | Seconds | Always on | Near-real-time pipelines with steady file arrival |
| `processingTime="5 minutes"` | Runs until stopped | Minutes | Always on | Steady arrival, with fewer storage calls than the default |
| `availableNow=True` | Stops when backlog is drained | Set by job schedule | Only during runs | Hourly or daily loads, bursty arrival |
Choosing between them
Ask these questions in order:
- What freshness do consumers need? If the answer is "within a minute," use a continuous stream. If hourly or daily is fine, use
availableNow. - How regularly do files arrive? Files that arrive in bursts, such as a nightly export, leave a continuous cluster idle most of the day.
availableNowfits better. - What does idle time cost? An always-on cluster has a fixed cost. A scheduled job pays only for the time it runs, plus cluster start time.
- Can you tolerate start-up delay? A scheduled job on a new cluster takes minutes to start. Continuous streams avoid that.
A common pattern is to develop with a continuous stream so you can watch results appear, then switch to availableNow for production. The checkpoint stays valid across this change, because the trigger is not part of the stored query identity.
Interaction with checkpoints and rate limits
Switching triggers is safe, but two behaviors are worth knowing.
First, availableNow honors rate-limit options. If a large backlog exists and you set cloudFiles.maxFilesPerTrigger, the run splits the backlog into several micro-batches of that size. The run still ends only after all pending files are processed. You get bounded memory use without leaving files for the next run.
Second, the older once=True trigger processes the backlog in a single micro-batch and ignores rate limits. It is deprecated in favor of availableNow. Avoid it in new code, because a large backlog processed in one batch can exhaust memory or run for hours before it commits any progress.
df = (spark.readStream
.format("cloudFiles")
.option("cloudFiles.format", "json")
.option("cloudFiles.schemaLocation", "/Volumes/main/raw/_schemas/orders")
.option("cloudFiles.maxFilesPerTrigger", "1000")
.load("/Volumes/main/raw/landing/orders"))
query = (df.writeStream
.option("checkpointLocation", "/Volumes/main/raw/_checkpoints/orders")
.trigger(availableNow=True)
.toTable("main.bronze.orders"))
query.awaitTermination()Rate limiting is covered in detail in a later chapter. Here the point is that availableNow works well for first-time backfills of large directories.
Common errors
- The cell never finishes. You left out the trigger, so the query runs continuously. Add
trigger(availableNow=True)for a one-time or scheduled run. - A scheduled job runs but loads nothing. Check that the job uses the same
checkpointLocationas before. A new checkpoint path means a new stream with no memory of earlier files, so Spark treats every file as unprocessed. If the path is the same and nothing loads, then no new files arrived since the last run. - Duplicate rows after changing the checkpoint path. This is the reverse problem. With a new checkpoint, Auto Loader reads all existing files again and appends them to the table. Keep the path stable, or plan a deliberate reload.
- The next step reads incomplete data. You did not wait for the query. Call
awaitTermination()before reading the target table. - A continuous job fails and nobody notices. A continuous stream that stops on an error leaves the job task failed, but nothing resumes it by default. Configure job retries and alerts, as covered in the chapter on production operations.
Summary
The trigger controls when micro-batches start and whether the query ends. A continuous trigger keeps a stream running for low latency. availableNow drains the pending files and stops, which suits scheduled and bursty workloads. Both use the same checkpoint, so you can move between them without reprocessing files.
Exercise
A nightly export drops about 200 files into a landing folder at 02:00. Analysts read the bronze table at 08:00. Which trigger would you choose, and what must you keep constant between runs so that files are not loaded twice?
Show answer
Use trigger(availableNow=True) in a job scheduled shortly after 02:00. The data is not needed until 08:00 and files arrive in one burst, so an always-on cluster would sit idle most of the day. Keep the same checkpointLocation on every run (along with the same schemaLocation), because the checkpoint records which files were already processed.
Exercise
A notebook runs an availableNow stream into main.bronze.orders and the next cell runs spark.table("main.bronze.orders").count(). The count is sometimes lower than expected. What is the likely cause, and what is the fix?
Show answer
The next cell runs while the stream is still writing, because toTable returns immediately. Assign the result to a variable and call awaitTermination() on it before reading the table.
Exercise
You set cloudFiles.maxFilesPerTrigger to 1000 and run with availableNow=True against a backlog of 5,500 files. How many micro-batches does the run produce, and does the run process all the files?
Show answer
About six micro-batches: five of 1,000 files and one of 500. The run processes all 5,500 files and then stops, because availableNow continues until the backlog that existed at the start is drained.