DataEng Hub
PySparkadvancedArticle · 13 min read

Structured Streaming on Databricks: Trigger Modes, Checkpoints and Exactly-Once

Which trigger mode to pick and what it costs, what actually lives in a checkpoint, and the three conditions exactly-once depends on — one of which is your code.

Balaji S.
Lead Data Engineer

TL;DR

  • Trigger mode is a cost decision wearing a latency costume. availableNow runs and stops; processingTime keeps a cluster alive; real-time mode keeps it alive and busy.
  • Trigger.Once is deprecated. It runs a single micro-batch that may ignore your rate limits, which is how a backlog becomes an out-of-memory error. Use availableNow.
  • Continuous processing mode (.trigger(continuous=...)) is not supported on Databricks. For sub-second latency the answer is real-time mode.
  • A checkpoint holds offsets, commits, query metadata and state. It is the only record of progress, it belongs to exactly one query, and changing the query's logical plan can invalidate it.
  • Exactly-once needs three things and the third is yours: a replayable source, an idempotent sink, and a checkpoint nobody shares or deletes.

The problem

NorthBridge Retail Group ran six streaming jobs. All six used the default trigger, which meant six clusters running twenty-four hours a day. Five of those jobs fed tables that were queried by a dashboard refreshed at 08:00 each morning.

The team had reasoned that streaming meant always-on, and always-on meant the default trigger. Nobody had worked out that a job whose output is read once a day can run for eleven minutes a night and sit idle the rest of the time. The compute bill for that misunderstanding was the single largest line in their Databricks spend.

The sixth job genuinely needed low latency — a fraud-scoring stream where a minute of delay was a real business cost. That one had been given the same configuration as the other five, which meant it was also wrong, just in the other direction.

Trigger mode is the lever that resolves both, and it's usually set once, by copying an example from a tutorial, and never revisited.

Key concepts

Concept What it means Why it matters here
Trigger How often the engine looks for new data and runs a micro-batch The single biggest cost control in a streaming job
Checkpoint Durable record of offsets, commits, metadata and state The only thing that makes a restart correct rather than catastrophic
Offsets / commits What was planned for a batch, and what was confirmed written Committing these with the output is what makes exactly-once work
State store Durable storage for stateful operations (aggregations, dedupe, joins) Unbounded state is the most common cause of a slowly dying stream
Idempotent sink A sink where writing the same batch twice has no extra effect Delta is one. A REST endpoint is not

Four trigger modes compared by micro-batch frequency and whether compute stays on Same query, same checkpoint, very different bills.

Step-by-step implementation

Step 1 — Pick a trigger deliberately

# Environment: Databricks Runtime 16.4 LTS, PySpark 3.5
 
# Default — processingTime with a 0 interval. Checks for data every few
# milliseconds. Almost never what you actually want.
.trigger()
 
# Fixed interval. A batch every 10 seconds; cluster stays up between batches.
.trigger(processingTime="10 seconds")
 
# Incremental batch. Drains everything available in properly sized
# micro-batches, then stops. The cheapest shape for scheduled work.
.trigger(availableNow=True)
 
# Real-time mode. Sub-second tail latency.
.trigger(realTime="5 minutes")
 
# Continuous processing — NOT supported on Databricks. Experimental in
# Spark OSS since 2.3. Use real-time mode instead.
.trigger(continuous="1 second")
Trigger Latency Compute Best for
Default (unset) A few milliseconds between checks Always on Rarely the right answer — it's a default, not a choice
processingTime Your interval Always on Steady near-real-time with a cost ceiling
availableNow Whatever your schedule is Only while running Scheduled incremental batch — most workloads
Real-time mode Under a second at the tail, often ~300 ms Always on Operational workloads where latency is the product

If I had to give one piece of advice about streaming on Databricks, it would be this: start with availableNow and a job schedule, and only move up when someone can name the person who needs lower latency. Most "streaming" requirements are actually "fresher than daily," and availableNow on an hourly schedule satisfies that at a fraction of always-on cost.

Two constraints to know before you design:

  • Trigger.Once is deprecated from Databricks Runtime 11.3 LTS onward. The reason is practical, not stylistic: Once runs exactly one micro-batch and may not honour maxFilesPerTrigger, so a large backlog goes into a single batch and falls over. availableNow splits the same backlog across multiple batches and respects your rate limits.
  • On serverless, only availableNow and once are supported, and Databricks recommends availableNow. Serverless jobs also don't support Scala, continuous mode, or time-based trigger intervals for Structured Streaming. If you need processingTime, you need classic compute. These restrictions don't apply to Lakeflow pipeline processing modes — for continuous streaming there, use a serverless pipeline in continuous mode.

Step 2 — Write the job the way it will actually run

from pyspark.sql import functions as F
 
CHECKPOINT = "/Volumes/northbridge/ops/checkpoints/silver_orders"
 
stream = (
    spark.readStream.table("northbridge.bronze.orders")
    .withWatermark("order_ts", "2 hours")
    .filter("total_amount IS NOT NULL")
    .withColumn("order_date", F.to_date("order_ts"))
)
 
query = (
    stream.writeStream
    .format("delta")
    .outputMode("append")
    .option("checkpointLocation", CHECKPOINT)   # required, and never shared
    .option("mergeSchema", "true")
    .queryName("silver_orders_ingest")          # shows up in the UI and logs
    .trigger(availableNow=True)
    .toTable("northbridge.silver.orders")
)
query.awaitTermination()

queryName costs nothing and makes the Spark UI's Structured Streaming tab navigable when six queries are running. Without it you get UUIDs, and debugging the right one becomes a guessing game.

awaitTermination() matters for availableNow in a job: without it the notebook can exit while the query is still draining, and the task reports success before the work is done.

Step 3 — Know what's inside the checkpoint

/Volumes/northbridge/ops/checkpoints/silver_orders/
├── offsets/      # what each batch was planned to read — written before the batch
├── commits/      # which batches completed — written after the output lands
├── metadata/     # the query ID; what ties this checkpoint to this query
├── sources/      # source-specific progress (e.g. Auto Loader's seen files)
└── state/        # the state store for aggregations, dedupe and stream joins

The exactly-once mechanism lives in the relationship between offsets and commits. Offsets for a batch are written before the batch runs; the commit is written after the output is durable. On restart, a batch with an offset entry and no commit entry is replayed; one with both is skipped. Exactly-once comes from committing the offsets and the output together — a batch whose commit is missing is replayed, and one whose commit is present is skipped.

Which gives you the three conditions, and makes clear that only two of them come for free:

  1. A replayable source. The source can re-serve the same records for a given offset range. Delta, Kafka and Auto Loader can. A socket source can't.
  2. An idempotent sink. Writing the same batch twice produces the same result. Delta does this through the transaction log.
  3. A checkpoint that nobody shares, moves or deletes. This one is yours.

Step 4 — Treat the checkpoint as production state

# Each query gets its own checkpoint. Always.
BASE = "/Volumes/northbridge/ops/checkpoints"
 
bronze_q = df1.writeStream.option("checkpointLocation", f"{BASE}/bronze_orders") ...
silver_q = df2.writeStream.option("checkpointLocation", f"{BASE}/silver_orders") ...

Rules that are not negotiable, learned the expensive way:

  • One checkpoint per query. Two queries sharing a checkpoint will corrupt each other's progress in ways that look like random data loss.
  • A checkpoint is not disposable. Deleting it means reprocessing from the source's beginning. That's sometimes what you want; it is never what you want by accident.
  • Changing the query's logical plan can invalidate the checkpoint. Adding a column to a select is usually fine. Changing the aggregation keys, adding or removing a stateful operation, or changing the source is usually not. Plan schema changes rather than discovering them.
  • Keep checkpoints in a governed location. A Unity Catalog volume with restricted permissions beats a DBFS path anyone can rm -rf.

Step 5 — foreachBatch for sinks that aren't Delta

def upsert_to_silver(micro_batch_df, batch_id: int):
    """Idempotent even if this batch is retried."""
    micro_batch_df.createOrReplaceTempView("updates")
    micro_batch_df.sparkSession.sql("""
        MERGE INTO northbridge.silver.orders AS t
        USING (
            SELECT * FROM (
                SELECT *, row_number() OVER (
                    PARTITION BY order_id ORDER BY order_ts DESC
                ) AS rn
                FROM updates
            ) WHERE rn = 1
        ) AS s
        ON t.order_id = s.order_id
        WHEN MATCHED AND s.order_ts > t.order_ts THEN UPDATE SET *
        WHEN NOT MATCHED THEN INSERT *
    """)
 
 
(
    stream.writeStream
    .foreachBatch(upsert_to_silver)
    .option("checkpointLocation", CHECKPOINT)
    .trigger(availableNow=True)
    .start()
)

foreachBatch gives you a normal batch DataFrame per micro-batch, which is how you do upserts, multi-table writes, and writes to systems that aren't Delta. The catch is that Structured Streaming guarantees at-least-once delivery into foreachBatch — the same batch_id can arrive twice after a failure. Your function has to be idempotent on its own.

For Delta targets, MERGE on a natural key handles that. For writes to an external system, use batch_id as a deduplication key on the receiving side. For multiple Delta writes from one batch, txnAppId and txnVersion let Delta recognise and skip a replayed write.

The deduplicating window function inside the merge is there for a specific reason: MERGE fails if the source contains multiple rows matching the same target row, and a single micro-batch frequently contains several updates to the same key. Collapsing to the latest row per key first is nearly always what you want.

Step 6 — Watch state, not just throughput

from pyspark.sql.streaming import StreamingQueryListener
 
 
class StateListener(StreamingQueryListener):
    def onQueryProgress(self, event):
        p = event.progress
        for op in p.stateOperators:
            print(
                f"{p.name} batch={p.batchId} "
                f"rows={op.numRowsTotal} "
                f"memory_mb={op.memoryUsedBytes / 1024 / 1024:.0f} "
                f"input_rate={p.inputRowsPerSecond:.0f}"
            )
 
    def onQueryStarted(self, event): pass
    def onQueryTerminated(self, event): pass
 
 
spark.streams.addListener(StateListener())

For stateful queries, numRowsTotal in the state operators is the metric that predicts failure. If it climbs steadily and never falls, your watermark either isn't set or isn't allowing state to be released, and the query will eventually die of memory exhaustion — usually weeks later, when nobody connects the crash to the design.

On Databricks, enable the RocksDB state store for anything with large state. It keeps state off the JVM heap, which trades a little latency for dramatically better behaviour at scale and far shorter garbage collection pauses.

The other number to watch is batchDuration against your trigger interval. If batches take 14 seconds on a 10-second processingTime trigger, you're permanently behind and the lag grows without bound. The fix is more parallelism, more compute, or a longer interval — but you only know to look if you're tracking it.

From production: gotchas and lessons

  1. Symptom: Six always-on clusters for jobs whose output was read once a day. Cause: The default trigger, copied from a tutorial into every job, never revisited. Fix: Five jobs moved to availableNow on an hourly schedule; the sixth, which genuinely needed latency, kept processingTime. Compute cost for that workload dropped by roughly 80%, and the one job that mattered got more attention, not less.

  2. Symptom: A job using Trigger.Once failed with an out-of-memory error after a four-day outage. Cause: Once processes a single micro-batch and may not honour maxFilesPerTrigger. Four days of backlog went into one batch. Fix: Switched to availableNow, which splits the same backlog across multiple batches with rate limits respected. The deprecation of Once exists precisely because of this failure mode.

  3. Symptom: A stream restarted after a code change and reprocessed the entire source history. Cause: A developer added a groupBy to a previously stateless query. The logical plan changed in a way the checkpoint couldn't reconcile, and the fastest-looking fix — deleting the checkpoint — did exactly what it says. Fix: Stateful changes now go to a new table with a new checkpoint, run in parallel, and get cut over once validated. Rewriting a stateful query in place is a migration, not an edit.

  4. Symptom: Duplicate rows in a downstream REST API after a cluster restart. Cause: A foreachBatch function POSTing to an external endpoint, written on the assumption that each batch_id arrives once. Delivery into foreachBatch is at-least-once. Fix: Sent batch_id as an idempotency key the API deduplicates on. Exactly-once at the sink is the sink's job when the sink isn't Delta.

  5. Symptom: A deduplication stream that ran fine for two months started failing with memory errors. Cause: dropDuplicates with no watermark. State grew by every distinct key ever seen, forever. Fix: Added withWatermark before the dedupe so state could be released, and enabled RocksDB. The general check: every stateful operation needs a watermark, and its state size should plateau rather than climb.

  6. Symptom: Two streams in the same notebook produced intermittently wrong results. Cause: Copy-paste. Both writeStream calls pointed at the same checkpointLocation. Fix: Checkpoint paths derived from the query name in a helper function, so they can't collide. A five-line helper that removes an entire class of bug.

Performance and cost notes

The biggest lever by a wide margin is trigger mode, and the question to ask about any streaming job is: who notices if this data is an hour old? If the answer is nobody, availableNow on a schedule is strictly better than always-on, with the same code and the same checkpoint.

Micro-batch sizing is the next one. maxFilesPerTrigger, maxBytesPerTrigger and maxOffsetsPerTrigger control how much work each batch takes on. Batches that are too small waste fixed per-batch overhead; too large and you risk memory pressure and long recovery after a failure. Aim for batch durations comfortably inside your trigger interval, with headroom for a backlog.

For stateful queries, RocksDB is the default choice at any real scale. Heap-based state works until it doesn't, and the failure arrives as a memory error weeks after the code that caused it shipped.

Watch out for small files. A processingTime trigger of 10 seconds writes a batch every 10 seconds, which is 8,640 commits a day and a lot of small files. Enable auto-optimise on the target table, or accept a longer trigger interval. Longer intervals are often both cheaper and faster downstream.

Finally, give every stream a job with retries and a health rule on run duration. Streaming jobs don't fail loudly — they fall behind quietly, and a latency alert catches that long before a failure notification would.

When not to use this

If you're building a standard medallion ingestion flow, a Lakeflow declarative pipeline gives you the same engine with autoscaling, data quality expectations, schema evolution handling and event log monitoring — and the checkpoint and schema location are managed for you. Databricks recommends pipelines for most production ingestion workloads, and hand-written Structured Streaming when you need maximum control and customisation. Writing writeStream by hand means owning all of that yourself, which is the right trade only when you need the control.

If your real requirement is "fresher than daily," a scheduled batch job may be simpler than anything streaming. Streaming brings checkpoints, state and restart semantics; don't take on that complexity to solve a scheduling problem.

And if you need true sub-millisecond, record-at-a-time processing with no micro-batch at all, Structured Streaming isn't the engine — even real-time mode is targeting sub-second, not sub-millisecond.

Checklist

  • Trigger mode chosen by naming who needs the latency, not by copying an example
  • No Trigger.Once anywhere in the codebase
  • Every query has its own checkpoint, derived programmatically so collisions are impossible
  • Checkpoints live in a governed location with restricted delete permissions
  • Every stateful operation has a watermark, and state size is monitored and plateaus
  • RocksDB enabled for any query with meaningful state
  • foreachBatch functions are idempotent on their own, not just because Delta is
  • queryName set so the Spark UI is readable
  • Streams run from jobs with retries and a duration health rule
  • Logical plan changes to stateful queries are treated as migrations

Practice

Further reading


#streaming#databricks#checkpoints

Keep going

One practical note a week

Get new articles, problems and guides in your inbox.