CertSafari
    Databricks Certified Associate Developer for Apache Spark· Lessons

    Domain 5 · Lesson 26/32

    Writing streaming DataFrames: readStream, writeStream, output modes and sinks

    Create and write Streaming DataFrames and Streaming Datasets, including the basic output modes and output sinks.

    18 min read
    2.5% of exam
    10 sources
    Published 21 Oct 2026
    Docs as of 17 Oct 2026

    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.

    Supplying a DDL-string schema to a streaming CSV source; printSchema() confirms the declared typespython
    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?

    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") )

    Sources1234

    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.

    DataStreamWriter methods you chain before launching a query
    MethodWhat 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
    The shortest complete loop: rate source in, console sink out, stopped by the StreamingQuery handlepython
    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.

    A file write with its own checkpoint, using the availableNow trigger to process the backlog and stoppython
    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()

    Checkpoint 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() )

    Sources564

    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.

    What each output mode writes across the two triggers of the hourly revenue example
    Output modeTrigger 1 (watermark 2:55pm)Trigger 2 (watermark 3:05pm)
    AppendNothing: both windows could still change[2pm, 3pm] $25, now final because 3:05pm is past the window's end
    UpdateBoth windows, because both changed[3pm, 4pm] $50 only, because it is the only window that changed
    CompleteAll rowsAll 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.

    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()

    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.

    Output modes accepted by the two production sinks with stated limits
    Sinkappendupdatecomplete
    Delta Lake (incl. Unity Catalog managed tables)Yes (default)No — use MERGE via foreachBatchYes — replaces the table each batch
    KafkaYesYesYes
    Appending a stream to a Delta table with toTable and a dedicated checkpointpython
    (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") with kafka.bootstrap.servers and topic options. 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 a path option. 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 with spark.sql("SELECT * FROM <name>"). queryName is 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?

    Sources7896

    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.

    A foreachBatch function that skips empty micro-batchespython
    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()

    Checkpoint 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?

    Sources10

    Sources

    (10)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 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. 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. 3.
      “A StructType object or a DDL-formatted string (for example, col0 INT, col1 DOUBLE).”
      ↩︎ Creating a streaming DataFrame with readStream
    4. 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. 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. 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. 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
      “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. 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. 9.
      “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. 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

    Spotted a mistake, or was something unclear? Tell us.