Spark & PySpark
Spark Structured Streaming in Production - The Complete Operational Guide
Your Streaming Job Ran for Three Days Then Died. Here Is How to Build One That Keeps Running.

TL;DR
- Checkpoints are the memory of a streaming job — store them on durable storage (S3, HDFS), never on local disk; a node restart with local checkpoints means reprocessing from the beginning and duplicate records in the sink
- Choose trigger type deliberately:
ProcessingTimefor predictable micro-batch schedules,AvailableNowfor streaming semantics on a batch schedule, default trigger only when latency genuinely demands it - The metrics that matter for operational monitoring are batch duration, input rows per second, and Kafka consumer lag — not CPU or memory alone
- Schema changes to a running streaming query require a restart with a new checkpoint; design schemas to be forward-compatible from the start
- An idempotent sink is non-negotiable — checkpoint recovery replays events, and a sink that cannot handle duplicates will corrupt its output on every restart
A streaming job that cannot survive a restart is not a production streaming job.
The team deployed a streaming pipeline on a Monday. Kafka → Spark Structured Streaming → Delta Lake. Checkpoints configured. Monitoring in place. Everything green through Wednesday.
Thursday morning, a Kubernetes pod restart wiped the checkpoint directory. It was on local disk. Nobody had checked.
The job restarted from the earliest available Kafka offset — four days back. It reprocessed 96 hours of events. The Delta Lake sink had no deduplication logic. Four days of records were written twice.
The data team spent two days cleaning up. The fix to prevent recurrence: two config lines. checkpointLocation pointing to S3. A merge-based upsert replacing the append write.Checkpoint Configuration — The Foundation of Everything
Checkpoints are how Structured Streaming survives restarts. They store the current Kafka offsets, the state of stateful operators (windows, aggregations, watermarks), and the query metadata. Without a valid checkpoint, a restarted query has no memory of where it was — it starts over.
Where to Store Checkpoints
The checkpoint location must survive anything that can happen to the nodes running the job: pod restarts, node failures, cluster termination, cluster replacement.
Local disk survives none of these. S3, HDFS, and Azure Blob Storage survive all of them.
query = (
df.writeStream
.format("delta")
.outputMode("append")
.option("checkpointLocation", "s3://your-bucket/checkpoints/pipeline-name/")
.trigger(processingTime="5 minutes")
.start("s3://your-bucket/output/events/")
)One practical note on S3 checkpoints: S3 has higher latency for small file writes than HDFS. For very high-throughput streams with short trigger intervals (under 30 seconds), checkpoint commit latency on S3 can become a bottleneck. For most production workloads with trigger intervals of 1–5 minutes, S3 is fine.
What Checkpoints Actually Store
Understanding checkpoint contents explains why the rules around them are strict:
checkpoint/
commits/ ← completed batch IDs
offsets/ ← Kafka offset range per batch
state/ ← operator state (windows, aggregations)
metadata ← query ID, schema, configurationThe offsets directory tells the job where to resume reading. The state directory holds window aggregations and watermark positions — lose this and stateful computations restart from zero. The metadata file locks the query to its original schema and configuration.
The Rules You Cannot Break
Rule 1: Never change the checkpoint location for a running query. The checkpoint contains the query’s identity. Moving it is equivalent to starting a new query from scratch — which means reprocessing from the beginning of the Kafka retention window.
Rule 2: Never change the schema of a streaming query without a new checkpoint. The schema is locked in metadata at query start. A schema change mid-stream requires stopping the query, deleting or archiving the checkpoint, and restarting — accepting that in-flight state is lost.
Rule 3: The sink must be idempotent. Checkpoint recovery replays the last uncommitted batch. If the sink wrote partial output before the failure, the replay will write it again. A sink that deduplicates on replay produces correct output. A sink that blindly appends produces duplicates.
Trigger Types — Choosing the Right One
The trigger controls when Spark processes available data. It is one of the most consequential configuration decisions in a streaming job and one of the least discussed.
ProcessingTime — The Production Default
ProcessingTime runs micro-batches on a fixed schedule. Each batch processes all events that arrived since the previous batch completed.
.trigger(processingTime="5 minutes")This is the right choice for most production streaming jobs. It gives you:
- Predictable resource usage — the cluster works for a defined interval, then waits
- Controllable batch size — the interval determines how much data accumulates per batch
- Manageable checkpoint overhead — checkpoints happen once per interval, not continuously
For latency requirements between 30 seconds and several hours, ProcessingTime is almost always the right answer. The interval is the primary lever for the latency vs throughput trade-off.
AvailableNow — The Scheduled Job Pattern
Added in Spark 3.3, AvailableNow processes all data currently available in the source, then stops. It uses streaming semantics (checkpointing, watermarks, state) but terminates like a batch job.
.trigger(availableNow=True)This is the right choice when you want:
- The correctness guarantees of streaming (exactly-once, stateful processing)
- The operational model of batch (runs, completes, terminates)
- To run on a schedule via Airflow or a cron job rather than keeping a long-running process alive
An AvailableNow job picks up from the last committed checkpoint offset, processes everything new, writes the output, and exits. The next scheduled run picks up from where this one left off. No always-on cluster required.
Default Trigger — Use With Care
The default trigger (no .trigger() call) runs micro-batches as fast as possible — the next batch starts as soon as the previous one finishes.
# Default trigger — implicit, continuous micro-batching
query = df.writeStream.format("delta").start(output_path)For low-volume streams, this is fine — if events arrive slowly, batches are small and the cluster mostly waits. For high-volume streams, continuous processing can saturate the cluster, drive up compute costs, and produce checkpoint overhead that exceeds the processing time. Check actual batch duration and resource utilization before leaving the default trigger in a high-volume production job.
Continuous Processing — Know the Limits
Continuous trigger runs a true streaming engine with sub-millisecond latency — no micro-batching.
.trigger(continuous="1 second") # checkpoint interval, not batch intervalAs of Spark 3.x, continuous processing is still experimental. It supports a limited set of operations — primarily stateless transformations and simple aggregations. Stateful operations (windows, watermarks, arbitrary stateful processing) are not supported. Verify your use case is supported before building on it in production.
For the vast majority of streaming workloads, ProcessingTime with a short interval produces sufficient latency at significantly lower operational complexity.
Monitoring That Actually Matters
CPU and memory metrics tell you the cluster is running. They do not tell you whether the streaming job is healthy. Streaming jobs need their own set of operational metrics.
StreamingQueryListener
The StreamingQueryListener API gives you programmatic access to per-batch metrics — the most important monitoring surface for production streaming jobs.
from pyspark.sql.streaming import StreamingQueryListener
import json
import time
class ProductionStreamingMonitor(StreamingQueryListener):
def onQueryStarted(self, event):
print(f"Query started: {event.name} (id={event.id})")
def onQueryProgress(self, event):
progress = event.progress
batch_duration_ms = progress.batchDuration
input_rows_per_sec = progress.inputRowsPerSecond
proc_rows_per_sec = progress.processedRowsPerSecond
num_input_rows = progress.numInputRows
# Alert on slow batches
if batch_duration_ms > 300_000: # 5 minutes
print(f"ALERT: batch duration {batch_duration_ms/1000:.0f}s "
f"exceeds threshold")
# Alert on processing falling behind ingestion
if (input_rows_per_sec > 0 and proc_rows_per_sec > 0 and
proc_rows_per_sec < input_rows_per_sec * 0.8):
print(f"WARN: processing ({proc_rows_per_sec:.0f} rows/s) "
f"falling behind ingestion ({input_rows_per_sec:.0f} rows/s)")
print(
f"Batch {progress.batchId}: "
f"{num_input_rows:,} rows | "
f"{batch_duration_ms/1000:.1f}s | "
f"{proc_rows_per_sec:.0f} rows/s processed"
)
def onQueryTerminated(self, event):
if event.exception:
print(f"ALERT: query terminated with exception: {event.exception}")
else:
print(f"Query terminated cleanly: {event.id}")
spark.streams.addListener(ProductionStreamingMonitor())The Metrics That Signal Problems
Three metrics that reliably indicate something is wrong before it becomes an incident:
Batch duration increasing over time. A batch that consistently took 30 seconds and now takes 3 minutes is accumulating state, processing growing partitions, or hitting an external bottleneck. Catch this before it causes Kafka lag.
processedRowsPerSecond falling below inputRowsPerSecond. The job is consuming data slower than it is arriving. Kafka lag will grow. If left unaddressed, the job eventually cannot catch up.
Zero input rows for multiple consecutive batches. Either the source is empty (expected) or the consumer has lost connectivity to Kafka (not expected). Distinguish between the two before dismissing it.
# Quick health check on a running query
# Store the query object at start — spark.streams.get() does not exist
# query = df.writeStream...start() ← keep a reference to this
# Or iterate active streams to find yours by name
active = {q.name: q for q in spark.streams.active}
query = active.get("your-query-name")
if query is None:
print("Query not found — may have terminated")
else:
progress = query.lastProgress
if progress:
print(f"Input rows/sec: {progress['inputRowsPerSecond']:.1f}")
print(f"Processed rows/sec: {progress['processedRowsPerSecond']:.1f}")
print(f"Batch duration: {progress['batchDuration']}ms")
print(f"Trigger gap: {progress['triggerExecution']['triggerStartOffsetMs']}ms")
# Source-specific lag (Kafka)
for source in progress.get('sources', []):
print(f"Source: {source['description']}")
if 'latestOffset' in source and 'startOffset' in source:
print(f" Latest offset: {source['latestOffset']}")
print(f" Start offset: {source['startOffset']}")
else:
print("No progress recorded yet — query may still be initializing")Kafka Consumer Lag
Consumer lag is the gap between the latest offset available on the broker and the offset your consumer has committed. Growing lag means your streaming job is falling behind.
Monitor this independently of Spark’s own metrics — Spark reports what it has processed, not what is waiting to be processed.
# Check consumer lag from the command line
kafka-consumer-groups.sh \
--bootstrap-server kafka:9092 \
--describe \
--group your-streaming-consumer-group
# Output shows: TOPIC, PARTITION, CURRENT-OFFSET, LOG-END-OFFSET, LAG
# LAG = LOG-END-OFFSET - CURRENT-OFFSET
# Growing LAG across multiple partitions = streaming job falling behindSet an alert when aggregate consumer lag exceeds a threshold that reflects your latency SLO — if your job should process events within 5 minutes and lag represents 8 minutes of data, you are already violating the SLO.
Schema Evolution in Streams
Schema evolution is one of the hardest operational problems in streaming — and one of the least discussed in tutorials, because tutorials don’t run for six months.
Why Schema Changes Break Running Queries
The query schema is recorded in the checkpoint metadata at startup. Spark validates incoming data against this schema on every batch. When an upstream team adds a column, the new data no longer matches the recorded schema. The query fails with a schema mismatch error — or worse, silently ignores the new column depending on the mode.
Stateful streaming queries often require a restart when schema changes affect the query plan or operator state. Some sources and sinks support controlled schema evolution — Delta Lake with mergeSchema enabled, Auto Loader with schema inference mode — but this should be validated explicitly for your specific configuration rather than assumed. The safest default: treat schema changes as requiring a migration plan, and verify in a lower environment before applying to production.
# Delta Lake sink — enable schema evolution on the sink side
# This allows new columns to be added to the Delta table
# without breaking the streaming write
query = (
df.writeStream
.format("delta")
.option("checkpointLocation", "s3://bucket/checkpoints/events/")
.option("mergeSchema", "true") # allows new columns to be added
.trigger(processingTime="5 minutes")
.start("s3://bucket/output/events/")
)
# Auto Loader — schema evolution with rescue column
# Captures unexpected fields in a _rescued_data column
# rather than failing or silently dropping them
df_autoloader = (
spark.readStream
.format("cloudFiles")
.option("cloudFiles.format", "json")
.option("cloudFiles.schemaEvolutionMode", "rescue")
.option("cloudFiles.schemaLocation", "s3://bucket/schema/events/")
.load("s3://bucket/raw/events/")
)
# New fields appear in _rescued_data as JSON string
# Existing fields are unaffected — no restart requiredForward-Compatible Schema Design
The best defence is designing schemas to accommodate evolution from the start:
from pyspark.sql.types import StructType, StructField, StringType, MapType
# Pattern 1: explicit selection — only read columns you depend on
# New columns added upstream are silently ignored
df = (
spark.readStream
.format("kafka")
.option("kafka.bootstrap.servers", "kafka:9092")
.option("subscribe", "payment-events")
.load()
.select(
F.col("value").cast("string").alias("raw"),
F.col("timestamp")
)
.select(
F.from_json(
F.col("raw"),
PAYMENT_SCHEMA # only the fields your job needs
).alias("data"),
F.col("timestamp")
)
.select("data.*", "timestamp")
)
# Pattern 2: schema with extra fields captured in a map
# Allows schema changes without breaking the query
FLEXIBLE_SCHEMA = StructType([
StructField("event_id", StringType(), nullable=False),
StructField("amount", StringType(), nullable=True),
StructField("merchant_id", StringType(), nullable=True),
# Catch-all for future fields — avoids breakage on new columns
StructField("extra", MapType(StringType(), StringType()), nullable=True)
])Pattern 1 is the most common and most practical — select only the fields you need and ignore the rest. New upstream fields arrive in the raw payload but are not parsed into your schema.
The Migration Path
When a breaking schema change is unavoidable — a field renamed, a type changed, a required field removed:
1. Stop the current query cleanly
query.stop()
2. Archive the existing checkpoint
# Do not delete — keep for debugging
mv s3://bucket/checkpoints/v1/ s3://bucket/checkpoints/v1-archived/
3. Start a new query with a new checkpoint location
.option("checkpointLocation", "s3://bucket/checkpoints/v2/")
4. Handle the backfill gap
# The new query starts from the latest Kafka offset by default
# If you need to reprocess the gap, set startingOffsets explicitly
.option("startingOffsets", json.dumps({
"payment-events": {str(p): gap_start_offset for p in partitions}
}))
The gap between the old query stopping and the new query starting at the correct offset is the most operationally sensitive part of a schema migration. Plan it explicitly — including whether the sink handles both old and new schema formats during the transition window.
Making the Sink Idempotent
Checkpoint recovery replays the last uncommitted batch. The sink will receive events it may have already partially written. If the sink cannot handle this, it produces duplicates.
The two patterns that produce idempotent sinks:
# Pattern 1: merge-based upsert for Delta Lake
# Duplicate event_ids are matched and updated rather than inserted again
def write_idempotent_batch(batch_df, batch_id):
from delta.tables import DeltaTable
target = DeltaTable.forPath(spark, "s3://bucket/output/events/")
(
target.alias("target")
.merge(
batch_df.alias("source"),
"target.event_id = source.event_id"
)
.whenMatchedUpdateAll()
.whenNotMatchedInsertAll()
.execute()
)
query = (
df.writeStream
.foreachBatch(write_idempotent_batch)
.option("checkpointLocation", "s3://bucket/checkpoints/events/")
.trigger(processingTime="5 minutes")
.start()
)
# Pattern 2: deduplication window in the stream itself
# Removes duplicates before writing — works for any sink type
df_deduped = (
df.withWatermark("event_timestamp", "10 minutes")
.dropDuplicates(["event_id", "event_timestamp"])
)
# dropDuplicates with watermark keeps dedup state for events
# within the watermark window — older events are assumed settledThe merge-based approach is generally more robust — it handles duplicates at the sink level regardless of how they arrived. The dropDuplicates approach works well but requires careful watermark configuration to bound the deduplication state size.
The Five Streaming Mistakes
1. Checkpoint on local disk
The most common and most expensive mistake. Pod restarts, cluster termination, node replacement — all of them wipe local disk. Two config lines fix it permanently. There is no valid reason to store production checkpoints locally.
2. Default trigger on a high-volume stream
A stream processing 50,000 events per second with the default trigger will run continuous micro-batches, accumulate checkpoint overhead between each, and drive resource utilization to 100% without obvious explanation. Set an explicit ProcessingTime interval and monitor batch duration.
3. No idempotent sink
The question is not whether your streaming job will restart. It will. The question is whether the restart produces duplicates. An append-only sink without deduplication logic will produce duplicates on every restart. Fix this before the first production deployment.
4. Ignoring Kafka consumer lag
Spark’s internal metrics tell you how fast the job is processing. Kafka consumer lag tells you how far behind it is. These are different questions. A job that processes 10,000 rows per second but is 2 million rows behind is not healthy — it is falling further behind with every batch. Monitor lag independently.
5. Schema changes without a migration plan
The upstream team adds a field. The streaming query fails. This is predictable and preventable. Design schemas to select only the fields you depend on, ignore extras, and document the migration procedure before the first schema change is needed — not after.
Streaming Production Checklist
Before promoting a streaming job to production, verify every item. Each unchecked box is a failure mode waiting for its moment
Checkpoint and state
□ Checkpoint stored on durable storage (S3, HDFS, Azure Blob)
□ Checkpoint path is versioned (e.g. /checkpoints/pipeline-v2/)
so schema migrations have a clean separation point
□ Checkpoint behaviour on restart tested in a lower environment
□ Replay from an older offset tested — verify no duplicates
Sink correctness
□ Sink is idempotent — merge-based upsert or dedup window in place
□ Duplicate record behaviour verified after simulated restart
□ Schema evolution behaviour on the sink side documented and tested
Trigger and performance
□ Trigger type chosen deliberately — not left as default
□ Batch duration monitored with an alert threshold
□ processedRowsPerSecond monitored relative to inputRowsPerSecond
Kafka and source
□ Consumer lag monitored independently of Spark metrics
□ Alert set on lag exceeding latency SLO threshold
□ Behaviour on source unavailability tested (broker restart, topic deletion)
Schema and operations
□ Schema migration procedure documented before first change is needed
□ Forward-compatible schema pattern in place (column selection or rescue)
□ StreamingQueryListener or equivalent monitoring attached
□ Query termination with exception triggers an alertA streaming job that passes this checklist will survive most production failure modes. One that skips it will eventually demonstrate why each item is on the list.
Final Takeaway
Structured Streaming jobs that run in tutorials run for five minutes on clean data. Production streaming jobs run for months on data that changes, on clusters that restart, against schemas that evolve, with sinks that must handle replayed events.
The patterns above address the failure modes that only appear after the tutorial ends. Most of them require two to five config lines or a small code change. The cost of skipping them is measured in hours of cleanup and corrupted output.
📌 Core Principle
A streaming job that cannot survive a restart is not a production streaming job. Configure for failure from day one. The restart will come.
Next in Series
Delta Lake in Production — Beyond the Tutorial
Your streaming job is writing to Delta Lake.
Next: what it takes to keep a Delta table healthy in production — OPTIMIZE and VACUUM on the right schedule, Z-ordering for query performance, schema evolution that doesn’t break downstream consumers, and time travel use cases that are actually useful rather than just impressive in demos.