Stream Processing - Spark Streaming
Introduction
Spark Streaming Overview
- “Low Latency”, High-throughput and Fault Tolerant
- Discretized Stream (DStream): Micro-batches of RDDs
- Leverage Core Components from Spark
- RDD data model and API
- Data Partitioning and Shuffles
- Task Scheduling
- Monitoring/ Instrumentation
- Scheduling and Resource Allocation
Discretized Stream Processing
Run a streaming computation as a series of very small, deterministic batch jobs
- Chop up the live stream into batches of X seconds
- Spark treats each batch of data as RDDs and processes them using RDD operations
- Finally, the processed results of the RDD operations are returned in batches
- Micro-Batching

DStream Abstraction
Spark Streaming API
Transformations: modify data from one DStream to another
- Standard RDD operations:
map,filter,distinct,countByValue,reduceByKey,join, … - Stateful, Sliding Window-based Operations:
window,updateStateByKey,countByValueAndWindow
- Standard RDD operations:
Output Operations: send data to external entity
saveAsHadoopFiles: saves to HDFSforeach: do anything with each batch of results
Example 1
Get HashTags from Twitter1
2
3
4
5
6
7
8// DStream: a sequence of distributed datasets (RDDs) representing a distributed stream of data
val tweets = ssc.twitterStream(<Twitter username>, <Twitter password>)
// new DStream - transformation: modify data in one DStream to create another DStream
val hashTags = tweets.flatMap (status => getTags(status))
// Output operation: to push data to external storage
hashTags.saveAsHadoopFiles("hdfs://...")
Spark program vs Spark Streaming program
Spark Streaming program on Twitter stream:
1
2
3val tweets = ssc.twitterStream(<Twitter username>, <Twitter password>)
val hashTags = tweets.flatMap(status => getTags(status))
hashTags.saveAsHadoopFiles("hdfs://...")Spark program on Twitter log file:
1
2
3val tweets = sc.hadoopFile("hdfs://...")
val hashTags = tweets.flatMap(status => getTags(status))
hashTags.saveAsHadoopFile("hdfs://...")
Example 2
Count the HashTags1
2
3val tweets = ssc.twitterStream(<Twitter username>, <Twitter password>)
val hashTags = tweets.flatMap (status => getTags(status))
val tagCounts = hashTags.countByValue()
Example 3
- Window-based Operations

Count the HashTags over last 1 min1
2
3
4
5val tweets = ssc.twitterStream(<Twitter username>, <Twitter password>)
val hashTags = tweets.flatMap (status => getTags(status))
// Sliding Window Operation: (window length, sliding interval)
val tagCounts = hashTags.window(Minutes(1), Seconds(1)).countByValue()
Word Count with Kafka
1 | // Entry point of streaming functionality |
Combine SQL with Streaming
Interactively query streaming data with SQL and Dataframes1
2
3
4
5
6
7// Register each batch in stream as table
kafkaStream. foreachRDD { batchRDD =>
batchRDD. toDF. registerTempTable("events")
}
// Interactively query table
sqlContext.sql("select * from events")
- Example
1
2
3
4
5
6
7
8
9
10
11
12
13val ssc = new StreamingContext(sc, Seconds(5))
val sqlContext = new SQLContext(sc)
val tweets = TwitterUtils.createStream(ssc, auth)
val transformed = tweets.filter(isEnglish).window(Minutes(1))
transformed. foreachRDD { rdd =>
// Tweet is a case class containing necessary
rdd.map(Tweet.apply(_)).registerAsTable("tweets")
}
// ------------------------------------------------
SELECT text FROM tweets WHERE similarity (tweet) › 0.01
SELECT getClosestCountry(lat, long) FROM tweets
Fault Tolerance
- RDDs remember the operations that created them
- Batches of input data are replicated in memory for fault-tolerance
- Data lost due to worker failure, can be recomputed from replicated input data
- Therefore, all transformed data is fault-tolerant

DStream Interface
The DStream interface primarily defines how to generate an RDD in each batch interval
- List of dependent (parent) DStreams
- Slide Interval, the interval at which it will compute RDDs
Function to compute RDD at a time t
Mapped DStream
- Dependencies: Single parent DStream
- Slide Interval: Same as the parent DStream
- Compute function for time t: Create new RDD by applying map function on parent DStream’s RDD of time t
1
2
3override def compute (time: Time): Option[RDD[U]] = {
parent.getOrCompute(time).map(_.map[U](mapFunc))
}
Windowed DStream
- Dependencies: Single parent DStream
- Slide Interval: Window sliding interval
- Compute function for time t: Apply union over all the RDDs of parent DStream between times t and (t – window length)
Network Input DStream
Base class of all input DStreams that receive data from the network
- Dependencies: None
- Slide Interval: Batch duration in streaming context
- Compute function for time t: Create a BlockRDD with all the blocks of data received in the last batch interval
- Associated with a Network Receiver object
DStream Graph
Spark Streaming program → DStream Graph
1
2
3t = ssc.twitterStream("...")
.map(...)
t.foreach(...)
DStream Graph → RDD Graphs → Spark jobs
1
2
3
4
5
6
7
8t1 = ssc.twitterStream("...")
t2 = ssc.twitterStream("...")
t = t1.union(t2).map(...)
t.saveAsHadoopFiles(...)
t.map(...).foreach(...)
t.filter(...).foreach(...)- Every interval, RDD graph is computed from DStream graph
- For each output operation, a Spark action is created
- For each action, a Spark job is created to compute it

System Model
Receiving Data

Job Scheduling

- Each output operation used generates a job
- More jobsàmore time taken to process batchesà higher batch duration
- Job Manager decides how many concurrent Spark jobs to run
- Default is 1, can be set using Java property spark.streaming.concurrentJobs
- If you have multiple output operations, you can try increasing this property to reduce batch processing times and so reduce batch duration
- Each output operation used generates a job
Persistence / Caching
- If a DStream is set to persist at a storage level, then all RDDs generated by it set to the same storage level
- Window-based DStreams are automatically persisted in memory
RDD Checkpointing
- Saving RDD to HDFS to prevent RDD graph from growing too large
RDD checkpointing is necessary because stateful DStream operators can have infinite lineages
Large lineages lead to
- Large closure of the RDD objectàlarge task sizesàhigh task launch times
- High recovery times under failure
Solution: Periodic RDD checkpointing
- Checkpoint too frequent: HDFS writing will slow things down
- Checkpoint too infrequent: Task launch times may increase
- Default setting checkpoints at most once in 10 seconds
- Try to checkpoint once in about 10 batches
Performance Tuning
- Step 1: Achieve a stable configuration that can sustain the streaming workload
- Step 2: Optimize for lower latency

