Structured Streaming
Use checkpoints, triggers, watermarks, and output modes to control incremental processing and recovery.
The model
Write a query as if over a static table. Spark runs it repeatedly in micro-batches over new input only. Progress (which input has been processed) is stored in a checkpoint directory, which makes the stream fault tolerant: after a failure or restart it resumes where it stopped.
(spark.readStream.table("main.bronze.events") # Delta table as a streaming source
.filter("event_type IS NOT NULL")
.writeStream
.option("checkpointLocation", "/Volumes/main/chk/silver_events")
.outputMode("append")
.trigger(availableNow=True)
.toTable("main.silver.events"))
Sources and sinks
- Sources: Delta tables, Auto Loader (
cloudFiles), Kafka, Kinesis, Event Hubs (Kafka API), Pub/Sub, rate (testing). - Sinks: Delta tables (
toTable), Kafka,foreachBatch(run any batch code, e.g. a MERGE, per micro-batch), memory/console (testing). - A Delta table used as a streaming source must be append-only. Updates or deletes in the source break the stream unless you set
skipChangeCommits(or read its change data feed).
Output modes
| Mode | Writes | Use with |
|---|---|---|
| append (default) | Only new rows | Non-aggregated streams; aggregations with a watermark |
| complete | The whole result table every trigger | Aggregations (rewrites everything) |
| update | Only rows changed since last trigger | Aggregations into sinks that support upserts (e.g. via foreachBatch) |
Triggers
The trigger decides when a micro-batch runs, and whether the stream stops or keeps running.
| Trigger | Behavior |
|---|---|
| Default (none) | Next micro-batch starts as soon as the previous finishes (about every 500 ms when idle) |
processingTime="1 minute" | Micro-batch at fixed intervals; continuous running |
availableNow=True | Process all available data in one or more batches, then stop. Incremental batch. Ideal on a schedule with job compute. |
once=True | Deprecated: single batch of all data. Use availableNow. |
continuous="1 second" | Apache Spark continuous processing, unsupported on Databricks. See the Databricks trigger reference for supported intervals. |
Triggered vs continuous
These triggers give two ways to run a pipeline:
| Triggered | Continuous | |
|---|---|---|
| Execution | Processes available data, then stops; runs on a schedule | Keeps running and processes data as it arrives |
| Latency | Higher, depends on the schedule | Low, near real time |
| Cost | Lower: compute starts and stops | Higher: compute always on |
| Typical use | Batch loads, periodic reports | Real-time dashboards, alerts |
| Streaming trigger | availableNow=True (or a schedule) | Default or processingTime micro-batches |
A continuous pipeline still uses micro-batches. The Lakeflow continuous scheduling setting controls when the work runs. See the Structured Streaming trigger reference for the supported query settings.
Exactly-once and checkpoints
- Exactly-once end-to-end requires a replayable source, a checkpoint, and an idempotent sink such as the Delta streaming sink. In
foreachBatch, a batch can be retried. Make the sink write idempotent using the batch ID or a deterministic keyed merge. - Each stream must have its own checkpoint location. Deleting the checkpoint makes the stream start over from the beginning.
- Changing a query's logic significantly may need a new checkpoint.
Watermarks and stateful operations
(events.withWatermark("event_time", "10 minutes")
.groupBy(F.window("event_time", "5 minutes"), "device_id")
.count())
Aggregations, joins and dropDuplicates on streams keep state. A watermark tells Spark how late data can arrive, so old state can be dropped and append mode can emit finished windows. Data inside the delay bound is guaranteed to be considered. Records beyond that delay can be dropped once the relevant state has been evicted.
Monitoring a stream
query.status, query.lastProgress (rows per second, batch duration), query.stop(), query.awaitTermination(). In a notebook, display() on a streaming DataFrame shows a live dashboard. The Spark UI has a Structured Streaming tab.
Trace recovery
A Delta streaming sink has committed a batch. The process stops before the next trigger. Explain what must survive the restart, and why a foreachBatch call to an external API needs an additional safeguard.
Check your reasoning
Retain the checkpoint and target. The native Delta streaming sink can recognize committed writes. An external API call can be retried, so send an idempotency key or record processed batch IDs.
Product reference
Structured Streaming concepts in the Databricks documentation
Structured Streaming quiz
Answer 5 questions. Check each answer for an explanation.