Part VIII - Batch vs. Streaming in Spark: One SQL Engine, Two Execution Contracts
From the publisher’s feed, collected in the ZeroLabs newsroom.
Why changing read to readStream preserves your transformations but changes state, time, recovery, and output semanticsPart I | Part II | Part III | Part IV | Part V | Part VI | Part VII | Part VIIIThe Ten-Second Query That Fell 93 Minutes BehindAt 3:07 AM, an order-fraud pipeline configured with a 10-second trigger was serving results that were 93 minutes stale. The same transformation had been unremarkable in batch: read 1.6TB of orders, deduplicate by order_id, enrich valid rows, and finish in 27 minutes.The streaming migration looked disciplined. The team reused the tested DataFrame transformation, changed spark.read to spark.readStream, moved the source from Parquet to Kafka, and replaced write with writeStream. For the first day, each trigger completed in 6-8 seconds.By day nine, the query had accumulated 286 million order IDs in its state store. State and checkpoint data occupied 146GB. Trigger execution had climbed to 11 minutes, while Kafka was delivering data faster than Spark could commit it. Restarting from the checkpoint restored the problem exactly as designed.The batch job and streaming query used the same dropDuplicates(["order_id"]) expression. They did not ask Spark to perform the same physical obligation:A batch query sees a finite input. Once its shuffle has compared every row in that input, the deduplication state can disappear with the job.A streaming query sees an unfinished input. Without a time boundary, any order seen today might be duplicated next month, so Spark must remember every ID for the lifetime of the query.The trigger interval was not the root cause. The missing data contract was: how late can a duplicate arrive?So if Structured Streaming runs on Spark SQL, what does Spark genuinely treat the same between batch and streaming, and where does an unbounded input force a different execution contract?The Unifying Model: A DataFrame Is a Plan, Not a ContainerA Spark DataFrame does not hold the rows it describes. It holds a logical plan. Whether that plan is bounded enters at the source:spark.read creates a relation Spark can exhaust.spark.readStream creates a relation whose future rows do not exist yet.The streaming property propagates through every downstream DataFrame; df.isStreaming exposes it.For both paths, Spark SQL still resolves attributes and types, applies Catalyst rules such as predicate pushdown and projection pruning, chooses physical operators, generates code where supported, and schedules stages and tasks through the same Spark runtime. A filter does not acquire new boolean semantics because its parent is Kafka instead of Parquet.This is the useful part of Spark’s unified model: deterministic, row-local business logic can usually be written once and applied to either a bounded or unbounded DataFrame.But “same SQL engine” does not mean “identical physical plan.” After analysis, Spark validates whether a logical operation can be executed incrementally. It then plans streaming-specific operators where the query must preserve information across triggers.What Spark Can Reuse DirectlyStateless transformations only need the current row or current partition. These are naturally incremental:projections and expression evaluation;filters and deterministic parsing;schema normalization and column derivation;many stream-static joins, where the static side does not change during a running query.Each micro-batch can run these operators with the same task, stage, shuffle, and code-generation machinery used by a batch job.What Becomes a Temporal ContractOperations that need to compare the present with the past require state:aggregation must retain partial results by key;deduplication must retain previously observed keys;stream-stream joins must retain unmatched rows from both sides;event-time windows must remain open for late records;arbitrary stateful functions must restore their key-value state after failure.Other batch operations do not have a finite streaming interpretation at all. A global sort cannot emit the first row while a smaller row may still arrive tomorrow. A bare limit(100) cannot know that its result is final. Spark rejects such plans during streaming analysis rather than silently changing their meaning.The dividing line is not syntax. It is whether Spark can produce correct incremental results without waiting for an input that never ends.What a Micro-Batch Actually ExecutesStructured Streaming uses micro-batch processing by default. It does not keep one giant batch job open. For each trigger, the driver coordinates a transaction-like sequence:Ask each source for its latest available offset or position.Choose the bounded offset range for this micro-batch, applying controls such as maxOffsetsPerTrigger when configured.Persist the intended offsets in the checkpoint before processing.Plan and execute that finite range with ordinary Spark stages and tasks.Commit state-store versions and sink output for the micro-batch ID.Record the completed batch in the checkpoint, then advance to the next range.That fourth step is why the Spark UI looks familiar: a micro-batch still contains jobs, stages, shuffle exchanges, and tasks. The surrounding offset, state, and commit protocol is what turns repeated finite jobs into one recoverable streaming query.A Trigger Is a Scheduling Policy, Not a Latency GuaranteeWith a 10-second processing-time trigger, Spark starts a new micro-batch every 10 seconds only when the previous one has finished. If one trigger takes 11 minutes, Spark does not run 66 overlapping batches. The next batch starts immediately after it and reads a larger backlog.That creates a positive feedback loop:state grows, so lookup and commit work takes longer;longer triggers admit more source data into the next range;larger ranges produce more shuffle and state updates;processing rate falls below arrival rate, so source lag grows without bound.The useful control signal is not the configured trigger interval. Compare processedRowsPerSecond with inputRowsPerSecond, then inspect durationMs.triggerExecution, source offsets, and state-operator metrics in StreamingQueryProgress. A healthy query has enough headroom to clear bursts; merely completing a trigger is not evidence that it is keeping up.Spark also offers continuous processing, but it is an experimental, restricted execution mode with at-least-once guarantees. It can reduce latency for compatible stateless queries; it is not a switch that makes arbitrary stateful SQL execute row by row. The default micro-batch engine remains the general-purpose path and provides the broad operator surface.The Result Table: Why Streaming State ExistsSpark models a streaming query as an unbounded input table updating a logical result table. Output modes decide which result-table changes a trigger sends to the sink:Append mode emits rows only after Spark knows they will not change again.Update mode emits rows changed by the current trigger.Complete mode emits the entire result table after every trigger.Output mode is not a storage optimization flag. It is part of query correctness. An all-time count by customer can change forever, so it cannot be appended as a final row after each trigger. A five-minute event-time window can become final once the watermark passes its end, so Append mode can emit it exactly once to a fault-tolerant sink.Watermarks Bound the Question Spark Must AnswerA watermark converts an open-ended event-time question into a bounded one. If the maximum event time observed is 12:40 and the delay threshold is 30 minutes, the query watermark is approximately 12:10. Spark can use that boundary to finalize old windows and evict state that can no longer affect future output.Three details matter in production:The watermark follows event time observed in the data, not wall-clock time. If input stops, event-time progress can stop too.The delay is a one-sided guarantee: data less late than the threshold will not be dropped. Data later than the threshold may or may not still be processed.The watermark must participate in the stateful operator correctly. Calling withWatermark after an aggregation does not retroactively bound its state, and Complete mode preserves the full aggregation result by definition.For multiple input streams, Spark tracks each watermark and uses the slowest one by default as the global watermark. That protects late data from the lagging source but lets one stalled input delay state eviction for the entire query.In the incident, upstream retries were contractually limited to 20 minutes. The corrected query used a 30-minute watermark and deduplicated within that boundary. State stabilized at 8.7 million keys and 6.4GB instead of growing past 286 million keys and 146GB. With a 30-second trigger, p95 trigger execution settled at 18 seconds, and the 93-minute Kafka backlog cleared in 47 minutes.That improvement did not come from “making streaming faster.” It came from giving Spark permission to forget.One Logical Pipeline, Two Execution PathsThe shared and divergent parts of the engine look like this:For the streaming path, the checkpoint closes the recovery loop:+-----------------------+| Source offset range |+-----------------------+ | execute v+-----------------------+| Spark jobs and tasks |+-----------------------+ | update v+-----------------------+| State store version |+-----------------------+ | commit v+-----------------------+| Sink + checkpoint log |+-----------------------+ | +----> next triggerThe checkpoint is therefore not a cache directory to delete whenever a query is slow. It stores query identity, processed offset ranges, commit metadata, and state-store versions. Removing it creates a new query with no memory of what the old one committed.The Engine-Aware ImplementationKeep reusable business transformations stateless. Put boundedness, event-time policy, and sink semantics at the execution edge.from pyspark.sql import DataFrame, functions as Fdef valid_orders(orders: DataFrame) -> DataFrame: """Business logic shared by bounded and unbounded inputs.""" return ( orders .select( "order_id", "customer_id", "event_time", F.col("amount").cast("decimal(18, 2)").alias("amount"), F.upper("currency").alias("currency"), ) .where( F.col("order_id").isNotNull() & F.col("customer_id").isNotNull() & (F.col("amount") > 0) ) )# Bounded source: Catalyst can optimize the full finite relation.historical_orders = valid_orders( spark.read.table("bronze.orders_history"))# Unbounded source: the same row-local plan runs for every offset range.live_orders = valid_orders( spark.readStream.table("bronze.orders_ingest"))The dangerous version leaves deduplication time unbounded:# Naive: retain every order_id for the entire lifetime of the query.unbounded_dedup = live_orders.dropDuplicates(["order_id"])The production version encodes the retry SLA and lets the state store evict IDs after they can no longer be duplicated legitimately:# Optimized: bound deduplication state with the upstream 20-minute retry SLA.deduplicated_orders = ( live_orders .withWatermark("event_time", "30 minutes") .dropDuplicatesWithinWatermark(["order_id"]))query = ( deduplicated_orders.writeStream .queryName("orders_deduplicated_v2") .outputMode("append") .format("parquet") .option("path", "s3://analytics/silver/orders") .option( "checkpointLocation", "s3://analytics/checkpoints/orders_deduplicated_v2", ) .trigger(processingTime="30 seconds") .start())dropDuplicatesWithinWatermark is intentionally different from batch-global deduplication. It guarantees deduplication only within the declared event-time horizon. That is not a compromise hidden in configuration; it is the business contract required to make memory finite.For older Spark versions, watermark-aware deduplication often includes event time in the deduplication key. That can change which records count as duplicates when retry timestamps differ. Do not treat the two forms as mechanically interchangeable.AvailableNow: The Useful Middle GroundBatch and streaming are not mutually exclusive deployment identities. An AvailableNow trigger runs the streaming plan until all data available at invocation time has been processed, potentially across multiple rate-limited micro-batches, and then stops.# Naive: write a second batch pipeline with separate offset bookkeeping.# Optimized: reuse streaming offsets, state, and watermark progression, then stop.catch_up_query = ( deduplicated_orders.writeStream .format("parquet") .option("path", "s3://analytics/silver/orders") .option( "checkpointLocation", "s3://analytics/checkpoints/orders_deduplicated_v2", ) .trigger(availableNow=True) .start())catch_up_query.awaitTermination()This is often the right operating model for hourly ingestion, controlled backfills, and clusters that should terminate when caught up. It keeps Structured Streaming’s offset and state semantics without paying for an always-on cluster.Do not run the continuous and AvailableNow variants concurrently against the same checkpoint. A checkpoint represents one query execution lineage, not a distributed lock service for competing writers.Checkpointing Is Necessary, Not Sufficient, for Exactly-Once ResultsSpark can replay a failed micro-batch from the offsets recorded in its checkpoint. Stateful operators can reopen the corresponding version of their state. Those capabilities prevent the engine from losing its place, but end-to-end exactly-once still depends on every boundary:The source must make the recorded offsets replayable. Kafka does; a socket source does not.The transformation must be deterministic for a replayed offset range. Calling external services or using nondeterministic values inside the plan can produce a different retry.The sink must commit a micro-batch atomically or deduplicate retries. The file sink has an exactly-once metadata protocol; the Kafka sink is at-least-once and can contain duplicates.foreachBatch is at-least-once by default. Use its batch_id with an idempotent transaction or merge if the destination must observe each batch once.This is why “we enabled checkpointing” is not a delivery guarantee. Checkpointing makes replay possible; the sink contract determines whether replay is harmless.The checkpoint also constrains deployments. On restart, startingOffsets does not override saved progress. Spark resumes from the checkpoint. Changing the number or type of sources, join keys, aggregation keys, or state schema under an existing checkpoint is unsupported or semantically unsafe. Treat a stateful streaming query like a stateful service: schema evolution needs an explicit migration or a new checkpoint and a controlled replay.Choosing Batch, Streaming, or BothChoose based on boundedness, freshness, and correction semantics, not on which API looks more modern.Use Batch Whenthe result requires a full snapshot, global ordering, or exact recomputation over all history;freshness is measured in hours and an ephemeral cluster is materially cheaper;source corrections routinely rewrite old history beyond any practical watermark;the workload is a one-off backfill whose natural boundary is already known.Batch gets to see the end of the table. That makes global decisions possible and lets all execution state die when the job completes.Use Continuous Micro-Batch Streaming Whenthe source exposes replayable offsets and downstream freshness has a sub-hour SLO;row-local work or incremental state updates dominate the computation;the business can define lateness, deduplication, and finalization boundaries;the sink can make retries idempotent or transactional.Streaming avoids rescanning unchanged history, but it turns accumulated state, checkpoint health, and source lag into production capacity concerns.Use AvailableNow Whenthe pipeline should process only new data but does not need an always-on cluster;a large backlog must be split into controlled micro-batches;scheduled execution should preserve the same offsets, state, and watermark logic as the low-latency path.Keep a Batch Reconciliation PathWatermarks deliberately stop revising sufficiently old results. Sources are reprocessed, contracts fail, and upstream systems sometimes produce data beyond the promised lateness bound. A periodic batch reconciliation over an immutable source of truth is not an admission that streaming failed; it is the correction path for facts that arrive outside the streaming contract.The strongest design is usually one set of deterministic transformations, two explicit execution contracts:streaming for low-latency incremental truth inside the watermark horizon;batch for historical repair and invariant checks across the complete dataset.TakeawaysSpark does not maintain unrelated SQL engines for batch and Structured Streaming. Both use DataFrames, Catalyst, physical operators, stages, and tasks.A streaming source marks the plan as unbounded. Spark must validate incremental execution and introduce offsets, triggers, output modes, state stores, watermarks, and checkpoints.Stateless expressions transfer cleanly. Stateful operators transfer only after you define how long the past can affect the future.A trigger interval controls when Spark tries to run; it does not guarantee latency. Sustainable throughput requires processing headroom.Watermarks are correctness policies that enable state eviction, not generic performance tuning.Checkpoints coordinate replay. Exactly-once output still requires a replayable source, deterministic computation, and an idempotent or transactional sink.AvailableNow collapses much of the false batch-versus-streaming choice: it runs an incremental streaming contract over a bounded backlog and stops.Spark treats batch and streaming alike until time becomes part of the answer. At that boundary, the code may still look familiar, but the system you are operating is no longer stateless.If this saved you a 3 AM pager incident, follow me on Medium for Twice a week for the next 3 Months of Advanced Data Engineering & AI. Let’s connect on LinkedIn and X.Part VIII - Batch vs. Streaming in Spark: One SQL Engine, Two Execution Contracts was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.