What you will be able to do
- Describe how Structured Streaming treats a stream as an unbounded table queried with batch logic and executed incrementally
- Choose between the default, processingTime and availableNow triggers, and explain why once is deprecated
- Explain what a checkpoint location stores and which query changes are allowed when a query restarts from it
- Identify the conditions behind exactly-once guarantees and where those guarantees stop
Key concept
Incremental query over an unbounded table — In Structured Streaming you write an ordinary batch-style query over a table that keeps growing, and the engine runs it again and again on just the new rows, adding them to the result instead of recomputing everything.
1.A stream is a table that keeps growing
Structured Streaming is Spark's engine for near real-time processing, and it adds no separate streaming API to learn. You write a query with the same DataFrame and SQL operations you use on static data, and the engine runs it incrementally. Each time new data arrives, the engine updates the result rather than recomputing it from the start.
To make this work, the engine treats every source as an unbounded table. Records from a Kafka topic or files landing in a directory become new rows appended to that table. Your query is a standing definition over the whole table, and each run of the engine processes only the rows added since the last run. The source is never overwritten in place, and it is not reloaded in full on every run: the engine keeps track of how far it has read.
Because the table is infinite, a few batch operations have no streaming equivalent. Sorting a whole stream is the usual example, since the engine would have to sort rows that have not arrived yet. Most other transformations carry over unchanged: select, filters, built-in functions such as current_timestamp(), and even model inference wrapped as a UDF.
Defining a stream is lazy, as a batch read is. spark.readStream builds a streaming DataFrame but reads nothing. The stream starts only when an action begins it, and in production that action is normally writing to a sink.
Streaming queries come in two kinds. A stateless query, such as a projection or filter, handles each row independently and forgets it once it has been emitted. A stateful query, such as an aggregation, a stream-stream join or deduplication, keeps intermediate results that carry over from one run to the next. How that state is stored is covered in Stateful operators and the StateStore. The distinction matters here because state is one more thing the engine has to recover after a restart.
Checkpoint 1 of 9· Check yourself
A team defines a streaming query with select and a filter over a Kafka topic, using the same DataFrame code they use for batch jobs. When a new set of records lands on the topic, what does the Structured Streaming engine do?
The engine treats the source as an unbounded table that only grows. It keeps track of how far it has read, processes just the newly appended rows with the ordinary batch-style query, and updates the result. It does not reload or overwrite the source, and it needs no separate streaming API.
“The Structured Streaming engine performs the computation incrementally and continuously updates the result as streaming data arrives.”Source: docs.databricks.com
Checkpoint 2 of 9· Exam question
In Spark Structured Streaming's programming model, how does the engine conceptually treat a streaming data source?
Correct answer: A — As a table that is continuously appended to, where each new batch of data is treated as new rows added to an unbounded input table
- A. This is correct: Structured Streaming models a data stream as an unbounded input table that grows with each arriving batch, and queries are expressed as if run against that table, which lets the same DataFrame/Dataset API work for both batch and streaming.
- B. This is incorrect because the engine does not overwrite prior data in place; new data is appended to the conceptual input table rather than replacing what came before it.
- C. This is incorrect because Structured Streaming's execution model is not built on merging independent RDD checkpoints at query completion; it incrementally updates a result table on each trigger.
- D. This is incorrect because the engine tracks incremental offsets from the source rather than reloading the entire dataset from disk on every trigger.
2.Micro-batches and the trigger that schedules them
The engine does not handle records one at a time. It collects new rows into a micro-batch, runs the query on that batch as a small batch job, and then checks for more data. The trigger, set with .trigger(...) on writeStream, decides when each check happens.
| Trigger | Syntax (Python) | Behaviour | Use it when |
|---|---|---|---|
| Unspecified (default) | none | Equivalent to processingTime with a 0 ms interval; the next micro-batch is planned as soon as the previous one finishes, for as long as data arrives | General-purpose streaming where latency matters more than cost |
| Processing time | .trigger(processingTime='10 seconds') | Fixed-interval micro-batches; checks for new data once per interval | You want to cut overhead by checking less often |
| Available now | .trigger(availableNow=True) | Processes everything unprocessed at start time, possibly in several batches, then stops | Scheduled incremental batch jobs, such as hourly or nightly |
| Once | Trigger.Once | Deprecated; replaced by availableNow | Not for new work |
| Continuous | .trigger(continuous='1 second') | Experimental since Spark 2.3 | Not recommended |
If you leave out the trigger, the query does not sit idle and does not switch to continuous mode. Spark sets processingTime with an interval of 0, so a new micro-batch begins as soon as the previous one finishes. That gives the lowest latency the micro-batch engine can offer. Against cloud object storage, though, checking every few milliseconds can generate a large number of storage API calls and an unexpected bill. A processingTime interval such as '10 seconds' trades a little latency for far fewer checks. Set it from how fast data arrives and how fresh the results must be.
availableNow is the trigger for jobs that run on a schedule. It reads everything the source holds when the job starts, still respects rate limits such as maxBytesPerTrigger, and then shuts down. The older Trigger.Once did the same job in a single batch and is now deprecated in favour of availableNow. Because both stop on their own, you can run the same code every hour and each run picks up only what arrived since the last one.
transformed_df.writeStream
.trigger(availableNow=True)
.option("checkpointLocation", checkpoint_path)
.option("path", target_path)
.start()Checkpoint 3 of 9· Fill the gap
This write runs as an hourly scheduled job. It must process everything that arrived since the last run, respect batch-size limits, and then shut down. Which trigger keyword completes it?
transformed_df.writeStream
.trigger( ? =True)
.option("checkpointLocation", checkpoint_path)
.option("path", target_path)
.start()availableNow processes all unprocessed records, possibly over several batches that respect options such as maxBytesPerTrigger, and then stops. That makes it the trigger for scheduled incremental batch jobs. once did the same job but is deprecated, processingTime keeps the stream running, and continuous is experimental and not recommended.
Source: docs.databricks.comCheckpoint 4 of 9· Check yourself
A streaming job that reads from cloud object storage was deployed without any .trigger(...) call, and the storage API bill has risen sharply. What is causing this, and which change addresses it?
Leaving out the trigger is equivalent to processingTime with a 0 interval. A new micro-batch is planned as soon as the previous one ends, and checking that often can generate a large number of storage API calls. A processingTime interval adds a little latency in exchange for far fewer checks.
“By default, if you don't set a trigger mode, Structured Streaming sets the trigger mode to processingTime and the interval to 0”Source: docs.databricks.com
Checkpoint 5 of 9· Exam question
A data engineer starts the following streaming query without specifying a .trigger(...) clause:
query = (streamingDF.writeStream
.format("console")
.outputMode("append")
.start())
Which best describes how Spark schedules micro-batches for this query?
Correct answer: A — Spark uses the default micro-batch trigger, immediately starting the next micro-batch as soon as the previous one finishes processing
- A. This is correct: when no trigger is specified, Spark uses the default micro-batch trigger, which starts a new batch as soon as the prior one finishes, giving the lowest latency the micro-batch engine can offer without explicit tuning.
- B. This is incorrect because continuous processing is an experimental, opt-in execution mode requiring
.trigger(continuous=...); omitting a trigger does not switch the engine into that mode. - C. This is incorrect because the absence of a trigger clause does not pause the query; Spark falls back to its default trigger behavior rather than waiting for configuration.
- D. This is incorrect because processing a single batch and stopping is the behavior of a one-time trigger such as
Trigger.Once(), not the default trigger that is used when no trigger is specified.
3.Checkpoints: what a restarted query remembers
A batch job that loses an executor rebuilds the lost partitions from their lineage, as covered in Fault tolerance through lineage recomputation. A stream needs more than that. When the driver itself restarts, the query has to know which source offsets it already read, which batches reached the sink, and what its aggregations held. None of that can be rebuilt from lineage, so Structured Streaming writes it to durable storage as a checkpoint, alongside a write-ahead log.
A checkpoint directory holds four kinds of record:
- Offsets: the source offsets each micro-batch processed, so the query resumes exactly where it stopped.
- Commits: which micro-batches have been committed to the sink.
- State: for stateful queries, the operator metadata, the state schema and the state store contents.
- Metadata: the unique query ID. Configuration settings are stored in the offset log.
State is restored from the checkpoint, not from memory. That is why a stateful query survives a cluster restart: its running counts are read back from fault-tolerant storage such as S3 or Azure Blob storage, and executor memory plays no part. Caching a streaming DataFrame does nothing for recovery.
(df.writeStream
.option("checkpointLocation", "/Volumes/catalog/schema/volume/path")
.toTable("catalog.schema.table")
)The checkpoint is the query's identity, so each query needs its own location and two queries must never share one. The memory sink and notebook display() will create a temporary checkpoint if you leave the option out. Those temporary locations give no fault tolerance or consistency guarantees, so set a real location there too.
Restarting from an existing checkpoint only works if the new query still matches what the checkpoint recorded. Sources are identified by their position in the query plan. Saved state also assumes the same schema. Changes that leave those intact are generally fine. Changes that break them need a new checkpoint, or the restarted query may fail with unpredictable errors.
| Change | Same checkpoint? |
|---|---|
| Add or remove a filter | Allowed |
| Add, remove or change a rate limit such as maxOffsetsPerTrigger | Allowed |
| Change the trigger interval | Allowed; applies from the first new batch |
| Change the number or type of input sources | Not allowed by default |
| Subscribe to a different Kafka topic | Generally not allowed; results are unpredictable |
| Change grouping keys or aggregates of a streaming aggregation | Not allowed |
| Change the key columns of dropDuplicates | Not allowed |
| Change the sink from file to Kafka | Allowed; Kafka sees only new data |
| Change the sink from Kafka to file | Not allowed |
Checkpoint 6 of 9· Match them up
Match each part of a checkpoint directory to what it lets a restarted query recover.
Tap a term, then the definition that fits it.
A restarted query cannot rebuild these from lineage, so the checkpoint stores them in durable storage. Offsets say where to resume reading, commits say which batches reached the sink, state restores stateful operators, and metadata identifies the query. Configuration settings are kept in the offset log.
“Offsets: The source offsets processed in each micro-batch. This allows the query to resume from exactly where it left off without reprocessing data.”Source: docs.databricks.com
Checkpoint 7 of 9· Check yourself
Four edits are proposed for a running stateful query that writes to Kafka. Which one can be deployed while restarting from the existing checkpoint location?
Adding or removing a filter leaves the sources and the saved state schema unchanged, so the query can restart from the same checkpoint. Changing grouping keys or dropDuplicates keys changes the state schema, and a Kafka-to-file sink change is not allowed. All three of those need a new checkpoint.
“Changes that are generally safe include adding or removing filters, changing rate limits, trigger intervals”Source: docs.databricks.com
Sources4
4.How exactly-once is achieved, and where it stops
Exactly-once means every record affects the result as if it had been processed one time, even when batches are retried. At-least-once guarantees that no record is lost, but a retry can apply the same record twice. Structured Streaming offers exactly-once from source to sink, and that guarantee rests on three parts working together.
The three parts are:
- A replayable source. The offset log records the exact range each micro-batch read. After a failure, the batch that was planned but not finished runs again over that same range, so the source must be able to serve it again. Kafka offsets and Delta table versions can do that.
- Checkpointed offsets and commits. Offsets say what each batch read. Commits say which batches reached the sink. Together they tell a restarted query exactly which batch to redo.
- An idempotent sink. Writing the same batch twice must leave the same result as writing it once. Delta Lake does this by committing a micro-batch's offsets and its output in one transaction. A retried batch either succeeds in full or is rolled back and retried. It is never applied partly, and never applied twice.
Several things look like guarantees but are not. Running on a single executor, calling cache(), and choosing outputMode("complete") have nothing to do with exactly-once. Output mode only controls which rows a stateful aggregation emits. Recovery comes from the checkpoint and the sink, never from memory.
The engine also refuses to skip a failed batch. If a batch failed because it ran out of memory, changing the trigger will not get the query past it: that same batch has to complete first. Scaling up the compute is the usual fix. In rare cases you have to restart the stream with a new checkpoint.
The guarantee ends at the edges of the query. It covers how each offset is read and how each batch is committed. It does not cover the content of the data. If an at-least-once producer sends the same event twice, the stream sees two distinct records and writes both, and removing those duplicates is your job. On the output side, a sink with no idempotent commit, such as a custom foreachBatch write, gets at-least-once unless you make the write itself safe to repeat.
Checkpoint 8 of 9· Check yourself
Upstream of a streaming query, a Kafka producer with at-least-once delivery retries a send and publishes the same order event twice. The query reads the topic with a checkpoint and writes to a Delta table. What ends up in the table?
Exactly-once covers how offsets are read and how batches are committed, not what the data contains. A duplicate sent by the producer sits at its own offset, so the engine treats it as a separate record and writes it. You have to deduplicate it yourself.
“If an at-least-once source sends the same record multiple times, the pipeline processes them as unique records, and writes all of them to your table.”Source: docs.databricks.com
Checkpoint 9 of 9· Exam question
A team is designing a Structured Streaming pipeline that must guarantee exactly-once end-to-end processing semantics, from source to sink, even if the driver restarts mid-query. Which two conditions are both required to achieve this guarantee? (Choose 2 answers)(Select 2)
Correct answers: A, B — The source must be replayable, so the engine can re-read the same data range identified by a recorded offset after a failure; The sink must be idempotent or support deterministic writes, so reapplying the same micro-batch output does not create duplicate records
- A. This is correct: a replayable source lets Structured Streaming re-read exactly the offset range of a failed or incomplete micro-batch after recovery, which is a prerequisite for reproducing identical output.
- B. This is correct: because the engine can re-execute a micro-batch after a failure, the sink must tolerate that reapplication without duplicating records, which is why idempotent or deterministic sink writes are required.
- C. This is incorrect because exactly-once semantics do not depend on cluster topology; multi-executor clusters with shuffles are fully compatible with exactly-once guarantees when checkpointing and idempotent sinks are used.
- D. This is incorrect because output mode choice is unrelated to exactly-once guarantees; append and update modes can also achieve exactly-once semantics when paired with a replayable source and an idempotent sink.
- E. This is incorrect because
cache()persists data in executor memory for reuse within a single run and provides no durability across a driver restart, so it does not contribute to exactly-once recovery.
Sources
(7)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.
“The Structured Streaming engine performs the computation incrementally and continuously updates the result as streaming data arrives.”
↩︎ A stream is a table that keeps growing“Stateless queries process rows without retaining state. Stateful queries maintain intermediate state for aggregations, joins, and deduplication.”
↩︎ A stream is a table that keeps growing“Structured Streaming lets you express computation on streaming data in the same way you express a batch computation on static data.”
↩︎ Key concept - 2.
“Structured Streaming treats data sources as unbounded or infinite datasets.”
↩︎ A stream is a table that keeps growing“some transformations are not supported in Structured Streaming workloads because they would require sorting an infinite number of items.”
↩︎ A stream is a table that keeps growing“configuring a streaming read does not actually load data. You must trigger an action on the data before the stream begins.”
↩︎ A stream is a table that keeps growing“process all previously unprocessed records from the source dataset and then shut down”
↩︎ Micro-batches and the trigger that schedules them - 3.
“Equivalent to processingTime trigger with 0 ms intervals. Stream processing runs continuously as long as new data arrives.”
↩︎ Micro-batches and the trigger that schedules them“By default, if you don't set a trigger mode, Structured Streaming sets the trigger mode to processingTime and the interval to 0”
↩︎ Micro-batches and the trigger that schedules them“This can generate a high volume of cloud storage API calls per day and result in unexpected charges from your cloud provider.”
↩︎ Micro-batches and the trigger that schedules them“The configuration of this interval determines how often the system performs checks to see if new data has arrived.”
↩︎ Micro-batches and the trigger that schedules them“This mode has been classified as experimental since Spark 2.3.”
↩︎ Micro-batches and the trigger that schedules them“The previous unsuccessful batch must complete because Structured Streaming requires idempotent micro-batches.”
↩︎ How exactly-once is achieved, and where it stops“In Databricks Runtime 11.3 LTS and above, Trigger.Once is deprecated. Use Trigger.AvailableNow for all incremental batch processing workloads.”
↩︎ Exam trap 1 - 4.
“Checkpoints and write-ahead logs work together to provide processing guarantees for Structured Streaming workloads.”
↩︎ Checkpoints: what a restarted query remembers“Offsets: The source offsets processed in each micro-batch. This allows the query to resume from exactly where it left off without reprocessing data.”
↩︎ Checkpoints: what a restarted query remembers“Structured Streaming automatically checkpoints the state data to fault-tolerant storage (for example, DBFS, AWS S3, Azure Blob storage) and restores it after restart.”
↩︎ Checkpoints: what a restarted query remembers“Each query must have a different checkpoint location. Multiple queries should never share the same location.”
↩︎ Checkpoints: what a restarted query remembers“Structured Streaming identifies sources by their position in the query plan.”
↩︎ Checkpoints: what a restarted query remembers“Changes that are generally safe include adding or removing filters, changing rate limits, trigger intervals”
↩︎ Checkpoints: what a restarted query remembers“File sink to Kafka sink is allowed. Kafka will see only the new data. Kafka sink to file sink is not allowed.”
↩︎ Checkpoints: what a restarted query remembers“Commits: A record of which micro-batches have been committed to the sink, enabling exactly-once semantics.”
↩︎ How exactly-once is achieved, and where it stops“These temporary checkpoint locations do not ensure any fault tolerance or data consistency guarantees and might not get cleaned up properly.”
↩︎ Exam trap 2“any changes (that is, additions, deletions, or schema modifications) to the stateful operations of a streaming query are not allowed between restarts.”
↩︎ Exam trap 3“When you delete the files in a checkpoint directory or change to a new checkpoint location, the next run of the query begins fresh.”
↩︎ Prediction - 5.
“Exactly-once processing guarantees every record affects the result as if it were processed precisely one time, even across retries”
↩︎ How exactly-once is achieved, and where it stops“each micro-batch commits its source offsets and its output together”
↩︎ How exactly-once is achieved, and where it stops“If an at-least-once source sends the same record multiple times, the pipeline processes them as unique records”
↩︎ Exam trap 4“If an at-least-once source sends the same record multiple times, the pipeline processes them as unique records, and writes all of them to your table.”
↩︎ Checkpoint - 6.
“When a query restarts, the micro-batch planned during the previous run processes.”
↩︎ How exactly-once is achieved, and where it stops“Some operations like foreachBatch provide at-least-once rather than exactly-once guarantees. For these operations, make sure that your processing pipeline is idempotent.”
↩︎ Prediction - 7.
“Only stateful streams containing aggregations require an output mode configuration.”
↩︎ How exactly-once is achieved, and where it stops