Skip to content
Bronze 7 min read · foreachBatch 2 practice problems ↓

foreachBatch: write a stream anywhere

Spark has streaming sinks for Delta, files and Kafka, but not for everything: a Postgres table, a REST API, two tables at once. foreachBatch fills the gap. It hands each micro-batch to your own function as an ordinary DataFrame, and the batch code you already know does the rest. This lesson shows how, and the four rules that keep it correct.

Step 4 · Structured Streaming · Bronze · First streams, lesson 4 of 5

Read first: Sources and sinks (skip if you know it)

In plain words first

A delivery van brings a box of parcels to your shop every few minutes. The van does not care what you do with them: you can shelve some, send some on, and note the rest in a ledger. You just sign for each box when you are done.

With foreachBatch, 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 → is that box. Spark hands it to your function, you do whatever a normal batch job would do with it, and when your function returns, Spark signs for it in the checkpointcheckpoint: In streaming, the folder where Spark records which input it has processed and its state, so a restarted query continues where it stopped. Learn more →. If the shop burns down before you sign, the same box comes again tomorrow: that is the one rule you must plan for.

How it works

PySpark · Write each micro-batch to a Postgres table
# Spark calls this function once per micro-batch
def to_postgres(batch_df, batch_id):
    # batch_df: the rows of this batch, a normal (non-streaming) DataFrame
    # batch_id: the batch number: 0, 1, 2, ...
    (batch_df.write.format("jdbc")
        .option("url", "jdbc:postgresql://db:5432/analytics")
        .option("dbtable", "daily_clicks")
        .mode("append").save())

clicks.writeStream.foreachBatch(to_postgres) \
    .option("checkpointLocation", "s3://chk/clicks_pg/").start()

Spark calls to_postgres once per micro-batch, with that batch's rows and its number. Inside the function you are writing batch code: write, not writeStream, and any format Spark can write in batch.

Four rules

  • It is a normal DataFrame. Filter, join, aggregate, write: anything a batch job does works. To run SQL on it, register a view and use batch_df.sparkSession.sql(...), the session the batch belongs to.
  • The same batch can arrive twice. If the job crashes after your write but before Spark records the batch as done, Spark runs that batch again with the same batch_id, and the plain append above inserts the rows twice. Make the write safe to repeat: a MERGE on a key, a Delta write with txnAppId and txnVersion, or delete this batch_id's rows and insert them again in one transaction (Delivery guarantees).
  • Writing to two places? Cache first. Each write reads and computes the batch again from the sourcesource: Where a stream reads from: a Kafka topic, a folder of files, a Delta table. Learn more →. Call batch_df.persist() before the writes and batch_df.unpersist() after, so it is computed once. The lab below does exactly this.
  • Write the whole batch. Do not only call show() or limit() on it. On a statefulstateful: A query that remembers something between micro-batches, such as running counts, open windows or ids already seen. What it remembers is its state. Learn more → query (one that remembers things between batches, such as an aggregation), Spark 4.2 checks that every partitionpartition: In Kafka, one ordered slice of a topic, read in order. In Spark, one chunk of a DataFrame's rows, processed as one task. Learn more → of the batch was read, and fails with STATE_STORE_COMMIT_VALIDATION_FAILED if not.

foreachBatch or foreach?

foreachBatchforeach
You writeA function that gets a whole batch as a DataFrameA writer object with open, process (called per row) and close
Good forAnything a batch writer can do: JDBC, MERGE, several tablesDestinations with no batch writer, one row at a time
GuaranteeAt-least-onceat-least-once: No event is lost, but after a failure some can be processed or written twice. Learn more →, unless your write is safe to repeatAt-least-once

Start with foreachBatch. Reach for foreach only when no batch writer exists for the destination.

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: Use foreachBatch: write every micro-batch to two places with ordinary batch code, in a way that is safe to repeat.

Production patternPySpark · foreachBatch: each micro-batch written to two places, safe to repeat
import json, os
from pyspark.sql import functions as F

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


def land(name, rows):
    with open(f"lab/fb/in/{name}.json", "w") as f:
        f.write("\n".join(json.dumps({"user": u, "amount": a}) for u, a in rows))


def save(batch_df, batch_id):            # Spark calls this once per micro-batch
    batch_df.persist()                   # two writes below, computed once
    print(f"batch {batch_id}: {batch_df.count()} rows,",
          "streaming DataFrame?", batch_df.isStreaming)
    # each batch overwrites only its own folder, so running it again is harmless
    batch_df.write.mode("overwrite").parquet(f"lab/fb/orders/batch_id={batch_id}")
    (batch_df.groupBy("user").agg(F.sum("amount").alias("spent"))
        .write.mode("overwrite").parquet(f"lab/fb/totals/batch_id={batch_id}"))
    batch_df.unpersist()


def run():
    (spark.readStream.schema("user STRING, amount INT").json("lab/fb/in")
        .writeStream.foreachBatch(save)
        .option("checkpointLocation", "lab/fb/_chk")
        .trigger(availableNow=True)
        .start().awaitTermination())


land("1", [("ana", 10), ("bo", 5)])
run()
land("2", [("ana", 7)])
run()
spark.read.parquet("lab/fb/totals").orderBy("batch_id", "user").show()

Output from a real run

batch 0: 2 rows, streaming DataFrame? False
batch 1: 1 rows, streaming DataFrame? False
+----+-----+--------+
|user|spent|batch_id|
+----+-----+--------+
| ana|   10|       0|
|  bo|    5|       0|
| ana|    7|       1|
+----+-----+--------+

What to notice:

  • Spark called save once per micro-batch, with ids 0 and 1, and isStreaming is False: inside the function it is a normal DataFrame.
  • That is why the per-user groupBy works with no watermarkwatermark: In streaming, how late data may arrive. Spark uses it to know when old state can be dropped. Learn more →: it only sums the rows of that one batch (ana appears once per batch, not as a running total).
  • persist() before the two writes means the batch is read from the source once, not twice.
  • Each batch overwrites only its own batch_id= folder, so if Spark re-runs a batch after a crash, the result is the same, not doubled.

Common mistakes

  • A plain append inside foreachBatch — A batch that runs twice after a crash is inserted twice. MERGE on a key, or use txnAppId and txnVersion.
  • Two writes without persist() — The batch is read and computed twice, and the two writes can even see different data from a changing source.
  • Calling only show() or limit() on the batch — On a stateful query Spark 4.2 fails the batch; write the whole batch.
  • Using writeStream inside the function — batch_df is not a stream. Use the batch writer: batch_df.write.

Key takeaways

  • foreachBatch hands each micro-batch to your function as a normal DataFrame: any batch writer becomes a sink.
  • A batch can arrive twice with the same batch_id: make every write safe to repeat.
  • persist() before writing one batch to several places; unpersist() after.
  • Prefer foreachBatch; foreach is for row-by-row writers when no batch writer exists.

Interview prep

THE QUESTION

"You need to write a stream into a Postgres table. How, and what can go wrong?"

There is no streaming JDBC sink, so foreachBatch: each micro-batch arrives as a normal DataFrame and is written with the JDBC writer. The risk is duplicates: if the job crashes after the insert but before Spark records the batch, the batch runs again with the same batch_id. So the write must be safe to repeat: an upsert on a unique key (INSERT ... ON CONFLICT), or delete the rows tagged with this batch_id and insert them again in one transaction. I would also persist the batch if it is written to more than one place, and size batches with maxOffsetsPerTrigger so each JDBC write stays reasonable.

Avoid: "just append each batch in foreachBatch" without saying that a batch can run twice after a crash, and how the write survives that.

Follow-ups · answer out loud, then open

Follow-up"Why call persist() inside foreachBatch?"
Every write is a separate action, and each action computes the batch again from the source. Writing one batch to two tables without persist() reads and transforms it twice, which costs time and can even give the two writes different data if the source changes. persist() before the writes and unpersist() after.
Scenario"A foreachBatch function writes to two tables, and the second write fails. What happens on restart, and how do you make it safe?"
The batch was never marked done, so Spark runs the whole function again with the same batch_id, including the first write, which already succeeded. Both writes must be safe to repeat: a Delta write with txnAppId and txnVersion set to the batch id, or a MERGE on a key, so the repeated first write changes nothing.
Trap"foreachBatch is exactly-once because the query has a checkpoint."
The checkpoint makes Spark re-run an unfinished batch, which is exactly why a batch can be written twice. The Spark docs call foreachBatch at-least-once by default; it becomes exactly-once only when your write uses the batch id to skip or overwrite a repeat.

Check yourself

3 questions

Inside foreachBatch, what is batch_df?

Show the answer

A normal DataFrame with this batch's rows. It is a batch DataFrame, so batch writers work on it.

The job crashes after your foreachBatch insert but before the batch is marked done. What happens on restart?

Show the answer

The batch runs again with the same batch_id. An unfinished batch is re-run on the same input, so the write must be safe to repeat.

Why call persist() before writing a batch to two tables?

Show the answer

Otherwise the batch is computed twice, once per write. Each write is a separate action that would recompute the batch.

Practise this

Interview problems on streaming, graded on hidden tests

Keep going

Up next · First streams · lesson 5 of 5 · 7 min read
Triggers
When micro-batches run, what happens when one overruns, and availableNow for scheduled incremental jobs.

Related lessons

Previous: Sources and sinks

Primary sources: Using foreach and foreachBatch