Skip to main content

Structured Streaming

Module Duration: 4-5 hours Focus: Real-time data processing and stream analytics Prerequisites: Spark SQL and DataFrames

Overview

Structured Streaming is Apache Spark’s scalable and fault-tolerant stream processing engine built on the Spark SQL engine. It treats streaming data as an unbounded table that is continuously appended, allowing you to write streaming computations using the same DataFrame/Dataset API.

Key Concepts

Unbounded Table Model: Streaming data is treated as an append-only table that grows continuously. Micro-Batch Processing: Data is processed in small batches with latencies as low as 100ms. Event Time Processing: Process data based on timestamps embedded in the data, not arrival time. Fault Tolerance: Exactly-once semantics through checkpointing and write-ahead logs.

Structured Streaming Fundamentals

Basic Streaming Query

Scala Implementation

Output Modes

Complete Mode

Outputs the entire updated result table. Use for aggregations.

Append Mode

Only new rows added to the result table. Default mode.

Update Mode

Only rows that were updated in the result table.

Event Time Processing

Event Time vs Processing Time

Watermarking

Watermarks allow the system to track progress in event time and clean up old state.

Scala Watermarking

Stateful Operations

mapGroupsWithState

Track custom state for each group.

Scala mapGroupsWithState

flatMapGroupsWithState

For more complex stateful processing with multiple outputs per group.

Window Operations

Tumbling Windows

Fixed-size, non-overlapping windows.

Sliding Windows

Fixed-size, overlapping windows.

Session Windows

Dynamic windows based on activity gaps.

Scala Window Operations

Stream-Stream Joins

Inner Join

Outer Join

Scala Stream-Stream Join

Stream-Static Joins

Fault Tolerance and Checkpointing

Checkpointing

Recovery from Failures

Exactly-Once Semantics

Data Sources and Sinks

Kafka Source

Kafka Sink

File Sources

File Sinks

Memory Sink (Testing)

Trigger Modes

Processing Time Trigger

Once Trigger

Continuous Processing

Available Now Trigger

Monitoring and Management

Query Management

Multiple Queries

Progress Monitoring

DStreams (Legacy API)

Basic DStream Operations

Window Operations in DStreams

Real-World Use Cases

Real-Time ETL Pipeline

Fraud Detection System

Click-Through Rate (CTR) Calculation

Performance Optimization

Optimize Trigger Intervals

Optimize Watermarks

State Management

Partition Tuning

Common Pitfalls and Solutions

Issue 1: Late Data Handling

Problem: Data arriving after watermark causes dropped events. Solution:

Issue 2: State Explosion

Problem: Unbounded state growth causes OOM errors. Solution:

Issue 3: Checkpoint Compatibility

Problem: Schema changes break checkpoint recovery. Solution:

Issue 4: Memory Pressure

Problem: Large batches cause executor memory issues. Solution:

Hands-On Exercises

Exercise 1: Real-Time Word Count

Create a streaming word count application that processes text data.

Exercise 2: Session Analysis

Implement user session tracking with timeout.

Exercise 3: Join Streams

Implement stream-stream join for ad analytics.

Summary

Structured Streaming provides a powerful, fault-tolerant framework for real-time data processing:
  • Unified API: Use DataFrame/Dataset API for batch and streaming
  • Event Time: Process data based on event timestamps
  • Exactly-Once: Achieve exactly-once semantics with checkpointing
  • Stateful Operations: Track complex state across events
  • Stream Joins: Combine multiple streams with time bounds
  • Scalability: Handle high-throughput workloads

Key Takeaways

  1. Use watermarks appropriately to balance latency and completeness
  2. Choose output modes based on your use case
  3. Monitor state size and use timeouts to prevent memory issues
  4. Configure checkpoints for fault tolerance
  5. Optimize trigger intervals for your latency requirements

Next Steps

  • Practice with real streaming data sources
  • Implement complex stateful operations
  • Explore integration with Delta Lake
  • Study production deployment patterns
  • Learn advanced monitoring and troubleshooting

Continue to the next module to explore MLlib for distributed machine learning at scale.