What you will be able to do
- Create a streaming DataFrame with spark.readStream and give a file source its schema
- Start a StreamingQuery with writeStream, start() or toTable(), and a checkpointLocation that belongs to that query alone
- Predict what append, update and complete modes emit on each trigger, and which modes a sink accepts
- Pick a sink (Delta, Kafka, file, console, memory) or use foreachBatch, and state the delivery guarantee each one gives
Key concept
Streaming query — A streaming DataFrame is only a description of a computation over an unbounded source. No data moves until writeStream names a sink and start() or toTable() launches a StreamingQuery, which runs until you stop it.
1.Creating a streaming DataFrame with readStream
A streaming DataFrame is an ordinary DataFrame whose input never ends. You get one from spark.readStream rather than spark.read. Everything you know about DataFrames and Datasets still applies, because a stream uses the same type over an unbounded input. You write the transformation the way you would for a static table, and the engine runs it incrementally as new rows arrive.
spark.readStream returns a DataStreamReader, and its methods match the batch reader. format() names the source, option() and options() pass source settings, and load(path) returns the streaming DataFrame. There are also shortcuts per format: json(), csv(), parquet(), orc(), text() and xml() for file streams, and table(tableName), which streams from a Delta table. The rate format generates rows by itself, which makes it a convenient way to test a pipeline with no real input.
File sources need their schema up front. In batch, reading with an explicit schema is an optimisation. In streaming, a JSON or CSV file source given no schema fails with an AnalysisException when the query starts. The fix is .schema(...) before .load(). It takes either a StructType or a DDL string such as "col0 INT, col1 DOUBLE". The other workarounds leave the problem in place. A batch-reader option like inferSchema, switching to text, or turning on multiLine does not give the stream a schema. Reading with spark.read and calling .toDF() produces a static DataFrame, not a stream.
import tempfile
with tempfile.TemporaryDirectory(prefix="schema") as d:
spark.readStream.schema("col0 INT, col1 STRING").format("csv").load(d).printSchema()
# root
# |-- col0: integer (nullable = true)
# |-- col1: string (nullable = true)A streaming DataFrame is a plan and does no work by itself. In a notebook, display() will start a streaming job. In production, the action that starts a stream should be a write to a sink, which is the job of writeStream.
Checkpoint 1 of 9· Check yourself
A streaming query reads CSV files with spark.readStream.format("csv").load(path) and no schema. When the query starts, it fails with an AnalysisException. Which change fixes it and keeps the DataFrame streaming?
A streaming file source needs its schema before it starts, and DataStreamReader.schema() takes a StructType or a DDL string. inferSchema and the text format leave the stream without a schema. spark.read gives you a static DataFrame, not a stream.
“schema(schema) | Specifies the schema of the streaming DataFrame.”Source: docs.databricks.com
Checkpoint 2 of 9· Exam question
A data engineer builds a streaming DataFrame from JSON files in cloud storage. The code below throws an AnalysisException at start time because the file source has no schema to work with. Which single change fixes the error while keeping the same file source?
raw_stream = (
spark.readStream
.format("json")
.load("/mnt/raw/events")
)
Correct answer: A — Add .schema(event_schema) before .load(), supplying an explicit StructType that matches the JSON files.
- A. File-based streaming sources require an explicit schema by default so that the query behaves consistently across restarts, and supplying a
StructTypeup front satisfies that requirement. This is the documented fix for schema errors on file sources such as JSON. - B. There is no per-source
inferSchemastreaming option that enables inference onreadStream; schema inference for streaming file sources is controlled separately and is disabled by default. Setting this option does not resolve the missing-schema error. - C. Switching to the text format changes what the source produces entirely, turning each line into a single raw string column instead of parsed JSON fields, so the pipeline would lose its structured columns rather than fixing the schema error.
- D. The
multiLineoption only controls how JSON records spanning multiple lines are parsed once a schema is known; it does not cause Spark to infer a schema for a streaming file source, so the error remains. - E.
spark.read.json(...)produces a static, non-streaming DataFrame, and.toDF()does not turn a static DataFrame into a streaming source, so this approach cannot be used to build a streaming query at all.
2.Starting a query with writeStream, start() and toTable()
df.writeStream returns a DataStreamWriter. You configure it in a chain and end the chain with a call that launches the query. Two calls launch a query. start(path) begins execution against the configured format and returns a StreamingQuery. toTable(tableName) begins execution and writes continuously to a table, and table() is an alias for it. Hold on to the returned StreamingQuery: calling stop() on it ends the stream, and awaitTermination() blocks until it finishes.
| Method | What it does |
|---|---|
| outputMode(outputMode) | How rows are written to the sink: append, complete or update |
| format(source) | Output data source format |
| option(key, value) / options(**options) | Output options for the underlying data source, including checkpointLocation and path |
| queryName(queryName) | Names the streaming query |
| trigger(**kwargs) | Sets when the query executes |
| foreach(f) / foreachBatch(func) | Hands each row, or each micro-batch, to your own code |
| start(path) / toTable(tableName) | Starts execution and returns a StreamingQuery |
import time
df = spark.readStream.format("rate").load()
df = df.selectExpr("value % 3 as v")
q = df.writeStream.format("console").start()
time.sleep(3)
q.stop()A production write needs a checkpointLocation. Checkpoints and write-ahead logs record the offsets, commits and state that let a query resume. A Parquet or Delta file write configured with only path fails at start with checkpointLocation must be specified. The fix is to add .option("checkpointLocation", ...) before .start(). Dropping outputMode, switching format, or adding a one-time trigger does not remove the requirement. Each query also needs its own location, because the checkpoint is the query's identity. If two writers share one directory, their progress collides. Pointing a query at a new or empty directory makes it start over from scratch.
transformed_df.writeStream
.trigger(availableNow=True)
.option("checkpointLocation", checkpoint_path)
.option("path", target_path)
.start()trigger() controls when the query runs, not whether it keeps state. With availableNow=True, the query processes everything that has not been processed yet and then shuts down. That suits a summary table refreshed on a schedule, where nobody needs second-level latency and an always-on cluster would be wasted money. With no trigger set, the stream keeps running. A running stream can stop auto-termination from shutting down compute, so stop queries you no longer need.
Checkpoint 3 of 9· Fill the gap
This file write uses a one-time availableNow trigger, but it still fails at start if one option is missing. Which option key completes the sample?
transformed_df.writeStream
.trigger(availableNow=True)
.option(" ? ", checkpoint_path)
.option("path", target_path)
.start()A streaming file write must set the checkpointLocation option before it starts, even with a one-time trigger such as availableNow. The checkpoint stores the offsets, commits and state that make up the query's identity, so each writer needs its own directory.
Source: docs.databricks.comCheckpoint 4 of 9· Exam question
The following streaming write fails immediately with AnalysisException: checkpointLocation must be specified. Which single change lets the query start successfully while keeping Parquet as the output format?
query = (
filtered_events.writeStream
.format("parquet")
.option("path", "/mnt/output/events")
.outputMode("append")
.start()
)
Correct answer: A — Add .option("checkpointLocation", "/mnt/checkpoints/events") before .start() so Spark can persist offsets and state for recovery.
- A. Fault-tolerant sinks such as the file sink require a
checkpointLocationso Spark can record processed offsets and any intermediate state needed to resume correctly after a restart. Adding this option is exactly what the error message asks for. - B.
appendis already the default output mode, so removing it changes nothing about the query's behavior, and the checkpoint requirement applies regardless of which output mode is configured on a fault-tolerant sink. - C. Checkpointing is a requirement of fault-tolerant sinks in general, not something unique to the Delta format; Parquet file sinks also need a checkpoint location, so switching formats does not remove the requirement.
- D. A one-time trigger still writes through a fault-tolerant sink and therefore still needs a checkpoint location to track offsets and guarantee exactly-once output; triggers do not exempt a query from checkpointing.
- E.
DataStreamWriterdoes not expose a.save()method after.start(), and the destinationpathoption is unrelated to checkpoint metadata, so this does not address the missing checkpoint location.
3.Output modes: append, update and complete
The output mode decides which result rows a query emits on each trigger. It only matters when rows can change after they are first produced, which happens in stateful queries such as aggregations. In a stateless query, such as a filter or projection, every mode behaves the same: each trigger emits the source rows it processed.
Each mode answers the question differently:
- Append (the default) emits only rows that will not change in later triggers. For an aggregation, Spark uses the watermark to decide when a row is final.
- Update emits every row that changed during this trigger, even if it may change again.
- Complete emits every row the operator has ever produced, on every trigger. It only works with streaming aggregations.
Now a second batch brings $20 at 3:20pm. The watermark moves to 3:05pm, and the [3pm, 4pm] window rises from $30 to $50. All three modes now write something different, as the table below shows.
| Output mode | Trigger 1 (watermark 2:55pm) | Trigger 2 (watermark 3:05pm) |
|---|---|---|
| Append | Nothing: both windows could still change | [2pm, 3pm] $25, now final because 3:05pm is past the window's end |
| Update | Both windows, because both changed | [3pm, 4pm] $50 only, because it is the only window that changed |
| Complete | All rows | All rows |
The choice is a trade-off between latency and how many times each row is written. Append writes each row once, but only after the watermark delay. A 1-hour watermark means at least a 1-hour wait before anything is written. That fits a notification service that must act exactly once per record. Update keeps a dashboard or a real-time feature reader fresh, but it writes once per trigger for every aggregate that changed. If the sink charges per write, that gets expensive. Complete rewrites everything each time and can perform poorly as data grows. Some operators also limit the choice: joins support only append, and output mode does not affect deduplication.
Checkpoint 5 of 9· Match them up
Three teams are each building a stateful streaming aggregation. Match each output mode to the team whose requirement it fits.
Tap a term, then the definition that fits it.
Append writes each row once, after the watermark shows it is final, so downstream code acts once per record. Update writes every row that changed in a trigger, which keeps a dashboard fresh. Complete rewrites the whole aggregation result on every trigger, so the memory table always holds every key.
“If downstream services need to take a single action for every downstream write, use append mode in most cases.”Source: docs.databricks.com
Checkpoint 6 of 9· Exam question
A team runs this streaming aggregation and then queries the in-memory result table from a notebook cell. What happens?
counts = clicks_stream.groupBy("page").count()
query = (
counts.writeStream
.queryName("page_counts")
.outputMode("complete")
.format("memory")
.start()
)
spark.sql("SELECT * FROM page_counts").show()
Correct answer: A — The SQL query returns the full, continuously updated count per page because complete mode rewrites the entire in-memory table after every micro-batch.
- A. The memory sink registers an in-memory table named after
queryName, and incompletemode Spark rewrites that table with the full Result Table after each trigger, so querying it withspark.sqlreturns the current full aggregation. This is the documented behavior for debugging aggregations with the memory sink. - B. The memory sink supports both
appendandcompleteoutput modes, andcompleteis the mode typically paired with aggregation queries on this sink, so it does not raise an exception here. - C.
queryNameonly names the in-memory table for querying; it does not override the configured output mode, and the query as written runs incompletemode, not append-only. - D. The in-memory table becomes queryable as soon as the streaming query has processed at least one trigger;
spark.sqlcan read it directly, and callingawaitTermination()is not required and would block the notebook cell instead. - E. The memory sink is explicitly documented as not fault-tolerant and does not require a
checkpointLocationto populate results; it keeps the full table in the driver's memory rather than relying on checkpoint state to return rows.
Sources7
4.Output sinks: Delta, Kafka, file, console and memory
The sink is where each trigger's output goes. Not every sink accepts every output mode, so choose the sink and the mode together. Delta Lake is the default table format behind toTable() on Databricks. It accepts append and complete but not update, so an update-mode write to a managed table fails. For update-like results in Delta, write each micro-batch with a MERGE through foreachBatch, covered in the next section. Kafka accepts all three modes.
| Sink | append | update | complete |
|---|---|---|---|
| Delta Lake (incl. Unity Catalog managed tables) | Yes (default) | No — use MERGE via foreachBatch | Yes — replaces the table each batch |
| Kafka | Yes | Yes | Yes |
(events.writeStream
.outputMode("append")
.option("checkpointLocation", "/tmp/delta/events/_checkpoints/")
.toTable("events")
)Delta gives the strongest guarantee. Its transaction log provides exactly-once semantics even when other streams or batch jobs write to the same table at the same time. Complete mode on Delta replaces the whole table after every batch, which suits a summary table such as event counts per customer. A Delta table directory can also hold the stream's checkpoint, for example under <table-name>/_checkpoints, because VACUUM skips directories whose names start with _.
The other sinks serve narrower purposes:
- Kafka:
.format("kafka")withkafka.bootstrap.serversandtopicoptions. It is the low-latency choice when the next consumer is another streaming service on a message bus. - File:
.format("parquet")or another file format plus apathoption. Writing to cloud object storage adds latency compared with a message bus. - Console:
.format("console"). You watch output while developing, as in the rate example above. - Memory: the query writes to an in-memory table named by
queryName, which you then read withspark.sql("SELECT * FROM <name>").queryNameis required for this sink.
The memory sink and the notebook display() output will run without a checkpoint. They create a temporary checkpoint location instead, and that location provides no fault tolerance or data-consistency guarantee and may not be cleaned up. Specify a checkpoint for these sinks as well, and do not use them where a restart must resume correctly.
Checkpoint 7 of 9· Check yourself
Each of these streaming writes sets its own checkpointLocation. Which one fails because the sink does not accept the output mode?
Unity Catalog managed tables are Delta tables, and Delta sinks accept only append and complete, so the update-mode write fails. Kafka accepts all three modes, and complete mode on Delta replaces the table each batch. To get update-like results in Delta, run a MERGE inside foreachBatch.
“Delta Lake, which backs all Unity Catalog managed tables, supports append and complete modes but not update mode.”Source: docs.databricks.com
5.foreachBatch: batch writers for each micro-batch
foreachBatch hands each micro-batch to your own function as an ordinary DataFrame. Inside that function you can use any batch writer. The function receives two arguments: the DataFrame holding that micro-batch's output, and the micro-batch's unique ID. Use it in three cases: the target has no streaming sink (Cassandra, for example), the operation has no incremental streaming plan, or you need a Delta MERGE. A MERGE INTO inside foreachBatch is how you write a streaming aggregation to Delta with update-mode behaviour.
def process_batch(output_df, batch_id):
# Process valid DataFrames only
if not output_df.isEmpty():
# business logic
pass
streamingDF.writeStream.foreachBatch(process_batch).start()foreachBatch gives you that freedom at the cost of a weaker guarantee. It provides at-least-once writes, so a micro-batch can be written twice after a failure. To get exactly-once, use batch_id to make the write idempotent, for example by skipping a batch ID that has already been committed. Either way, you are responsible for the end-to-end semantics. Your function must also handle an empty DataFrame. A Delta source can produce empty micro-batches, for instance when OPTIMIZE has nothing to compact, and code that assumes rows exist will fail the query.
Three more rules govern foreachBatch. First, it depends on micro-batch execution, so it does not work in continuous processing mode. There, use foreach(), which processes rows rather than whole batches. Second, writing to several sinks from one foreachBatch runs the writes one after another and adds latency to every micro-batch. Separate streaming writers parallelise better. Third, after a stateful operator such as dropDuplicatesWithinWatermark, the function must consume the entire batch DataFrame. A function that only calls show(2) leaves rows unconsumed, and the next batch fails.
Checkpoint 8 of 9· Fill the gap
The function below takes the micro-batch's output DataFrame and its unique batch ID, so it can call any batch writer. Which DataStreamWriter method hands it each micro-batch?
def process_batch(output_df, batch_id):
# Process valid DataFrames only
if not output_df.isEmpty():
# business logic
pass
streamingDF.writeStream. ? (process_batch).start()foreachBatch passes each micro-batch to your function as an ordinary DataFrame, along with the batch ID. foreach processes rows one at a time instead of whole batches, so it does not match a function that takes a DataFrame and a batch ID.
Source: docs.databricks.comCheckpoint 9 of 9· Check yourself
Your foreachBatch function MERGEs each micro-batch into a Delta table. The query fails partway through a batch and restarts from its checkpoint. What should the team expect for that batch?
foreachBatch guarantees only at-least-once writes, so a micro-batch can be written again after a failure. To get exactly-once, you have to make the write idempotent yourself with batch_id. Continuous mode is no fix either, because foreachBatch does not work there at all.
“foreachBatch() provides only at-least-once write guarantees. However, you can use the batchId provided to the function as way to deduplicate the output”Source: docs.databricks.com
Sources10
Sources
(10)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.
“Interface used to load a streaming DataFrame from external storage systems”
↩︎ Creating a streaming DataFrame with readStream“schema(schema) | Specifies the schema of the streaming DataFrame.”
↩︎ Checkpoint - 2.
“Structured Streaming lets you express computation on streaming data in the same way you express a batch computation on static data.”
↩︎ Creating a streaming DataFrame with readStream - 3.
“A StructType object or a DDL-formatted string (for example, col0 INT, col1 DOUBLE).”
↩︎ Creating a streaming DataFrame with readStream - 4.
“For most Structured Streaming use cases, the action that triggers a stream should be writing data to a sink.”
↩︎ Creating a streaming DataFrame with readStream“The availableNow setting for the trigger instructs Structured Streaming to process all previously unprocessed records from the source dataset and then shut down”
↩︎ Starting a query with writeStream, start() and toTable()“configuring a streaming read does not actually load data.”
↩︎ Prediction - 5.
“Starts the execution of the streaming query and returns a StreamingQuery object.”
↩︎ Starting a query with writeStream, start() and toTable()“Starts the execution of the streaming query and returns a StreamingQuery object.”
↩︎ Key concept - 6.
“You must specify the checkpointLocation option before you run a streaming query”
↩︎ Starting a query with writeStream, start() and toTable()“These temporary checkpoint locations do not ensure any fault tolerance or data consistency guarantees”
↩︎ Output sinks: Delta, Kafka, file, console and memory“Each query must have a different checkpoint location. Multiple queries should never share the same location.”
↩︎ Exam trap 1 - 7.
“In this mode, operators only emit rows that don't change in future triggers.”
↩︎ Output modes: append, update and complete“For stateless streaming, all output modes behave the same.”
↩︎ Output modes: append, update and complete“Joins only support the append output mode, and output mode doesn't impact deduplication.”
↩︎ Output modes: append, update and complete“Kafka supports all output modes.”
↩︎ Output sinks: Delta, Kafka, file, console and memory“Complete mode only works with streaming aggregations.”
↩︎ Exam trap 2“Delta Lake sinks support only append and complete modes, so the update output mode example fails against a managed table.”
↩︎ Exam trap 3“The streaming aggregation operator does not emit anything downstream.”
↩︎ Prediction“If downstream services need to take a single action for every downstream write, use append mode in most cases.”
↩︎ Checkpoint“Delta Lake, which backs all Unity Catalog managed tables, supports append and complete modes but not update mode.”
↩︎ Checkpoint - 8.
“The Delta Lake transaction log guarantees exactly-once processing, even when there are other streams or batch queries running concurrently against the table.”
↩︎ Output sinks: Delta, Kafka, file, console and memory - 9.https://docs.databricks.com/aws/en/spark/api-optionsOfficial docs
“The name of the in-memory table that the query writes to. Required for the memory sink.”
↩︎ Output sinks: Delta, Kafka, file, console and memory - 10.
“Functions used with foreachBatch take two parameters”
↩︎ foreachBatch: batch writers for each micro-batch“foreachBatch() might receive an empty DataFrame, and your code must handle this scenario.”
↩︎ foreachBatch: batch writers for each micro-batch“Using foreachBatch to write to multiple sinks serializes the execution of streaming writes, which can increase latency for each micro-batch.”
↩︎ foreachBatch: batch writers for each micro-batch“foreachBatch() provides only at-least-once write guarantees.”
↩︎ Exam trap 4“foreachBatch() provides only at-least-once write guarantees. However, you can use the batchId provided to the function as way to deduplicate the output”
↩︎ Checkpoint