Implementations and comparison
Running totals in Spark Structured Streaming
Follow a grouped sum across micro-batches, then see how Spark's output modes and checkpoint affect the result a receiver sees.
Learn with an AI assistant
Copy the prompt and paste it into a chat with an AI assistant.
You are a tutor for the course "Stream Processing".Topic: "Running totals in Spark Structured Streaming"In short: Follow a grouped sum across micro-batches, then see how Spark's output modes and checkpoint affect the result a receiver sees.Topic text in Markdown: https://stream-processing-systems.github.io/implementations/running-totals-in-spark-structured-streaming.mdBase your explanations on the topic text. First ask how I want to study: a short summary, a step-by-step walkthrough, or a deep dive with questions that check my understanding. Use the text's example and terms. If you add anything the text does not say, point it out.The team wants to inspect the usage report while new files of accepted token
contributions arrive. The first file gives acme 1,400 tokens and delta
300. When a second file gives acme another 1,100, the reader should see an
updated total of 2,500. How does one query carry the earlier total forward,
and what does it publish each time it processes more input?
Keep the query running between arrivals
Section titled “Keep the query running between arrivals”A streaming DataFrame describes data with named columns whose rows keep arriving. Here the columns are the account ID and the tokens contributed by one accepted request. An upstream step has already removed repeated requests. Write each file outside the input directory and move it into place atomically once it is complete.1
This PySpark 4.1.2 excerpt uses an existing Spark session named spark.
input_dir is the directory that receives files, and checkpoint_dir is a
separate directory for the query’s recovery data.
from pyspark.sql import functions as F
usage = ( spark.readStream .schema("account_id STRING, tokens LONG") .json(input_dir))
totals = usage.groupBy("account_id").agg( F.sum("tokens").alias("total_tokens"))
query = ( totals.writeStream .outputMode("complete") .format("memory") .queryName("usage_totals") .option("checkpointLocation", checkpoint_dir) .start())readStream declares a streaming source. The grouped sum specifies what the
query maintains, just like the continuous SQL query.
start() starts the query. The in-memory sink exposes the result as a table
that the team can inspect with spark.table("usage_totals").1
Advance the same sum in micro-batches
Section titled “Advance the same sum in micro-batches”By default, Spark Structured Streaming advances a running query in micro-batches. Each micro-batch processes a portion of new input and updates the stored totals. Suppose we wait until the first file has been processed before publishing the second.2
| File just processed | New contributions | Current totals |
|---|---|---|
| First | acme 1,000 and 400, delta 300 | acme 1,400, delta 300 |
| Second | acme 600 and 500 | acme 2,500, delta 300 |
In the second micro-batch, Spark uses the earlier 1,400 and adds the new
1,100. If both files are available when Spark picks its next input, one
micro-batch could contain both. The page may see 2,500 as the first result
for acme.
An event-time window groups contributions by when they occurred. A micro-batch groups work by which input is available for a turn of execution. Either file could contain a request from yesterday. Our sum includes it as soon as its file is processed.
Choose which rows to publish
Section titled “Choose which rows to publish”Complete mode sends the whole current result table when the query
publishes a result, including delta after the second file. This works well
for inspecting a small table in memory. For a large report, sending every
account each time can make delivery expensive.1
Update mode, with a sink that supports it, would send only the rows for
account groups updated by the micro-batch. After the second file that is
acme at 2,500. A contribution of zero can also produce an update with
the same total. A usage page receiving an update replaces its existing
row for that account. Append mode is
unavailable for this unwindowed sum. Any account’s total can still change
when another contribution arrives.1
Recover the query and its destination
Section titled “Recover the query and its destination”Spark records processing progress and aggregate state in the query’s checkpoint. With checkpoint storage that survives the failure, a compatible query can resume using the accumulated totals. The inspection table lives in the running Spark process. After a restart from the checkpoint, Complete mode fills the new in-memory table when the query executes its next micro-batch. If all available files were processed before the restart, the table remains empty until another file arrives and is processed.1
If the team writes to an external database with foreachBatch, Spark can
invoke the writer again for the same batch. The callback receives a batch
ID. The writer can recognize a retry by keeping a record of completed batch
IDs for this query in the database. It must record the ID and write the
corresponding rows in the same transaction.1 This is the
safe retry problem for a
batch of result rows.
What to remember
Section titled “What to remember”- A running query carries its grouped state across micro-batches. Business time belongs in a separate windowing rule when the report needs one.
- Complete mode publishes the full result. Update mode can publish just the updated rows to a compatible sink.
- The checkpoint tracks state and progress. An external writer also needs a way to handle retries safely.
References
Section titled “References”© 2026 Grig Alex · CC BY-NC-SA 4.0
