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

  1. Chop up the live stream into batches of X seconds
  2. Spark treats each batch of data as RDDs and processes them using RDD operations
  3. Finally, the processed results of the RDD operations are returned in batches
  • Micro-Batching

DStream Abstraction

Spark Streaming API

  1. 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
  2. Output Operations: send data to external entity

    • saveAsHadoopFiles: saves to HDFS
    • foreach: do anything with each batch of results

Example 1

Get HashTags from Twitter

1
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
      3
      val 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
      3
      val tweets = sc.hadoopFile("hdfs://...")
      val hashTags = tweets.flatMap(status => getTags(status))
      hashTags.saveAsHadoopFile("hdfs://...")

Example 2

Count the HashTags

1
2
3
val 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 min

1
2
3
4
5
val 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Entry point of streaming functionality
val context = new StreamingContext(conf, Seconds(1))

// Create DStream from Kafka data
val lines = KafkaUnits.createStream(context, ...)

// Split lines into words
val words = lines.flatMap(_.split(" "))

// Count the words
val wordCounts = words.map(x => (x,1)).reduceByKey(_ + _)

// Print some counts on screen
wordCounts.print()

// Start receiving and transforming the data
context.start()

Combine SQL with Streaming

Interactively query streaming data with SQL and Dataframes

1
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
    13
    val 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
      3
      override 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
    3
    t = ssc.twitterStream("...")
    .map(...)
    t.foreach(...)

  • DStream Graph → RDD Graphs → Spark jobs

    1
    2
    3
    4
    5
    6
    7
    8
    t1 = 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

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

    1. Large closure of the RDD objectàlarge task sizesàhigh task launch times
    2. 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

Achieving Stable Configuration