30 Mins

6. Structured Streaming

Micro-batching vs. Continuous Processing

Spark Structured Streaming primarily utilizes a micro-batch architecture where the engine collects data over a small interval, transforming it into a temporary DataFrame. This paradigm offers high throughput and leverages the mature Spark SQL query optimizer. The latency is generally determined by the trigger interval, typically measured in milliseconds to seconds, providing a balance between fault tolerance and near-real-time requirements.

In contrast, Continuous Processing is designed for sub-millisecond latency requirements. By running a long-lived task that processes records as they arrive, it sacrifices some of the sophisticated state-management optimizations of micro-batching for raw performance. While micro-batching achieves exactly-once guarantees via WAL (Write-Ahead Logs) and checkpointing, continuous processing relies on epoch-based checkpointing for state consistency.

Operator Note: Use trigger(availableNow=True) for cost-efficient batch-like processing on streams.
Python 3
# Define a streaming read source from Kafka
df = spark.readStream.format("kafka").option("kafka.bootstrap.servers", "localhost:9092").option("subscribe", "events").load()

# Micro-batch processing with a 5-second trigger
query = df.writeStream.trigger(processingTime='5 seconds').outputMode("append").format("console").start()

Windowing and Watermarking

Handling late-arriving data is a fundamental challenge in distributed stream processing. Structured Streaming uses watermarks to define how long the system should wait for late data to arrive before dropping it. A watermark is defined as $T_{watermark} = T_{max} - L$, where $T_{max}$ is the observed maximum event time and $L$ is the allowed lateness threshold.

Windowing operations, such as tumbling or sliding windows, work in tandem with watermarks. If a window ends at time $W_{end}$ and the watermark has progressed beyond that point, Spark considers the window closed and triggers the computation. Without watermarking, the state size would grow indefinitely as the engine would never know when to evict old window keys from the state store.

Operator Note: Always apply withWatermark on the time column before grouping by window to prevent OOM errors.
Python 3
from pyspark.sql.functions import window

# Apply 10-minute windows with a 2-minute lateness threshold
windowed_df = df.withWatermark("event_time", "2 minutes") \
  .groupBy(window("event_time", "10 minutes"), "user_id") \
  .count()

Stateful Operations and Exactly-Once Guarantees

Stateful streaming involves maintaining internal state across micro-batches, such as maintaining a running sum or sessionizing events. Spark utilizes a state store (typically HDFS or S3-backed) to keep this state consistent. By storing state in checkpoints, Spark can recover from failures by replaying logs from the last successful offset.

The system ensures exactly-once semantics by using a combination of idempotent sinks and metadata tracking. During a commit, Spark writes the result of the micro-batch along with the current offset; if the job crashes, the recovery process re-executes the batch from the last consistent offset, ensuring that the downstream system does not process duplicate data.

Operator Note: Always provide a unique checkpoint location for each streaming query to avoid state corruption.
Python 3
# Configuring checkpointing for fault-tolerant state
query = result_df.writeStream \
  .format("delta") \
  .option("checkpointLocation", "s3://my-bucket/checkpoints/streaming_job") \
  .start()

Knowledge Check

Ready to test your understanding of 6. Structured Streaming?

Back