Sub topic 13
Limiting how much each micro-batch reads
This chapter assumes you can write a basic Auto Loader stream with cloudFiles, and that you know what a checkpoint and a trigger are. If those are new, read the earlier chapters first.
Why batch size needs a limit
A micro-batch is one unit of work in Structured Streaming. The stream reads some input, transforms it, writes it, and records progress in the checkpoint. How much input goes into one micro-batch changes how the job behaves.
When a stream first starts, the landing folder may hold months of history, such as 200,000 files. If the stream tried to read all of them in one micro-batch, you would see several problems:
- Executors could run out of memory during shuffles or wide transformations.
- One failure would throw away hours of work, because the checkpoint only records progress after a batch commits.
- Progress would be invisible until the whole batch finished.
- The write to the Delta table would be one very large transaction.
Rate limiting caps the input of each micro-batch. The remaining files stay in a queue and are picked up by later batches. Nothing is skipped or dropped.
The two options
Auto Loader has two options that set the cap. Both use the cloudFiles. prefix.
| Option | Meaning | Default |
|---|---|---|
| `cloudFiles.maxFilesPerTrigger` | Maximum number of new files in each micro-batch | 1000 |
| `cloudFiles.maxBytesPerTrigger` | Approximate maximum total size of new data in each micro-batch | Not set |
maxBytesPerTrigger takes a size string such as "512m" or "10g". It is a soft limit. A batch can go slightly over it, and if one file is larger than the limit, that file still forms a batch on its own. Auto Loader never splits a file across batches, so the limit can only be applied between files.
If you set both options, the batch ends when either limit is reached first.
A worked example
This stream reads JSON files and caps each micro-batch at 500 files or about 2 GB, whichever comes first.
df = (spark.readStream
.format("cloudFiles")
.option("cloudFiles.format", "json")
.option("cloudFiles.schemaLocation", "/Volumes/main/raw/_schemas/orders")
.option("cloudFiles.maxFilesPerTrigger", "500")
.option("cloudFiles.maxBytesPerTrigger", "2g")
.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()Suppose the landing folder holds 20,000 files, each about 1 MB. The file limit is the tighter one here, because 500 files is only about 500 MB. The job runs 40 micro-batches and then stops. Now suppose the files are 20 MB each. The byte limit applies first, at about 100 files per batch, and the job runs about 200 batches.
How the limits interact with triggers
The rate limits apply to every trigger type, and the way they combine with the trigger matters.
- Continuous (default) trigger. Each micro-batch takes up to the limit, and the next one starts as soon as the previous one ends. When fewer files than the limit are waiting, the batch is smaller.
availableNow=True. The stream processes everything that exists when the run starts, split into several micro-batches that respect the limits. Then it stops. This is the most common pairing for scheduled jobs. Without rate limits, a long backlog becomes one huge batch.processingTime. Each interval takes up to the limit. If the backlog is bigger than one batch, the stream falls behind until the data rate drops.
Choosing values
There is no universal right number. Pick values by looking at what a batch costs.
- Start from batch duration. A batch that finishes in 30 seconds to a few minutes is usually healthy. If batches take an hour, lower the limit. If they take two seconds and most of that is overhead, raise it.
- Prefer bytes when file sizes vary. A file count says little when some files are 10 KB and others are 2 GB. A byte limit tracks the actual work more closely.
- Prefer files when files are small and uniform. Many tiny files cost per-file overhead, so a file limit keeps that overhead predictable.
- Consider the cluster. A batch should give every core enough work. If a batch has fewer files than the cluster has cores, you waste capacity.
- Think about failure cost. Smaller batches mean less work to redo after a failure, but they also mean more commits and more small writes to the Delta table.
Changing limits between runs
The limits are read when the stream starts. They are not part of the data that defines which files were processed, so you can change them between runs while keeping the same checkpoint. A common pattern is to use small limits for the first backfill, then raise them for the steady state, or the reverse. Restart the stream after changing the option. A running stream does not pick up new values.
Rate limiting does not change which files are processed or the exactly-once guarantee. It only changes how the pending files are grouped. A different grouping after a restart gives the same final table contents.
Checking the backlog
To decide whether your limits are right, look at the progress reports. Auto Loader adds backlog metrics to the source section of each progress report. These include the number of files and bytes still waiting to be processed. A backlog that shrinks over time means the stream keeps up. A backlog that grows means your batches cannot keep pace with arrivals, and raising the limit alone will not fix that if the cluster is the bottleneck.
progress = query.lastProgress
if progress:
for source in progress["sources"]:
print(source["description"])
print(source.get("metrics", {}))Look for the outstanding file and byte counts in the printed metrics. The exact set of metric names can vary between runtime versions, so print the dictionary once and check what your runtime reports.
Common errors
- Limit ignored. The option was spelled without
cloudFiles., or it was set on the writer instead of the reader. These options belong onreadStream. - Batches far larger than the byte limit. The limit is soft, and a single large file can exceed it. Check file sizes before assuming the option is broken.
- A backfill that seems stuck. Each batch commits separately. If the job is running with a small limit and 100,000 files, it will take many batches. Watch the backlog metrics before cancelling.
- Limits changed but no effect. The stream has to be restarted for new option values to apply.
- Expecting the limit to reduce discovery cost. The limits control how many discovered files go into each batch. They do not make directory listing faster. Discovery mode is a separate choice, covered in the discovery chapters.
Exercise
An availableNow job reads 12,000 files of about 5 MB each. You set cloudFiles.maxFilesPerTrigger to 1000 and cloudFiles.maxBytesPerTrigger to 2g. Roughly how many micro-batches will the run use, and which option decides the batch size?
Show answer
The byte limit decides it. 2 GB divided by 5 MB is about 400 files per batch, which is below the 1000-file limit, so the batch ends at the byte limit first. 12,000 files at about 400 per batch gives about 30 micro-batches. Because maxBytesPerTrigger is a soft limit, the exact count can differ slightly.
Exercise
You lowered cloudFiles.maxFilesPerTrigger in your notebook while the stream was running, but batches stay the same size. What is the cause and what should you do?
Show answer
The option is read when the stream starts, so a running stream does not pick up the change. Stop the stream and start it again with the same checkpoint location. The new limit then applies, and no files are reprocessed or skipped.