Apache Spark Structured Streaming: Kafka Pipeline Guide
Build a PySpark 4.3.0 Kafka pipeline, set up checkpoint recovery, and learn why the built-in Kafka sink can still write duplicate records.
Use Structured Streaming for new Spark streaming applications and keep DStreams as legacy context. A runnable PySpark 4.3.0 example reads from Kafka and writes to another topic; the guide separates checkpoint recovery from the built-in sink's at-least-once delivery and downstream deduplication.
Apache Spark Structured Streaming: Kafka Pipeline Guide
For new Spark streaming applications, start with Structured Streaming. It lets a DataFrame query process an unbounded input and recover progress through a checkpoint. The sink still matters: Spark’s built-in Kafka sink is at-least-once, so checkpoint recovery can still be followed by duplicate output records.
This tutorial uses Apache Spark 4.3.0, the latest released version when checked on 2026-11-04. The release was announced on October 30, 2026. See the Spark 4.3.0 release notice and downloads page for the version and package details.
Start with Structured Streaming
Structured Streaming represents incoming records as an unbounded table. You write DataFrame or SQL operations over that table, then start a query that incrementally processes new input. In Spark 4.3.0, the standard trigger runs micro-batches as soon as it can. You can also request a processing-time cadence, such as two seconds, as in the sample below. That setting controls when Spark checks for another batch; observed end-to-end latency also depends on source availability, backlog, query work, cluster resources, and sink response time. Measure latency with your workload and service target. The Structured Streaming API guide documents trigger behavior and output modes.
Spark also has Structured Streaming Real-time Mode, introduced in Spark 4.1.0. It uses the Structured Streaming APIs with different execution and scheduling behavior. In Spark 4.3.0, documented support includes stateless queries and a limited set of stateful operations: streaming deduplication, aggregations, and the JVM transformWithState operator. Other stateful operations remain unsupported in this mode. Check the current Real-time Mode support list before choosing it; the pipeline in this article uses the standard micro-batch mode.
Run a Kafka-to-Kafka example
The script reads text records from events-in, lowercases their values, and writes them to normalized-events. It keeps each Kafka key so downstream consumers can associate output records with the same entity.
Before running it, prepare these local prerequisites:
- Spark 4.3.0 with
spark-submitavailable. - A Kafka broker supported by Spark 4.3.0, reachable at
localhost:9092(the integration guide lists broker versions 0.10.0 and newer). - Existing Kafka topics named
events-inandnormalized-events. - A writable local directory at
/tmp/spark-checkpoints.
This local checkpoint path works for a single-machine exercise. A deployed Spark application needs a durable, fault-tolerant checkpoint filesystem accessible to its workers; see Spark’s checkpointing guidance.
Save this as process_events.py:
from pyspark.sql import SparkSession
spark = (
SparkSession.builder
.appName("KafkaTextNormalizer")
.getOrCreate()
)
source = (
spark.readStream
.format("kafka")
.option("kafka.bootstrap.servers", "localhost:9092")
.option("subscribe", "events-in")
.option("startingOffsets", "earliest")
.load()
)
normalized = source.selectExpr(
"CAST(key AS STRING) AS key",
"LOWER(CAST(value AS STRING)) AS value",
).where("value IS NOT NULL")
query = (
normalized.writeStream
.format("kafka")
.option("kafka.bootstrap.servers", "localhost:9092")
.option("topic", "normalized-events")
.option("checkpointLocation", "file:///tmp/spark-checkpoints/normalizer")
.outputMode("append")
.trigger(processingTime="2 seconds")
.start()
)
query.awaitTermination()
The Kafka source exposes keys and values as binary columns, so the query casts them to strings. This text-only lab skips Kafka tombstones, which have a null value; a production consumer should handle delete records according to its data model. The Kafka sink requires a string or binary value; key is optional. The subscribe, kafka.bootstrap.servers, topic, and checkpoint options follow Spark’s Kafka integration guide.
Submit the script with the Kafka connector package that matches Spark 4.3.0 and Scala 2.13:
spark-submit \
--master 'local[*]' \
--packages org.apache.spark:spark-sql-kafka-0-10_2.13:4.3.0 \
process_events.py
Leave the process running; awaitTermination() blocks the driver until the query stops or fails. Send a few text records to events-in, then read normalized-events to confirm that the values were lowercased and the keys were preserved. Restart the script with the same checkpoint directory to exercise recovery. Spark uses startingOffsets when a new query starts; on restart from its checkpoint, it resumes from the recorded progress.
For example, Spark might write a normalized record to normalized-events and then fail before saving progress for that trigger. Recovery can replay the source offset range, so the same output may appear again. That is why recovery and sink delivery need separate checks.
Choose a trigger and output mode
The sample requests a two-second processing-time trigger. Actual output delay depends on batch processing time, source backlog, and sink response. The default trigger starts the next micro-batch as soon as the previous work allows. Try different cadences under representative load and compare end-to-end delay with batch duration and backlog.
Output mode describes which rows from the query’s result table go to the sink. The right mode depends on whether a query can revise earlier results and what the sink accepts:
| Mode | What is written | Common fit |
|---|---|---|
| Append | Rows added since the last trigger, when those rows will not be revised. | Stateless transforms such as this pass-through. |
| Update | Rows that changed during the trigger. | Aggregations whose current result may change as new records arrive. |
| Complete | The whole result table on every trigger. | Small result tables when downstream can consume repeated full snapshots. |
Spark supports different output modes for different query types and sinks. Check the API’s compatibility table before changing the sample to a stateful aggregation; an output mode that works for a stateless query may not fit the new query.
Keep progress recovery separate from sink delivery
A checkpoint records the query’s progress, including Kafka offset ranges processed by each trigger, and any managed streaming state. With a replayable source such as Kafka, Spark can restart from that progress instead of relying on Kafka consumer auto-commit. This recovers Spark’s source position and state. The checkpoint covers Spark’s progress; the sink must coordinate its own side effects.
The built-in Kafka sink has an at-least-once guarantee. Kafka may store a record even when its acknowledgement is lost; a retry can then write the same logical output again. Spark’s API guide lists Kafka as at-least-once and the Kafka sink documentation explains why duplicates can occur.
| Mechanism | Contribution | Boundary |
|---|---|---|
| Spark checkpoint | Saves query progress and managed state so a restart can resume. | External side effects need their own coordination with Spark’s progress. |
| Kafka sink | Writes each output record at least once when a query succeeds. | A logical record can appear more than once. |
| Idempotent destination logic | Lets a destination recognize a replay and avoid applying the same effect twice. | Consumers still need a deduplication rule, even when records have stable Kafka keys. |
For downstream Kafka processing, use a stable event ID as the record key and have the consumer or destination deduplicate by that ID. For a database, an upsert keyed by an immutable event identifier can make repeated writes safe. The uniqueness rule must match the business effect; generating a new random ID on each retry defeats deduplication.
If a destination supports transactions or an idempotency ledger, foreachBatch gives the application a batchId to use during writes. The destination must atomically record the batch ID with its effects, or make those effects idempotent. Spark documents foreachBatch as at-least-once by default; deduplication by batch ID can provide exactly-once behavior when the destination implements it. Sink-side coordination supplies that guarantee. The API guide’s foreachBatch section describes the batch ID and its semantics.
Event time and state
The sample is stateless, but many streaming jobs aggregate or deduplicate events. Those operations keep state between triggers. If events have an event-time column, withWatermark sets a delay threshold Spark uses to handle late data and eventually discard old state. Watermarks advance with observed event-time progress, independent of wall-clock time. Choose a threshold from observed event lateness and the amount of state the job can retain. In Append mode, a windowed aggregate is written when the watermark advances past the window’s allowed late-data threshold; Update mode can emit revised results before state is removed. Spark’s watermark documentation explains how the threshold affects late records, output modes, and state cleanup.
A checkpoint also ties recovery to the query. Keep its location stable across restarts of the same query, and reserve a separate path for each independent query. Spark documents restrictions on query changes made while reusing a checkpoint: changing the input source type is unsupported, and changing subscribed Kafka topics can produce unpredictable results. For incompatible changes, start a new query and plan source-offset and state migration explicitly. The recovery section lists the compatibility rules.
DStreams are legacy context
DStreams are Spark’s previous-generation streaming API. A DStream represents a stream as a sequence of RDDs and uses a StreamingContext. The Spark 4.3.0 guide says DStreams are a legacy project with no further updates and recommends Structured Streaming for streaming applications. Keep DStreams in view when maintaining an older codebase; use Structured Streaming for new pipelines. See the official DStreams guide and legacy notice.
Summary
- Use Structured Streaming for new Spark streaming work. The pipeline here uses the standard micro-batch trigger; Spark 4.3.0 also documents Real-time Mode with a narrower support matrix.
- Trigger intervals set a requested cadence. Measure end-to-end latency with your actual source, query, resources, and sink.
- Checkpoints recover Spark offsets and managed state from a replayable source. They do not make sink effects exactly once.
- The built-in Kafka sink is at-least-once. Add stable identifiers and destination-side deduplication or idempotent writes when duplicates would change business results.
- Treat DStreams as a legacy API when maintaining existing jobs.
Further reading
The Apache Kafka guide covers the broker and message-delivery side. Compare engine choices in the repository guides to Apache Spark and Apache Flink after you have defined your recovery and delivery requirements.
Category
Related Posts
Apache Spark DataFrames: Inspect a Shuffle in PySpark
Trace one PySpark 4.3.0 aggregation from input through its physical plan, then use Spark UI metrics to inspect shuffle volume and task skew.
Replay and Reprocessing in Event-Driven Systems
Learn how to replay event streams safely, choose offsets and cursors, isolate side effects, and recover projections without confusing replay with retry.
Apache Flink Event-Time Tutorial: State and Recovery
Follow one Apache Flink 2.3.0 event-time job through watermarks, late orders, checkpoint recovery, and a file sink, with delivery guarantees stated clearly.