Skip to content
Bronze 6 min read · outputMode 3 practice problems ↓

Output modes: append, update, complete

After every micro-batch, a stream has to decide which rows to write: only the new final ones, the ones that changed, or everything again. That choice is the output mode. This lesson explains the three with a scoreboard, then the rules for which one a query may use.

Step 4 · Structured Streaming · Bronze · Output modes and checkpoints, lesson 1 of 2

Read first: Structured Streaming basics · groupBy + agg (skip if you know them)

In plain words first

Think of the scoreboard at a cricket ground during a tournament. After every over, the operator can show the board in three ways:

complete

Reprint the whole table, every team, every over, even the ones that did not change.

update

Change only the lines whose scores changed in this over.

append

Add a line only when a match is finished, because only then will the score never change again.

A streaming query keeps a result table, like the scoreboard. The output mode is how much of it is written to the sinksink: Where a stream writes its results: a Delta table, files, Kafka, or your own code with foreachBatch. Learn more → after each micro-batchmicro-batch: One small round of a stream: Spark takes the data that arrived since the last round, processes it like a little batch job, and saves its progress. Learn more →.

An example: page views

A query keeps a running count of page views. After batch 0, /home has 2 views and /cart has 1. Batch 1 brings one more /home and a first /pay.

ModeBatch 0 writesBatch 1 writes
update/home 2, /cart 1/home 3, /pay 1 (only the rows that changed)
complete/home 2, /cart 1/home 3, /cart 1, /pay 1 (the whole table, again)
appendRefused for this queryA running count is never final, so there is nothing to add

Which mode a query can use

Queryappendupdatecomplete
No aggregation (select, filter, explode, join with a static table)YesYes, same as appendNo: there is no result table to repeat
Aggregation without a watermarkwatermark: In streaming, how late data may arrive. Spark uses it to know when old state can be dropped. Learn more →NoYesYes
Aggregation on event-timeevent time: When something actually happened, from the timestamp inside the event, as opposed to when Spark received it. Learn more → windows with a watermarkYes, once each window is finalYesYes, but old windows are never dropped
Session windowsYesNoYes

One idea explains the whole table. Append promises that a written row never changes. For a count or a sum, Spark can only keep that promise for a group it knows is finished, and only a watermark on an event-time window tells it that (Watermarks). Complete rewrites every group every time, so it has to keep all of them in memory forever, watermark or not: fine for a few hundred groups, a slow leak for millions.

What the sink must be able to do

  • append: the sink only ever adds rows. Every sink can do that, including plain files.
  • update: a key can arrive again with a new value, so the sink must overwrite it. Delta does that through foreachBatch with a MERGE (foreachBatch); a plain file sink cannot, and refuses update mode.
  • complete: the sink replaces everything each time. Delta supports it as an overwrite per batch; it is also handy with the memory sink in tests.

The price of append

In append mode a window appears only once the watermark has passed its end: at least one window length plus the watermark delay after it opened. Hourly windows with a 30-minute delay are written up to 90 minutes after the hour starts. If a dashboard needs numbers while the hour is still running, use update mode into a table that can take upsertsupsert: Update a row if its key already exists, insert it if not. Done with MERGE in Delta. Learn more →, and accept that a number is revised as late rowslate data: Events that arrive after newer events have already been seen, for example from a phone that was offline. Learn more → arrive.

Try it yourself

Each example says what it shows, then the output from a real run and what to notice in it, so you can follow without running anything. To try one yourself, paste it into a local Spark session, with spark already created: each builds its own data.

Goal: Run the same running count in update mode and complete mode, and compare what each batch emits.

ExplorePySpark · The same count in update and complete mode, batch by batch
import json, os

os.makedirs("lab/modes/in", exist_ok=True)


def land(name, pages):
    path = f"lab/modes/in/{name}.json"
    with open(path, "w") as f:
        f.write("\n".join(json.dumps({"page": p}) for p in pages))
    n = len(os.listdir("lab/modes/in"))          # files are read in modification order
    os.utime(path, (1_700_000_000 + n, 1_700_000_000 + n))


def show_batch(batch_df, batch_id):
    rows = sorted((r.page, r["count"]) for r in batch_df.collect())
    print(f"  batch {batch_id}: {rows}")


land("a", ["/home", "/home", "/cart"])
land("b", ["/home", "/pay"])
for mode in ["update", "complete"]:
    print(mode)
    (spark.readStream.schema("page STRING")
        .option("maxFilesPerTrigger", 1)
        .json("lab/modes/in")
        .groupBy("page").count()
        .writeStream.outputMode(mode)
        .foreachBatch(show_batch)
        .option("checkpointLocation", f"lab/modes/_chk_{mode}")
        .trigger(availableNow=True)
        .start().awaitTermination())

Output from a real run

update
  batch 0: [('/cart', 1), ('/home', 2)]
  batch 1: [('/home', 3), ('/pay', 1)]
complete
  batch 0: [('/cart', 1), ('/home', 2)]
  batch 1: [('/cart', 1), ('/home', 3), ('/pay', 1)]

What to notice:

  • Batch 1 in update mode emits only the pages that changed (/home and /pay); /cart is left out.
  • Complete mode emits the whole table every batch, /cart included.
  • Append mode is refused for this query: without a watermark, no count is ever final.

Common mistakes

  • complete mode on an aggregation with many groups — Every group stays in memory forever and the whole table is rewritten every batch.
  • update mode into a plain file sink — Refused: files cannot be updated by key. Use foreachBatch with MERGE.
  • Expecting append to show windows straight away — It writes a window only once the watermark passes it.
  • Appending an aggregation without a watermark — Refused at start: no group would ever be final.

Key takeaways

  • append: only rows that will never change; update: rows that changed; complete: the whole table.
  • Aggregations need a watermark (and windows) for append.
  • complete keeps every group in memory forever.
  • The mode decides what the sink must support: update needs upserts.

Interview prep

THE QUESTION

"Why can't you use append mode for a running count per user?"

Append writes each row exactly once and never changes it. A running count per user is never final: the next event changes it. Spark refuses append for an aggregation unless it can tell when a group is finished, which needs event-time windows and a watermark. For a running count, use update mode into a sink that can upsert (foreachBatch with MERGE), or complete mode if the number of users is small.

Avoid: "update mode writes the whole result each time". That is complete mode; update writes only the rows that changed in the batch.

Follow-ups · answer out loud, then open

Follow-up"Can you use complete mode on a windowed aggregation with a watermark?"
Yes, but the watermark then does not drop any state: complete mode has to rewrite every window each batch, so all of them stay. It suits small results only.
Scenario"Product wants hourly revenue on a dashboard while the hour is still running. Which output mode?"
Update mode, written with foreachBatch and a MERGE on the window and store, so each batch revises the running totals. Append would show an hour only after it closed plus the watermark delay.
Trap"A stream with no aggregation needs complete mode to write all its rows."
Complete is only allowed for aggregations. A select / filter query uses append, which already writes every new row once.

Check yourself

3 questions

An hourly count with a 30-minute watermark is written in append mode. When does the 10:00-11:00 window appear?

Show the answer

Once the watermark passes 11:00, so at the earliest 11:30. Append waits until the window is final: its end plus the delay.

Which mode keeps all aggregation groups in memory even with a watermark?

Show the answer

complete. Complete rewrites every group, so none can be dropped.

You need update mode into Delta. How?

Show the answer

foreachBatch with a MERGE. Upserting by key is done with MERGE inside foreachBatch.

Practise this

Problems that use this, graded on hidden tests

Keep going

Up next · Output modes and checkpoints · lesson 2 of 2 · 7 min read
Checkpoints and state stores
What a checkpoint holds, how state is partitioned and stored, RocksDB, and reading state as a table.

Related lessons

Previous: Triggers

Primary sources: Output modes