Spark Structured Streaming

Earn 25 points (50 with Pro) in two steps

  1. ① Read through the lesson — each section gets a ✓ as you scroll through it.
  2. ② When every section has a ✓, tap Complete lesson.

0 of 13 read · keep scrolling

✦ See fewer ads and earn double points — 50 a lesson instead of 25 — with Pro

Spark Structured Streaming: Mastering Real-Time Data Pipelines

Introduction: Why Real-Time Matters

In the modern landscape of data engineering, the ability to process information as it arrives is no longer a luxury; it is a fundamental requirement. Historically, organizations relied on batch processing—collecting data throughout the day and running heavy jobs overnight to generate reports. While reliable, this approach leaves stakeholders waiting hours or even days for critical insights. Spark Structured Streaming changes this dynamic by allowing developers to treat live data streams as if they were static tables, enabling near real-time analytics with the same tools used for batch processing.

Understanding Spark Structured Streaming is essential for any data engineer because it bridges the gap between complex event-driven architectures and standard data manipulation workflows. By leveraging the Spark SQL engine, Structured Streaming provides fault tolerance, consistency, and a unified API that simplifies the development of streaming applications. Whether you are building fraud detection systems, monitoring server logs, or tracking real-time user behavior on a website, Structured Streaming offers a path to build scalable and resilient pipelines without needing to manage the low-level complexities typically associated with stream processing.

Not read yet

The Core Concept: The Unbounded Table

To understand how Structured Streaming works, you must shift your mental model from "events flowing through a pipe" to an "unbounded table." In Spark, a streaming data source is treated as a table that is constantly growing. Every time a new piece of data arrives, it is appended to this table. Your query operates on this table as if it were a standard dataset, and Spark handles the underlying mechanics of reading new data, updating the state, and producing the result.

This approach is powerful because it allows you to use familiar SQL syntax or the DataFrame API to perform operations like filtering, joining, and aggregation on streaming data. You do not need to rewrite your code when moving from batch to streaming; you simply change the input source. This unification reduces the cognitive load on engineering teams and ensures that the logic used to test your code in a batch environment remains consistent when deployed into a production streaming environment.

Callout: Batch vs. Streaming Mental Model In traditional batch processing, you define a fixed dataset, process it, and write the output. In Structured Streaming, you define an input source as a streaming DataFrame and an output sink. Spark continuously checks for new data, processes the increments, and updates the sink. The query logic remains identical, but the execution engine maintains state across these micro-batches to ensure accuracy.

Not read yet

Setting Up Your First Streaming Pipeline

Building a streaming pipeline in Spark typically involves three distinct steps: defining the input source, specifying the processing logic, and configuring the output sink. Before writing any code, ensure you have a Spark session initialized with the necessary streaming configurations.

1. Defining the Input Source

Spark supports various sources, including Apache Kafka, file systems (like S3 or HDFS), and socket connections for testing purposes. To read from a source, you use the readStream method on your Spark session object.

# Example: Reading from a directory of JSON files as a stream
# This treats each new file appearing in the directory as a stream of data
streaming_df = spark.readStream \
    .format("json") \
    .schema(json_schema) \
    .load("/path/to/data/input")

2. Processing Logic

Once you have your streaming DataFrame, you can apply standard transformations. These transformations are lazy; they define the plan but do not execute until you start the streaming query.

# Perform a simple aggregation: counting events per user
# We group by 'user_id' and count the occurrences
processed_df = streaming_df.groupBy("user_id").count()

3. Configuring the Output Sink

The sink is where your processed data lands. Common sinks include console (for debugging), memory, Parquet files, or Kafka. The output mode determines how the sink is updated.

# Start the query and write to the console
query = processed_df.writeStream \
    .outputMode("complete") \
    .format("console") \
    .start()

query.awaitTermination()

Note: Always use awaitTermination() at the end of your script. This prevents the main thread from exiting immediately, which would cause the streaming query to stop before it has a chance to process any data.

Not read yet

Understanding Output Modes

The output mode is a critical configuration parameter that dictates how data is written to the sink. Choosing the wrong mode can lead to duplicate data, missing records, or performance bottlenecks.

  • Append Mode: Only the new rows added to the result table since the last trigger are written to the sink. This is the default and is most efficient for operations where you only care about new data (e.g., logging events).
  • Complete Mode: The entire result table is written to the sink every time an update occurs. This is used for aggregations where you need the final count of all items processed so far.
  • Update Mode: Only the rows that were updated in the result table since the last trigger are written. This is useful for aggregations where you want to see the changing state of a calculation without rewriting the entire table.
Mode Use Case Performance Impact
Append Writing raw events to a log Low; only appends new data
Complete Full aggregation reports High; rewrites entire state
Update Incremental dashboard updates Medium; updates only changed rows

Not read yet

Handling State and Watermarking

One of the most challenging aspects of streaming is handling late-arriving data. In a real-world system, network latency or system failures might cause data to arrive out of order. If you are calculating a windowed aggregation, such as counting events in 5-minute intervals, you need a way to tell Spark when it can stop waiting for late data. This is where watermarking comes in.

Watermarking allows you to define a threshold for how long Spark should wait for late events. If an event arrives with a timestamp older than the current maximum timestamp minus the watermark, it is discarded. This prevents the system's state from growing indefinitely, as it provides a clear signal to clear out old data that is no longer relevant.

# Applying a watermark to handle late events
# We allow events to be up to 10 minutes late
windowed_counts = streaming_df \
    .withWatermark("event_time", "10 minutes") \
    .groupBy(
        window("event_time", "5 minutes"),
        "user_id"
    ).count()

Callout: Why State Management Matters Streaming applications are stateful. When you perform a groupBy or a join, Spark must remember the previous counts or data points. If you do not use watermarking, the "state" will grow forever, eventually exhausting the memory of your executors. Watermarking acts as a cleanup mechanism, keeping your memory usage predictable and stable.

Not read yet

Working with Kafka as a Source and Sink

Apache Kafka is the industry standard for streaming data transport. Spark Structured Streaming has native integration with Kafka, making it the most common way to build production-grade pipelines. To use Kafka, you must include the spark-sql-kafka library in your build configuration.

Reading from Kafka

When reading from Kafka, you specify the bootstrap servers and the topic. You can also define the starting offset, such as earliest to read from the beginning of the topic or latest to start from the current point.

kafka_df = spark.readStream \
    .format("kafka") \
    .option("kafka.bootstrap.servers", "host1:9092,host2:9092") \
    .option("subscribe", "user-activity") \
    .option("startingOffsets", "earliest") \
    .load()

Writing to Kafka

Writing is equally straightforward. You need to ensure your DataFrame has a value column (and optionally a key column), which represent the payload sent to the Kafka topic.

# Write the processed data back to a Kafka topic
query = processed_df.selectExpr("CAST(user_id AS STRING) AS key", "to_json(struct(*)) AS value") \
    .writeStream \
    .format("kafka") \
    .option("kafka.bootstrap.servers", "host1:9092") \
    .option("topic", "processed-activity") \
    .option("checkpointLocation", "/path/to/checkpoints") \
    .start()

Not read yet

Fault Tolerance and Checkpointing

A streaming application must be resilient to failures. If a node in your cluster crashes, the application should be able to recover and continue exactly where it left off without losing data or producing duplicates. Spark achieves this through Checkpointing and Write-Ahead Logs (WAL).

A checkpoint directory is a location on a reliable storage system (like S3 or HDFS) where Spark saves the state of the query and the progress of the offsets. When a failure occurs, the Spark driver reads the checkpoint, identifies the last successfully processed offset, and restarts the tasks from that point.

Warning: Never delete the contents of your checkpoint directory while a streaming job is running or if you intend to restart it. If the checkpoint data is lost or corrupted, you lose the ability to recover the state of your stream, effectively forcing you to restart the entire pipeline from scratch.

Not read yet

Best Practices for Production

Building a streaming pipeline that runs 24/7 requires more than just functional code. You need to consider performance, monitoring, and operational stability.

1. Optimize Trigger Intervals

The trigger setting controls how frequently Spark processes the incoming data. Using trigger(processingTime='10 seconds') creates a micro-batch every 10 seconds. If you need lower latency, you can use trigger(availableNow=True) for batch-like processing or trigger(continuous=True) for sub-millisecond latency (though continuous processing has significant limitations).

2. Monitor Your Streams

Always monitor the "Input Rate" and "Processing Rate." If your input rate consistently exceeds your processing rate, your system is falling behind, and the latency will grow indefinitely. Use the Spark UI to track the duration of each batch and identify bottlenecks in your transformations.

3. Schema Management

Streaming data often comes in JSON or Avro formats. Always define an explicit schema when reading data. Relying on schema inference is dangerous because it requires Spark to scan the first batch of data, which can lead to errors if the data structure changes unexpectedly. Define your schema using StructType to ensure consistency.

4. Optimize Joins

Joining a static table with a streaming table is a common requirement. Spark optimizes this by caching the static table. However, if you are joining two streaming tables, ensure you have watermarks on both sides. Without watermarks, the join will attempt to keep all historical data in memory, leading to an OutOfMemoryError.

5. Managing Resources

Streaming jobs are long-running. You should allocate a dedicated cluster or a set of resources for your streaming jobs to prevent them from competing with batch jobs. If a batch job consumes all the cluster resources, your streaming job will stall, leading to data backlogs.

Not read yet

Common Pitfalls and How to Avoid Them

Pitfall 1: Unbounded State

As mentioned earlier, performing aggregations without watermarks is the most common cause of job failure. If your logic involves grouping or joining, always evaluate if the state can grow over time. If it can, implement a watermark.

Pitfall 2: Overloading the Output Sink

If you are writing to a database or a file system, ensure the sink can handle the incoming load. If you write small files to S3/HDFS too frequently, you will create a "small file problem" that degrades performance for subsequent read operations. Use trigger intervals to batch data into larger, more manageable chunks.

Pitfall 3: Ignoring Serialization

Streaming data is constantly being moved between memory and disk or across the network. Using efficient serialization formats like Kryo can significantly reduce the CPU overhead and memory usage of your streaming application.

Pitfall 4: Hardcoding Configurations

Avoid hardcoding Kafka brokers, topic names, or file paths. Use environment variables or configuration files. This makes your code portable across development, staging, and production environments, and allows you to update connection strings without changing the underlying logic.

Not read yet

Step-by-Step: Building a Complete Pipeline

Let’s walk through the creation of a robust streaming pipeline that ingests logs from Kafka, filters them, and writes the results to a Parquet file.

  1. Initialize Spark Session: Ensure you have the necessary dependencies. You will need spark-sql-kafka-0-10.

    spark = SparkSession.builder \
        .appName("LogProcessor") \
        .getOrCreate()
    
  2. Define Schema: Explicitly define the structure of your incoming logs to avoid runtime errors.

    from pyspark.sql.types import StructType, StringType, TimestampType
    schema = StructType() \
        .add("timestamp", TimestampType()) \
        .add("level", StringType()) \
        .add("message", StringType())
    
  3. Read and Transform: Read from Kafka, parse the JSON payload, and filter for 'ERROR' level logs.

    raw_df = spark.readStream \
        .format("kafka") \
        .option("kafka.bootstrap.servers", "localhost:9092") \
        .option("subscribe", "logs") \
        .load()
    
    parsed_df = raw_df.selectExpr("CAST(value AS STRING)") \
        .select(from_json("value", schema).alias("data")) \
        .select("data.*")
    
    error_df = parsed_df.filter(parsed_df.level == "ERROR")
    
  4. Write Output: Write the filtered logs to a Parquet directory with checkpointing.

    query = error_df.writeStream \
        .format("parquet") \
        .option("path", "/data/errors") \
        .option("checkpointLocation", "/data/checkpoints/errors") \
        .outputMode("append") \
        .start()
    
    query.awaitTermination()
    

Not read yet

Comparison: Structured Streaming vs. Other Approaches

When choosing a streaming framework, it is helpful to compare Spark Structured Streaming with other popular options like Apache Flink or Apache Storm.

  • Spark Structured Streaming: Best for teams already using Spark. It offers a unified API, excellent integration with the Spark ecosystem, and a lower learning curve. It is primarily micro-batch based, which is sufficient for most use cases but not ideal for sub-millisecond latency.
  • Apache Flink: Designed from the ground up for true event-at-a-time streaming. It offers lower latency and more complex windowing capabilities than Spark, but it has a steeper learning curve and a different programming model.
  • Apache Storm: An older framework that focuses on low latency. It is largely being replaced by Flink and Spark because it lacks the high-level abstractions and ecosystem support of its successors.
Feature Spark Structured Streaming Apache Flink
Model Micro-batch (mostly) Event-at-a-time
API Unified SQL/DataFrame DataStream API
Complexity Low High
Ecosystem Strong (Spark/SQL) Strong (Java/Scala)
Latency Milliseconds Sub-millisecond

Not read yet

Advanced Techniques: Custom Sinks and ForeachBatch

Sometimes, you need to write data to a system that doesn't have a native Spark connector. In these cases, you can use the foreachBatch sink. This method allows you to execute a function on every micro-batch of data, giving you complete control over how the data is written.

# Example: Using foreachBatch to write to an external database
def write_to_db(df, batch_id):
    # This function is called for every micro-batch
    df.write.format("jdbc").mode("append").save(...)

query = processed_df.writeStream \
    .foreachBatch(write_to_db) \
    .start()

This is incredibly powerful because it allows you to perform custom logic, such as deduplication or complex routing, within the context of a micro-batch while still benefiting from Spark’s fault tolerance and checkpointing mechanisms.

Operational Monitoring and Maintenance

A production streaming job is never "set and forget." You must implement a strategy to monitor the health of your pipelines.

  • Latency Metrics: Track the time between when an event is generated and when it is processed. If this grows, investigate the processing time per batch.
  • Checkpoint Health: Periodically check the size of your checkpoint directory. If it is growing rapidly, you might have too many small files or an improperly managed state.
  • Resource Utilization: Keep an eye on executor memory. If you see high garbage collection activity, your state might be too large for the allocated memory.
  • Logging: Ensure your application logs are being sent to a central logging system (like ELK or Splunk). If a stream fails, you need the stack trace to understand why.

Tip: If you find that your streaming job is consistently failing due to data quality issues, consider adding a "dead letter queue" to your pipeline. Filter out malformed records and write them to a separate sink for later inspection, allowing the main pipeline to continue processing valid data.

Not read yet

Key Takeaways

  1. Unified API: Spark Structured Streaming allows you to use the same DataFrame and SQL code for both batch and streaming, significantly reducing development time and complexity.
  2. Unbounded Tables: Think of streaming data as an ever-growing table. This mental model simplifies the process of applying complex transformations, windowing, and aggregations.
  3. Fault Tolerance: Always use checkpointLocation to ensure that your streaming job can recover from failures without losing data. Never delete or corrupt the checkpoint directory.
  4. State Management: Use watermarks to handle late-arriving data and to prevent state from growing indefinitely in memory. This is essential for any windowed or grouping operation.
  5. Operational Awareness: Monitor your input vs. processing rates. If the processing rate is slower than the input rate, your system will eventually fail due to latency or memory exhaustion.
  6. Flexibility: Leverage foreachBatch to interface with external systems that lack native Spark connectors, providing a bridge between your streaming pipeline and specialized databases or APIs.
  7. Production Readiness: Use explicit schemas, manage your resources, and implement robust monitoring to ensure your streaming pipelines remain stable and reliable in a production environment.

By mastering these concepts, you can move beyond simple data ingestion and build sophisticated, real-time data platforms that provide immediate value to your organization. Start small, focus on understanding how state and watermarking interact, and build your operational experience by observing how your jobs perform over time.

Not read yet

Each section gets a ✓ as you scroll through it. Tap the button to jump to the next one.