Spark Structured Streaming Using Java
In this article, take a look at Spark structured streaming using Java.
Join the DZone community and get the full member experience.Join For Free
Spark provides streaming library to process continuously flowing of data from real-time systems.
Spark Streaming is originally implemented with DStream API that runs on Spark RDD’s where the data is divided into chunks from the streaming source, processed and then send to destination.
From Spark 2, a new model has been developed in Spark which is structured streaming that is built on top of Spark SQL engine working on DataFrames and Datasets.
Structured Streaming makes use of continuous data stream as an unbounded table being updated continuously as events are processed from the stream.
Spark streaming application can be implemented using SQL queries performing various computations on this unbounded data.
Structured streaming handles several challenges like exactly-once stream processing, incremental updates, etc.
Structured Streaming works on polling of data based on trigger interval for fetching the data from the source. An output mode is required while writing result data set to sink. It supports append mode (only new data elements added to the result table will be written to sink), update mode (only the data elements that are updated in the result table will be written to sink), complete mode (all items in the result table will be written to sink).
In built Sources and Sinks
Structured Streaming supports following in built data sources.
File Source: Allows to read the files placed in certain directory. The formats supported are text, CSV, parquet, JSON
Kafka Source: Streaming library provides Kafka consumer to read data from Kafka broker. This is highly used in production.
Socket Source: Data can be read from socket using socket connections in UTF-8 format
The various built in sinks supported are as follows
File sink: Stores the output to a directory
Kafka sink: Stores the output to one or more topics in Kafka
Console sink: Prints the output to console, used for debugging purpose
Memory sink: Output is stored in memory as in-memory table, used for debugging purpose
Foreach sink: Runs adhoc computation on the records in output
Handling Fault Tolerance
Structured streaming provides fault tolerance by using check pointing to save the state of job and restart the job from the failed stage. This is also applicable to Spark Streaming using DStreams.
In addition, Structured Streaming provides following conditional based recovery mechanism for fault tolerance.
- The source must be replayable which is not yet committed
- The streaming sinks are designed to be idempotent for handling reprocessing
In this demo, we will be seeing Spark Streaming with some computations using File source and generating output to console sink.
This use case contains sample csv data set related to employee containing "empId, empName, department" fields. The data in csv will be placed in particular location of folder.
Spark Stream inbuilt file source listens for the directory update event notifications and passes the data to computation layer for required analytics. The output is streamed to console in this example.
The following example is Spark Structured Streaming program that computes the count of employees in a particular department based on file streaming data
The output is streamed in batches where the first batch related to first file and second batch relates to second file etc
First csv file contains below data
Second csv file contains below data
The output of streaming query is as shown below where the count is grouped by department name. The 2nd batch data is aggregated with first batch based on key values and the output is updated in 2nd batch.
In this demo, we will be seeing implementation of Spark structured streaming reading from Kafka broker and computing aggregations on 2 minute window period for batch
In this use case, web application is continuously generating logged in session duration of the users to Kafka broker.
Using Spark streaming program, for every 2 minute window we compute the sum of session duration of the user logged into the website
The below is the Spark Streaming program in Java that computes the window based aggregations
Kafka broker in this example sends the messages in key value pair where value is coma delimited string with session duration and userName value.
The output of the above program contains sequence of batches on window computation
These use cases are built as maven project. The below are the dependencies added in pom.xml
Performance Tuning Tips
Here are few performance tips to be considered in the Spark streaming applications
1. In the above Spark streaming output for Kafka source, there are some late arrival data. For example as shown below, first version of user19 data might be supposed to be arrived in batch1, but this has arrived in batch 2 for computation.
There are scenarios of late arrival data and computation of this data has to be performed on the earlier window data. In this scenario, the result of earlier window data is stored in memory and then aggregated with the late arrival data. Frameworks like Spark Streaming takes care of this process. But there might be possibilities of more memory consumption as the historical data is stored in the memory till the missed data is arrived which might lead to memory accumulation. In these scenarios, Spark streaming has feature of watermarking which discards the late arrival data when it crosses threshold value. In some cases, business results might have mismatch because of discarding these values. To avoid these type of issues, instead of applying watermarking feature, custom functionality has to be implemented to check the timestamp of data and then store it in HDFS or any cloud native object storage system to perform batch computations on the data. This implementation leads to complexity.
2. In the above Spark streaming output for kafka source, there is some performance lag where the data computation is slow. When we open the spark console and view the task and job info, we can predict the root cause for this issue.
The job is taking more than 1.5 minutes
When we open the task info of the completed job, we can see there are many partitions created with 0 shuffling tasks handled. These dummy tasks on these partitions will take some time to start and stop and there by increase the total processing time which leads to latency
By default 200 partitions are getting created as shown above. Spark while processing uses shuffling when grouping operation is performed. During shuffling, partitions of data will be created and each partition will have the tasks assigned. Spark SQL has to take decision to use how many partitions to use. In these scenarios, more partitions will be created during shuffle read and many partitions will not have data to work on. This is because there are not many keys in the output as partitions size. These dummy tasks on these partitions will take some time to start and stop and there by increase the total processing time which leads to latency. The recommendation is to set the below property in the Spark code. This property determines the number of partitions that are used when shuffling data for joins or aggregations
With this parameter, we can observe the job performance has been increased and also optimal number of partitions are created as shown below which is viewed from Spark console
In this way, we can leverage Spark Structured Streaming in real time applications and get benefits of optimized Spark SQL based computing on the streaming data.
Opinions expressed by DZone contributors are their own.