<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
	<id>https://openlakehouse.io/w/index.php?action=history&amp;feed=atom&amp;title=ForeachBatch</id>
	<title>ForeachBatch - Revision history</title>
	<link rel="self" type="application/atom+xml" href="https://openlakehouse.io/w/index.php?action=history&amp;feed=atom&amp;title=ForeachBatch"/>
	<link rel="alternate" type="text/html" href="https://openlakehouse.io/w/index.php?title=ForeachBatch&amp;action=history"/>
	<updated>2026-12-06T00:08:01Z</updated>
	<subtitle>Revision history for this page on the wiki</subtitle>
	<generator>MediaWiki 1.43.11</generator>
	<entry>
		<id>https://openlakehouse.io/w/index.php?title=ForeachBatch&amp;diff=149&amp;oldid=prev</id>
		<title>Open Lakehouse Wiki sync: Sync from open-lakehouse/wiki@7c9abaa</title>
		<link rel="alternate" type="text/html" href="https://openlakehouse.io/w/index.php?title=ForeachBatch&amp;diff=149&amp;oldid=prev"/>
		<updated>2026-11-25T00:52:42Z</updated>

		<summary type="html">&lt;p&gt;Sync from open-lakehouse/wiki@7c9abaa&lt;/p&gt;
&lt;p&gt;&lt;b&gt;New page&lt;/b&gt;&lt;/p&gt;&lt;div&gt;{{DISPLAYTITLE:foreachBatch}}&lt;br /&gt;
{{Infobox concept&lt;br /&gt;
| name            = foreachBatch&lt;br /&gt;
| also_known_as   = &amp;lt;code&amp;gt;DataStreamWriter.foreachBatch&amp;lt;/code&amp;gt;&lt;br /&gt;
| field           = [[Stream processing]]&lt;br /&gt;
| introduced      = Apache Spark 2.4.0&lt;br /&gt;
| key_parts       = User function called once per micro-batch with the batch DataFrame and the batch id&lt;br /&gt;
| implementations = [[Structured Streaming]] in [[Apache Spark]] (Scala, Java, Python; Spark Connect since 3.5.0)&lt;br /&gt;
| related         = [[Output mode]], [[Exactly-once semantics]], [[Delta Lake]], [[Streaming checkpoint]]&lt;br /&gt;
}}&lt;br /&gt;
{{Verified|2026-11-23|the Spark 4.3.0 Structured Streaming programming guide (Using Foreach and ForeachBatch) and Real-time Mode guide, &amp;lt;code&amp;gt;python/pyspark/sql/streaming/readwriter.py&amp;lt;/code&amp;gt; at tag v4.3.0 of apache/spark, SPARK-24565, the Delta Lake table streaming and merge documentation, and the Databricks foreachBatch page}}&lt;br /&gt;
&lt;br /&gt;
In [[Apache Spark]] [[Structured Streaming]], &amp;#039;&amp;#039;&amp;#039;foreachBatch&amp;#039;&amp;#039;&amp;#039; is a sink that calls a user function once for every micro-batch, passing the batch&amp;#039;s output as an ordinary DataFrame together with a unique batch id, so that any batch API can be used to write it. It is the standard way to write a stream to a system that has a batch writer but no streaming sink, to write one batch to several places, and to apply row-level upserts, such as a [[Delta Lake]] &amp;lt;code&amp;gt;MERGE&amp;lt;/code&amp;gt;, from a streaming query. foreachBatch was added in Spark 2.4.0 and is available in Scala, Java and Python.&amp;lt;ref name=&amp;quot;ss-fb&amp;quot;&amp;gt;{{Cite web |url=https://spark.apache.org/docs/4.3.0/streaming/apis-on-dataframes-and-datasets.html#foreachbatch |title=Structured Streaming: ForeachBatch (Spark 4.3.0) |publisher=Apache Software Foundation |access-date=2026-11-23}}&amp;lt;/ref&amp;gt;&amp;lt;ref name=&amp;quot;jira&amp;quot;&amp;gt;{{Cite web |url=https://issues.apache.org/jira/browse/SPARK-24565 |title=SPARK-24565: Add API for in Structured Streaming for exposing output rows of each microbatch as a DataFrame |publisher=Apache Software Foundation JIRA |access-date=2026-11-23}}&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== How does foreachBatch work? ==&lt;br /&gt;
The function takes two arguments: a DataFrame with the micro-batch&amp;#039;s output, and the batch id.&amp;lt;ref name=&amp;quot;ss-fb&amp;quot; /&amp;gt; Inside it, the DataFrame is a batch DataFrame, so every batch operation and writer works, including operations that streaming DataFrames do not support.&amp;lt;ref name=&amp;quot;ss-fb&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
def write_batch(batch_df, batch_id):&lt;br /&gt;
    batch_df.write.format(&amp;quot;jdbc&amp;quot;).options(**jdbc_options).mode(&amp;quot;append&amp;quot;).save()&lt;br /&gt;
&lt;br /&gt;
(stream_df.writeStream&lt;br /&gt;
    .foreachBatch(write_batch)&lt;br /&gt;
    .option(&amp;quot;checkpointLocation&amp;quot;, &amp;quot;/checkpoints/to_jdbc&amp;quot;)&lt;br /&gt;
    .start())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
foreachBatch works only in micro-batch execution. It does not work with the continuous trigger, where &amp;lt;code&amp;gt;foreach&amp;lt;/code&amp;gt; is the alternative, and it is not supported in Real-time Mode, which processes records one at a time.&amp;lt;ref name=&amp;quot;ss-fb&amp;quot; /&amp;gt;&amp;lt;ref name=&amp;quot;rtm&amp;quot;&amp;gt;{{Cite web |url=https://spark.apache.org/docs/4.3.0/streaming/real-time-mode.html |title=Real-time Mode (Spark 4.3.0) |publisher=Apache Software Foundation |access-date=2026-11-23}}&amp;lt;/ref&amp;gt; The &amp;lt;code&amp;gt;foreach&amp;lt;/code&amp;gt; sink, also available since Spark 2.4 in Python, calls user code per row through &amp;lt;code&amp;gt;open&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;process&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;close&amp;lt;/code&amp;gt; methods.&amp;lt;ref name=&amp;quot;ss-fb&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
foreachBatch has supported Spark Connect since Spark 3.5.0. In Spark Connect mode it behaves differently: the function does not have access to variables defined outside it.&amp;lt;ref name=&amp;quot;rw&amp;quot;&amp;gt;{{Cite web |url=https://github.com/apache/spark/blob/v4.3.0/python/pyspark/sql/streaming/readwriter.py |title=python/pyspark/sql/streaming/readwriter.py (Apache Spark v4.3.0) |publisher=Apache Software Foundation |access-date=2026-11-23}}&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Is foreachBatch exactly-once? ==&lt;br /&gt;
By default, foreachBatch gives only at-least-once write guarantees. If a query fails after the function has written a batch but before the batch is recorded in the commit log, the batch runs again after restart. The batch id makes exactly-once possible: the function can use it to detect and skip a batch that was already written.&amp;lt;ref name=&amp;quot;ss-fb&amp;quot; /&amp;gt; For the same batch id, the output DataFrame is guaranteed to be the same, provided every operation in the query is deterministic.&amp;lt;ref name=&amp;quot;rw&amp;quot; /&amp;gt; See [[Exactly-once semantics]] and [[Streaming checkpoint]].&lt;br /&gt;
&lt;br /&gt;
=== Idempotent writes to Delta Lake ===&lt;br /&gt;
Delta Lake supports this directly. The writer options &amp;lt;code&amp;gt;txnAppId&amp;lt;/code&amp;gt; (any unique string, such as the query id) and &amp;lt;code&amp;gt;txnVersion&amp;lt;/code&amp;gt; (a monotonically increasing number, such as the batch id) identify a write, and Delta ignores a write whose combination it has already committed.&amp;lt;ref name=&amp;quot;delta-stream&amp;quot;&amp;gt;{{Cite web |url=https://docs.delta.io/latest/delta-streaming.html |title=Table streaming reads and writes |publisher=Delta Lake (Linux Foundation) |access-date=2026-11-23}}&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
app_id = &amp;quot;orders_to_two_tables&amp;quot;&lt;br /&gt;
&lt;br /&gt;
def write_twice(batch_df, batch_id):&lt;br /&gt;
    batch_df.persist()&lt;br /&gt;
    (batch_df.write.format(&amp;quot;delta&amp;quot;).mode(&amp;quot;append&amp;quot;)&lt;br /&gt;
        .option(&amp;quot;txnAppId&amp;quot;, app_id).option(&amp;quot;txnVersion&amp;quot;, batch_id)&lt;br /&gt;
        .saveAsTable(&amp;quot;main.sales.orders&amp;quot;))&lt;br /&gt;
    (batch_df.filter(&amp;quot;amount &amp;gt; 1000&amp;quot;).write.format(&amp;quot;delta&amp;quot;).mode(&amp;quot;append&amp;quot;)&lt;br /&gt;
        .option(&amp;quot;txnAppId&amp;quot;, app_id).option(&amp;quot;txnVersion&amp;quot;, batch_id)&lt;br /&gt;
        .saveAsTable(&amp;quot;main.sales.large_orders&amp;quot;))&lt;br /&gt;
    batch_df.unpersist()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the checkpoint is deleted and the query restarts with a new one, batch ids start again from 0, so the query must use a different &amp;lt;code&amp;gt;txnAppId&amp;lt;/code&amp;gt;; otherwise Delta ignores its writes as duplicates.&amp;lt;ref name=&amp;quot;delta-stream&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== How are upserts written from a stream? ==&lt;br /&gt;
Streaming sinks for table formats append rows or replace the table; the Delta Lake and [[Apache Iceberg]] Spark sinks support append and complete [[output mode]]s.&amp;lt;ref name=&amp;quot;delta-stream&amp;quot; /&amp;gt;&amp;lt;ref name=&amp;quot;iceberg&amp;quot;&amp;gt;{{Cite web |url=https://iceberg.apache.org/docs/latest/spark-structured-streaming/ |title=Spark Structured Streaming (Apache Iceberg 1.12.0) |publisher=Apache Software Foundation |access-date=2026-11-23}}&amp;lt;/ref&amp;gt; To update existing rows, the query runs a &amp;lt;code&amp;gt;MERGE&amp;lt;/code&amp;gt; inside foreachBatch. The Delta Lake documentation uses this pattern to write streaming aggregates in update mode, which it describes as much more efficient than complete mode, to apply a stream of change data, and to deduplicate with an insert-only merge.&amp;lt;ref name=&amp;quot;delta-merge&amp;quot;&amp;gt;{{Cite web |url=https://docs.delta.io/latest/delta-update.html#upsert-from-streaming-queries-using-foreachbatch |title=Table deletes, updates, and merges: Upsert from streaming queries using foreachBatch |publisher=Delta Lake (Linux Foundation) |access-date=2026-11-23}}&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
from delta.tables import DeltaTable&lt;br /&gt;
&lt;br /&gt;
target = DeltaTable.forName(spark, &amp;quot;main.sales.customer_totals&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
def upsert(batch_df, batch_id):&lt;br /&gt;
    (target.alias(&amp;quot;t&amp;quot;)&lt;br /&gt;
        .merge(batch_df.alias(&amp;quot;s&amp;quot;), &amp;quot;s.customer_id = t.customer_id&amp;quot;)&lt;br /&gt;
        .whenMatchedUpdateAll()&lt;br /&gt;
        .whenNotMatchedInsertAll()&lt;br /&gt;
        .execute())&lt;br /&gt;
&lt;br /&gt;
(totals_stream.writeStream&lt;br /&gt;
    .foreachBatch(upsert)&lt;br /&gt;
    .outputMode(&amp;quot;update&amp;quot;)&lt;br /&gt;
    .option(&amp;quot;checkpointLocation&amp;quot;, &amp;quot;/checkpoints/customer_totals&amp;quot;)&lt;br /&gt;
    .start())&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The Delta documentation warns that the merge must be idempotent, because a restart can apply the same batch more than once. Because merge reads its input more than once, the reported input rate can be a multiple of the real one, and caching the batch before the merge avoids the extra reads.&amp;lt;ref name=&amp;quot;delta-merge&amp;quot; /&amp;gt; Databricks states that foreachBatch is required for Delta Lake merge operations in Structured Streaming.&amp;lt;ref name=&amp;quot;db-fb&amp;quot;&amp;gt;{{Cite web |url=https://docs.databricks.com/aws/en/structured-streaming/foreach |title=Use foreachBatch to write to arbitrary data sinks |publisher=Databricks |access-date=2026-11-23}}&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Common pitfalls ==&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;Recomputation.&amp;#039;&amp;#039;&amp;#039; Each action on the batch DataFrame can recompute the batch, including re-reading the source. Writing to several places should be wrapped in &amp;lt;code&amp;gt;persist()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;unpersist()&amp;lt;/code&amp;gt;.&amp;lt;ref name=&amp;quot;ss-fb&amp;quot; /&amp;gt;&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;State reloads.&amp;#039;&amp;#039;&amp;#039; In a stateful query, several actions on the same batch DataFrame, such as &amp;lt;code&amp;gt;count()&amp;lt;/code&amp;gt; then &amp;lt;code&amp;gt;collect()&amp;lt;/code&amp;gt;, evaluate the query several times and reload state each time; the Spark guide recommends persisting the DataFrame inside the function.&amp;lt;ref name=&amp;quot;ss-fb&amp;quot; /&amp;gt;&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;Empty batches.&amp;#039;&amp;#039;&amp;#039; The function can receive an empty DataFrame, and code that assumes rows can fail. Databricks gives examples where a Delta source produces an empty micro-batch, such as an &amp;lt;code&amp;gt;OPTIMIZE&amp;lt;/code&amp;gt; with no files to process.&amp;lt;ref name=&amp;quot;db-fb&amp;quot; /&amp;gt;&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;End-to-end semantics.&amp;#039;&amp;#039;&amp;#039; Operations applied inside foreachBatch are outside Spark&amp;#039;s incremental planning, so the user has to reason about their correctness across batches and retries.&amp;lt;ref name=&amp;quot;ss-fb&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== See also ==&lt;br /&gt;
* [[Output mode]]&lt;br /&gt;
* [[Exactly-once semantics]]&lt;br /&gt;
* [[Streaming checkpoint]]&lt;br /&gt;
* [[Delta Lake]]&lt;br /&gt;
* [[Streaming deduplication]]&lt;br /&gt;
* [[Structured Streaming]]&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{Navbox open lakehouse}}&lt;br /&gt;
&lt;br /&gt;
[[Category:Concepts]]&lt;br /&gt;
[[Category:Glossary terms]]&lt;br /&gt;
[[Category:Apache Spark]]&lt;br /&gt;
[[Category:Pipelines and orchestration]]&lt;/div&gt;</summary>
		<author><name>Open Lakehouse Wiki sync</name></author>
	</entry>
</feed>