Spark Streaming - Fault Tolerance

Updated 5 Oct 2026

🛡️ Fault Tolerance (Critical!)

How Spark Streaming Achieves Fault Tolerance

1. RDD Lineage

RDDs remember the sequence of operations that created them.

Input Data → flatMap → map → reduce → Output
    ↑
Replicated &
stored on
multiple nodes

Lineage Example:

tweets = ssc.twitterStream(...)
hashTags = tweets.flatMap(getTags)
counts = hashTags.map(x => (x,1)).reduceByKey(_+_)

Lineage DAG:

twitterStream → flatMap → map → reduceByKey
    ↑             ↑        ↑         ↑
  Where         What     What      What
  to get      function function  function
  data

2. Input Data Replication

Batches of input data are replicated in memory across multiple worker nodes.

Input Batch #42:
  Node 1: [Copy 1] ✓
  Node 2: [Copy 2] ✓
  Node 3: [Copy 3] ✓
  • Fault-tolerant storage
  • If one node fails, data still available on other nodes

3. Lost Data Recovery

If a worker fails:

Before Failure:
  tweets RDD:    [Node1] [Node2] [Node3] [Node4]
                    ↓       ↓       ↓       ✗ (failed!)
                 flatMap  flatMap flatMap
                    ↓       ↓       ↓    
  hashTags RDD:  [Node1] [Node2] [Node3] [Missing!]

After Recovery:
  1. Input data still available (replicated)
  2. Recompute lost partition using lineage:
     tweets(Node2) → flatMap → hashTags(Node4_new)
  3. Deterministic computation → same result

Process:

  1. Input data still available (it's replicated)
  2. Lost RDD partitions recomputed from input using lineage
  3. Computation is deterministic → Same input → Same output

Exactly-Once Semantics ✅

  • State data NOT lost even if worker dies
  • Immutable RDDs → Cannot change value of result
  • Exactly once semantics for all transformations
  • ✅ No double counting!

Comparison:

SystemGuaranteeProblem
StormAt-least-onceMay process twice → double count
TridentExactly-onceSlow (transactions)
Spark StreamingExactly-onceFast (lineage) ✓

Why This Matters: In financial applications, you can't count a transaction twice or lose a transaction. Spark Streaming guarantees correct results even with failures!


Performance Benchmarks

Scalability Test Results

Can process 6 GB/sec (60M records/sec) on 100 nodes at sub-second latency

Test Setup:

  • 100 streams of data
  • 100 EC2 instances (4 cores each)

Grep Performance (Simple Pattern Matching)

Nodes1-sec batches2-sec batches
202.0 GB/s2.0 GB/s
503.5 GB/s3.2 GB/s
1006.5 GB/s6.0 GB/s

WordCount Performance (Aggregation)

Nodes1-sec batches2-sec batches
200.5 GB/s0.4 GB/s
501.5 GB/s1.2 GB/s
1003.0 GB/s2.4 GB/s

Key Insight: Near-linear scalability with node count! 📈


Comparison with Other Systems

Throughput per Node (100-byte records)

Grep:

  • Spark Streaming: ~65 MB/s per node
  • Storm: ~12 MB/s per node
  • Ratio: Spark is 5-6× faster 🚀

WordCount:

  • Spark Streaming: ~27 MB/s per node
  • Storm: ~6 MB/s per node
  • Ratio: Spark is 4-5× faster 🚀

Records per Second per Node

  • Spark Streaming: 670,000 records/sec/node
  • Storm: 115,000 records/sec/node
  • Apache S4: 7,500 records/sec/node

Spark Streaming is 6× faster than Storm, 89× faster than S4!


Fast Fault Recovery

Recovers from failures within 1 second!

Processing Time Graph:
│
2.0 │         Failure! ↓
    │  ████████████████████████████████
1.5 │  ████████████████████████████████
    │  ████████████████████████████████  ← Brief spike
1.0 │  ████████████████████████████████
    │  ████████████████████████████████
0.5 │  ████████████████████████████████
    │
0.0 └─────────────────────────────────→ Time
    0   15   30   45   60   75   90 (seconds)

Red bars = recovery period (barely visible!)

Test: Sliding WordCount on 10 nodes with 30s checkpoint interval

Production Impact: For a system processing millions of events/second, 1-second recovery means you lose at most a few million events (which can be replayed). Traditional systems might take minutes, losing hundreds of millions of events!


🎯 Vision: One Stack to Rule Them All

Unified Processing Stack

        ┌─────────────────────────┐
        │   SAME CODEBASE         │
        └─────────────────────────┘
                   │
      ┌────────────┼────────────┐
      ↓            ↓            ↓
┌──────────┐ ┌──────────┐ ┌──────────┐
│Interactive│ │  Batch   │ │ Stream   │
│  (Shell) │ │Processing│ │Processing│
└──────────┘ └──────────┘ └──────────┘

Code Reuse Across Modes

The SAME transformation logic works in all three modes!

Interactive Exploration (Spark Shell)

$ ./spark-shell
scala> val file = sc.hadoopFile("smallLogs")
scala> val filtered = file.filter(_.contains("ERROR"))
scala> val mapped = filtered.map(_.split('\t')(2))
scala> mapped.collect()

Batch Processing (Production)

object ProcessProductionData {
  def main(args: Array[String]) {
    val sc = new SparkContext(...)
    val file = sc.hadoopFile("productionLogs")
    val filtered = file.filter(_.contains("ERROR"))
    val mapped = filtered.map(_.split('\t')(2))
    mapped.saveAsTextFile("hdfs://...")
  }
}

Stream Processing (Real-time)

object ProcessLiveStream {
  def main(args: Array[String]) {
    val ssc = new StreamingContext(...)
    val stream = ssc.kafkaStream(...)
    val filtered = stream.filter(_.contains("ERROR"))
    val mapped = filtered.map(_.split('\t')(2))
    mapped.saveAsHadoopFiles("hdfs://...")
  }
}

Difference: Only the data source changes!

  • Shell: sc.hadoopFile
  • Batch: sc.hadoopFile
  • Stream: ssc.kafkaStream

Everything else is IDENTICAL! 🎉


Typical Workflow Integration

Unified Data Pipeline:

1. EXPLORE (Interactive)
   └─→ Spark Shell/PySpark
       └─→ Identify problems
           Test transformations
           
2. TEST (Batch)
   └─→ Spark Standalone Programs
       └─→ Run on production logs
           Validate at scale
           
3. DEPLOY (Streaming)
   └─→ Spark Streaming
       └─→ Monitor live streams
           Catch problems in real-time

Real-world Example - Uber:

  • Spark Shell: Explore historical ride data, test features
  • Spark Batch: Generate daily/weekly reports
  • Spark Streaming: Track real-time ride requests, match drivers

Same codebase, same team, same cluster - three use cases!


🚀 Getting Started

Installation

Spark Streaming is included with Apache Spark 3.2.1+

Download: https://spark.apache.org/downloads.html

Documentation: https://spark.apache.org/docs/latest/streaming-programming-guide.html

Quick Example

from pyspark.streaming import StreamingContext
 
# Create streaming context (1-second batches)
ssc = StreamingContext(sc, 1)
 
# Create DStream from TCP socket
lines = ssc.socketTextStream("localhost", 9999)
 
# Count words
words = lines.flatMap(lambda line: line.split())
word_counts = words.map(lambda word: (word, 1)).reduceByKey(lambda a, b: a + b)
 
# Print results
word_counts.pprint()
 
# Start processing
ssc.start()
ssc.awaitTermination()

✅ Summary

Spark Streaming is...

✅ Scalable to large clusters

  • Horizontal scaling: Add nodes → process more data
  • Tested to 100+ nodes

✅ Fast

  • Second-scale latencies (0.5-2 seconds)
  • 6 GB/sec throughput on 100 nodes
  • 6× faster than Storm

✅ Simple

  • Batch-like programming model
  • Familiar RDD operations
  • Less code than traditional streaming

✅ Integrated

  • Works with Spark batch processing
  • Works with Spark SQL
  • Same codebase for multiple use cases

✅ Fault-tolerant

  • Efficient fault-tolerance via lineage
  • Exactly-once semantics
  • Fast recovery (< 1 second)

🎓 When to Use Spark Streaming

✅ Use Spark Streaming When:

  • Need near-real-time processing (seconds)
  • Want to reuse code between batch and streaming
  • Need strong fault-tolerance guarantees
  • Already using Spark ecosystem
  • Need stateful processing (windows, aggregations)
  • Processing millions of events/second

❌ Don't Use Spark Streaming When:

  • Need sub-second latency (use Flink or custom solutions)
  • Data rate is very low (simple cron jobs suffice)
  • Only doing simple filtering/routing (use Kafka Streams)
  • Need true millisecond latency (use Storm)

💡 Production Best Practices

1. Batch Interval Selection

Start:     5-10 seconds
Optimize:  Decrease if processing can keep up
Monitor:   Processing time vs batch interval

Rule: Processing time should be < batch interval

Good:  Batch=2s, Processing=1.5s ✓
Bad:   Batch=1s, Processing=2s   ✗ (falling behind!)

2. Memory Management

  • Enable memory-only storage for frequently accessed data
  • Use checkpointing for long windows
  • Monitor GC pressure
  • Tune executor memory based on window size
// Enable checkpointing
ssc.checkpoint("hdfs://checkpoint")
 
// Persist with memory-only
stream.persist(StorageLevel.MEMORY_ONLY)

3. Fault Tolerance Setup

// Enable checkpointing for stateful operations
ssc.checkpoint("hdfs://checkpoint")
 
// Use reliable receivers
val stream = ssc.receiverStream(new ReliableReceiver(...))
 
// Test failure scenarios regularly!

4. Performance Tuning

  • Tune number of partitions

    stream.repartition(100)  // More parallelism
  • Enable data locality

    spark.locality.wait = 3s
    
  • Use Kryo serialization

    spark.serializer = org.apache.spark.serializer.KryoSerializer
    
  • Optimize window operations (use incremental!)

    // Good: Incremental
    reduceByKeyAndWindow(_ + _, _ - _, Minutes(10), Seconds(1))
     
    // Bad: Recompute everything
    window(Minutes(10), Seconds(1)).reduceByKey(_ + _)

☁️ Cloud Services Using Spark Streaming

AWS

  • Amazon EMR: Managed Spark Streaming
  • Kinesis + Spark: Real-time analytics
  • AWS Glue: ETL with Spark Streaming

Google Cloud

  • Dataproc: Managed Spark clusters
  • Pub/Sub + Dataproc: Event streaming

Azure

  • Azure Databricks: Collaborative Spark environment
  • Azure HDInsight: Managed Spark Streaming
  • Event Hubs + Spark: Real-time ingestion

Databricks

  • Delta Live Tables: Production-grade pipelines
  • Structured Streaming: Modern streaming API
  • Auto Scaling: Dynamic resource allocation

Enterprise Examples

CompanyUse CaseScale
NetflixRecommendations, quality monitoring500B+ events/day
UberReal-time pricing, fraud detectionMillions/sec
PinterestUser engagement, recommendationsBillions/day
AlibabaTransaction processingMillions/sec

📚 Glossary

TermDefinition
DStreamDiscretized Stream - sequence of RDDs
Batch IntervalTime duration for each micro-batch (e.g., 1 sec)
Window LengthHow far back to look in time
Sliding IntervalHow often to compute windowed operations
CheckpointingSaving state to reliable storage
Exactly-onceEach record affects state exactly once
At-least-onceRecord may be processed multiple times
LineageSequence of transformations creating RDD

🔑 Key Takeaways

Core Concepts

  1. Micro-Batch Architecture

    • Stream divided into small batches
    • Each batch processed as RDD
    • Near-real-time with batch efficiency
  2. DStreams = Sequence of RDDs

    • Same operations as batch RDDs
    • Immutable and distributed
    • Fault-tolerant via lineage
  3. Smart Window Operations

    • Incremental computation (300× faster!)
    • Only process entering/leaving batches
    • Need inverse reduce function
  4. Exactly-Once Semantics

    • No double counting
    • Lineage-based recovery
    • Faster than transaction-based systems
  5. Unified Programming Model

    • Same code for batch, interactive, streaming
    • Only data source changes
    • Huge productivity gain

📐 Important Formulas

Window Operation

window(windowLength,slidingInterval)\boxed{\text{window}(\text{windowLength}, \text{slidingInterval})}

Incremental Window Count

New Count=Old Count−Leaving Batch+Entering Batch\boxed{\text{New Count} = \text{Old Count} - \text{Leaving Batch} + \text{Entering Batch}}

Performance Gain

Speedup=Window SizeSliding Interval\boxed{\text{Speedup} = \frac{\text{Window Size}}{\text{Sliding Interval}}}

Example: 10-minute window, 1-second slides = 600× less computation


🎯 Exam Tips

Q1: What is the key difference between Spark Streaming and traditional streaming?

Answer:

  • Traditional: Record-at-a-time processing
  • Spark Streaming: Micro-batch processing (small batches of records)
  • Benefit: Fault tolerance via lineage, exactly-once semantics

Q2: How does Spark Streaming achieve fault tolerance?

Answer:

  1. Input data replicated across nodes
  2. RDD lineage tracks transformations
  3. If partition lost → recompute from input using lineage
  4. Deterministic computation ensures same results

Q3: What's the difference between window() and countByValueAndWindow()?

Answer:

  • window(): Naive - recomputes all data in window
  • countByValueAndWindow(): Smart - incremental computation
  • 300× speedup by only processing entering/leaving batches

Q4: What are map vs flatMap?

Answer:

  • map: One input → One output (preserves structure)
  • flatMap: One input → Zero/one/many outputs (flattens)
  • Use flatMap when splitting elements (e.g., sentence → words)

Q5: What is exactly-once semantics?

Answer:

  • Each record processed exactly once
  • No double counting, no lost data
  • Achieved through immutable RDDs and lineage
  • Critical for financial/counting applications

🏆 Final Summary

Spark Streaming solves the two-stack problem:

Before:

Custom Stream System + Hadoop Batch = 2× everything!

After:

Spark Streaming + Spark Batch = Unified platform!

Key Benefits:

  • ⚡ 6× faster than Storm
  • 🛡️ Exactly-once semantics
  • 🔄 Code reuse across batch/streaming
  • 📊 Linear scalability
  • ⏱️ Sub-second recovery

Use for: Social media analytics, real-time monitoring, fraud detection, recommendations, log processing


Good luck on your exam, Google! 🚀

Resources: