Sub topic 6
Processing only new data: streaming, triggers, and checkpoints
This chapter assumes you can write basic PySpark DataFrame code, know what a Delta table is, and have seen the Auto Loader bronze example from the previous chapter. Here you learn how Structured Streaming lets each medallion layer process only the data that arrived since the last run, and how to avoid the errors that come from misusing it.
Why incremental processing matters
A bronze table grows all the time. If the silver step re-reads every bronze row on each run, cost and runtime grow with history instead of with new data. Incremental processing means each run reads only the rows or files that are new since the previous run.
Structured Streaming is the Spark engine that does this. You write a query against a stream, which is an unbounded table that keeps getting new rows. Spark runs it in small batches (micro-batches) and remembers how far it got.
Streaming does not have to mean "always on". The same engine can run as a scheduled batch job that wakes up, processes what is new, and stops. Most medallion pipelines use this pattern because it is cheap and simple to operate.
The three parts of a streaming query
Every streaming query has a source, a sink, and state that records progress.
- Source: where new data comes from. For bronze it is files (through Auto Loader, format
cloudFiles). For silver it is often the bronze Delta table. - Sink: where results go, such as a Delta table.
- Checkpoint: a directory where Spark records which data it has already processed.
Delta tables work as both streaming sources and sinks. A stream reading a Delta table picks up new commits to that table. That is why a bronze table can feed silver without any extra messaging system.
Reading a Delta table as a stream
The bronze step from the earlier chapter used cloudFiles. For silver, read the bronze table with readStream. The example below shows a stream from bronze to silver, using foreachBatch so you can run the MERGE from the deduplication chapter on each micro-batch.
from delta.tables import DeltaTable
from pyspark.sql import functions as F
from pyspark.sql.window import Window
def upsert_to_silver(batch_df, batch_id):
latest = (
batch_df
.where("order_id IS NOT NULL")
.withColumn(
"rn",
F.row_number().over(
Window.partitionBy("order_id").orderBy(F.col("_ingested_at").desc())
),
)
.where("rn = 1")
.select(
"order_id",
"customer_id",
F.col("order_ts").cast("timestamp").alias("order_ts"),
F.col("amount").cast("decimal(12,2)").alias("amount"),
"status",
)
)
(
DeltaTable.forName(spark, "main.silver.orders").alias("t")
.merge(latest.alias("s"), "t.order_id = s.order_id")
.whenMatchedUpdateAll()
.whenNotMatchedInsertAll()
.execute()
)
(
spark.readStream.table("main.bronze.orders")
.writeStream
.foreachBatch(upsert_to_silver)
.option("checkpointLocation", "/Volumes/main/sales/checkpoints/orders_silver")
.trigger(availableNow=True)
.start()
)The deduplication happens inside each micro-batch. A later batch can still contain a newer version of an order that is already in silver. The MERGE handles that case by updating the existing row. Without the merge, an append-only write would create duplicates across batches.
One more detail: foreachBatch gives you at-least-once behavior. If a failure happens after the merge but before the checkpoint is committed, Spark re-runs that batch. A merge keyed on order_id gives the same result when repeated, so this is safe here. Plain appends in foreachBatch are not.
Triggers: when a micro-batch runs
A trigger tells Spark when to run the next micro-batch. Pick it based on how fresh the data must be and how much you want to pay.
| Trigger | Behavior | Typical use |
|---|---|---|
| Default (no trigger) | Starts the next micro-batch as soon as the previous one finishes | Low latency, cluster always on |
| `processingTime="10 minutes"` | Starts a micro-batch on a fixed interval | Near real-time, always-on cluster |
| `availableNow=True` | Processes everything available, in one or more batches, then stops | Scheduled jobs, cost-efficient medallion runs |
| `once=True` | Processes one batch, then stops | Legacy. Prefer `availableNow` |
availableNow=True is the usual choice for scheduled medallion pipelines. It splits a large backlog into several batches, so it respects rate limits such as maxFilesPerTrigger and does not need to fit the whole backlog in memory at once. The older once=True runs the backlog as a single batch, which can overload the cluster after an outage.
(
spark.readStream.table("main.bronze.orders")
.writeStream
.option("checkpointLocation", "/Volumes/main/sales/checkpoints/orders_silver_append")
.option("maxFilesPerTrigger", 100)
.trigger(availableNow=True)
.toTable("main.silver.orders_append")
)Note that maxFilesPerTrigger applies to file sources such as Auto Loader. For reading a Delta table as a stream, the equivalent limits are maxFilesPerTrigger and maxBytesPerTrigger, which count the table's data files.
Checkpoints: how Spark remembers
A checkpoint stores two kinds of information: which source data has been read (offsets), and the state of the query, such as aggregation state. When the query restarts with the same checkpoint, it resumes where it stopped. That gives you exactly-once processing from the stream's point of view when the sink is a Delta table.
Follow these rules.
- One checkpoint per stream. Never share a checkpoint path between two queries. Each query needs its own.
- Keep the checkpoint in durable storage. A Unity Catalog volume works. Do not use a temporary location, or the stream restarts from the beginning.
- Treat the checkpoint and the target table as a pair. If you delete the target table but keep the checkpoint, the stream thinks old data is already processed and the new table stays empty. If you delete the checkpoint but keep the table, the stream reprocesses everything and may create duplicates.
- Keep the checkpoint with the logic. Some changes to the query are not allowed with an existing checkpoint, such as changing the source, or changing the keys of a stateful aggregation.
Replaying a layer
Because bronze keeps raw data, you can rebuild silver from it. The safe sequence is:
- Stop the silver stream.
- Drop or truncate the silver table, or plan for the merge to overwrite existing rows.
- Delete the silver checkpoint directory.
- Start the stream again.
Because silver uses MERGE, a replay without truncation is also safe when the merge key is stable. The replay simply rewrites each row with the latest version. For gold tables built with CREATE OR REPLACE TABLE, no replay is needed, since each run rebuilds the whole table.
Common errors
- Stream never ends under
availableNow. This almost always means the source is receiving data faster than it is processed, or a different trigger is set. Check thatavailableNow=Trueis in the code that actually runs. - Two jobs write to the same checkpoint. The second fails or corrupts progress. Give each stream its own path.
- Schema change breaks the stream. If bronze gains a column, a stream reading it may fail or ignore the column, depending on the settings. Handle schema evolution in bronze first, then update silver deliberately.
- Updates or deletes in the source table. A stream that reads a Delta table expects appends. If someone updates or deletes rows in bronze, the stream fails by default. Options such as
skipChangeCommitsskip those commits, but you then miss the changes. Keep bronze append-only to avoid the problem. - Missing
awaitin notebooks and scripts..start()returns a handle. WithavailableNow, call.awaitTermination()on it if later code must run after the data is processed, for example in a job task that follows.
query = (
spark.readStream.table("main.bronze.orders")
.writeStream
.option("checkpointLocation", "/Volumes/main/sales/checkpoints/orders_silver_copy")
.trigger(availableNow=True)
.toTable("main.silver.orders_copy")
)
query.awaitTermination()
print(query.lastProgress["numInputRows"])Which layers should be incremental
Bronze and silver are good candidates for streaming, since both grow with every new file. Gold depends on what it aggregates. A small daily summary can be rebuilt in full, as the gold example does with CREATE OR REPLACE TABLE. A very large gold table may need incremental refresh, which a declarative pipeline can manage for you. A later chapter covers that.
Exercise
Your silver stream runs on a nightly job with trigger(availableNow=True). After a bug fix, you delete the silver table but leave its checkpoint directory in place, then rerun the job. The new silver table is empty. Why, and what should you do?
Show answer
The checkpoint still records that all bronze data was already read, so the stream finds nothing new and writes nothing. To rebuild silver, stop the stream, delete the silver checkpoint directory (along with the table, which is already gone), recreate the table if needed, and start the stream again so it reads bronze from the beginning.
Exercise
Why is trigger(availableNow=True) usually preferred over trigger(once=True) for a scheduled bronze-to-silver job?
Show answer
availableNow processes the backlog in multiple micro-batches and honors rate limits such as maxFilesPerTrigger, so a large backlog does not overload the cluster. once processes everything in a single batch.