If you’re a software engineer, there’s a possibility that you’ll relate to this– aren’t you always wondering about how things work? Aren’t you always curious about how one thing fits into another? It could be as little as wondering about how traffic lights are synchronized or something as complex as how Indian Railways manage and run their services on so many routes.
These inquisitive thoughts can occur anytime and one such struck me while watching the news. I was switching channels on my TV when I stopped on one particular news channel. The news reporter was shouting his guts out about a news which had garnered a lot of public hatred. At the bottom of the screen, a series of tweets showed people’s reaction to it. I was wondering what can be the relation between a breaking news, people’s reaction to it and how it amplifies the magnanimity of the news. For example- how would people react when something as big as demonetization would be announced?
Once this thought came into my mind, my engineering mind started kicking in. I began to formulate a problem statement- “If I wanted to achieve something like this how would that happen? What would I need to start it? How would I want it to work?”
After defining the problem statement, I started looking for tools which would help me in achieving the goals I had set for myself. I started looking for how such problems are solved in the industry.
And I took a step forward and shared this idea with my colleagues at Quovantis. I told them that I am interested to learn how real time data works, and quite unsurprisingly, I found a bunch of like-minded people (trust me, we’ve got loads here). We were motivated to chase our goals and we immediately started working on it. We decided on a problem statement and formed teams to tackle the problems in different ways.
The problem was simple –
“Analyzing real time streaming Twitter data and displaying it in a meaningful way”
In simple words, we aimed to design a sample streaming data solution of analyzing tweets frequency and display the data visually. A single Twitter producer would be fetching streaming data from twitter and sending it out to a Kafka topic. Each team would be connecting to Kafka to get the stream of data.
I know it might be a little bit too much for you, so before we start diving into the details, let us cover up some basics first.
What is streaming data?
Streaming data is the data which is generated repeatedly through several data sources operating at the same time. Such data may include information like log files, server metrics, trades in market etc.
The simplest example of streaming data is Twitter tweets. Tweets are like a never ending flow of data which can be used to perform interesting analysis. We would be using this to analyze the tweet frequency per unit time.
What are the tools available to process streaming data?
The challenge with processing streaming data is that there is no end to the incoming data, so you’re never done with processing. Another challenge that comes with streaming data is of aggregating it. Since it’s a continuous stream of data we need to be careful of how much data we want to aggregate.
There are different tools for processing streaming data, one of them is Spark Structured Streaming.
Spark Structured Streaming is a fault-tolerant stream processing engine built on the Spark SQL Engine (ref).
We would be using tweepy for consuming the twitter stream. The tweepy package makes it easier to handle uninteresting but important stuff like authentication, session management, reading incoming messages etc.
Before starting with the code, we would need to create an application and generate the keys from there. Copy the following:
- API key
- API key secret
- Access token
- Access token secret
Here’s the Link for app creation steps.
Once we have the above, we can start with the code. Please note: we would be manually handling the threading here because there is some issue with streaming library in tweepy. It raises the IncompleteRead Exception which causes it to stop the stream. (There are a lot of SO threads around it. Link | Link | Link )
First, let’s create a StreamListener class which would handle the incoming streaming data. We would also create a class named Twitter which would handle the exceptions and restart the restart the stream.
We have a kafka producer instance in the StreamListener class. This is used to send out the data to Kafka.
The on_status method of the Listener receives the tweets and pushes it to Kafka.
The driver module which would run read configs and run the Twitter Stream.
This takes care of our source of streaming data. You can use tools like supervisor to easily start and stop the producer.
Now, let’s move to the solution part.
In this approach, we would be using the spark structured streaming to analyze the tweets frequency and display the same using Grafana.
We’ve kept the spark streaming consumer separate from the database writer because of the following reasons:
- Spark Structured Streaming doesn’t have a native stream sink to InfluxDB. We would need to implement our own ForEachWriter if we want the spark application to write to InfluxDB directly.
- Spark consumer can be scaled separately from the database writer.
- Having both separately gives us fault tolerance against database failures. In case the database goes down, our spark consumer would still keep working and pushing the records to Kafka.
With streaming data the choice of database becomes a little different than our traditional databases because the nature of data being stored is very different. Mostly the data stored with streaming data sources is time series data.
Time series data refers to any similar data which is stored in time order. This could include server metrics, performance monitoring, network data, sensor data, events, clicks, etc.
Since our data would be growing over time and there isn’t any relationship in the data, we don’t need a RDBMS. TSDBs are very efficient in performing large aggregation queries on the timestamps.
Out of the available options we decided to move forward with InfluxDB, which is made grounds up for such type of data. More info can be found here.
Visualisation of the data
Storing and retrieving the data is only half the story. Another important part of real time streaming solutions is the visualization of data. Visualizations make it easier to understand what’s going on. Looking at plain numbers can be difficult while making out sense from huge amounts of data. This is where the visualization tools come into play.
There are a lot of such dashboards available for use and we narrowed down to Grafana for this case. The primary concern in our scenario is to display large time series data which is stored in InfluxDB. Grafana provides easy connection to InfluxDB. It is one of the best tools for visualization out there. More info can be found here.
With our architecture in place, let’s get our hands a little dirty with code.
Spark Structured streaming consists of 3 parts:
- Source – This is the Kafka from which where we are getting our raw tweets data.
- Operations – These are the aggregation operations which we perform on the data. In our case we would be doing a simple groupBy and counting the number of records in the given window.
- Sink – This refers to the Kafka topic where we would be sending out our data.
To start with any spark application, we need to create a spark session. Let’s create a spark session with the app name as Twitter count.
For reading data from a Kafka topic, we would need to create a stream. Specify the settings such as the bootstrap servers and the topic to listen. While fetching from Kafka, the data is returned in the form of key and value. The key being the topic (and partition) and the value is the actual data. So we need to extract data from the single data column into a dataframe.
To do this, we would need to specify the schema of the data. A schema is of StructType which is a list of StructFields.
Once we have the schema in place, we can load the json from the data column as follows:
One thing to note here is that with spark 2.4+, we don’t need to specify the schema. This example was written with spark 2.3
With our source ready, we can move to operations part. We wanted to calculate the number of tweets per minute. In spark structured streaming, there are concepts of windows and watermark.
A window is time-event grouping. It denotes a logical start and end for a sliding dataframe.
Since streaming data can receive data out of sync, we use a watermark to decide till how long we would accept the data. We can keep the watermark to 10 secs, which would mean that we are not allowing data later than the current max event time – 10s.
To create a window we need to have a timestamp type column. Since our original data had timestamp in UNIXMS, we need to modify that to Timestamp to create a window and define the watermark.
As per our need, we would be doing a groupBy on the window to get the count of the data. The window length is 1 minute and the sliding interval is 30 secs. It means that we are calculating the number of tweets in a minute for each 30 secs.
Watermark is the threshold on how late the data is expected in terms of event time.
In our case, the watermark of 1 sec means that any event which is earlier than 1 sec from the max event time faced would be ignored.
To write data to Kafka, we need to do the reverse of what we did while reading the data from Kafka. We need to transform the data so that it is in the form of JSON string. The following code transforms the data and starts the stream.
Till now, we have created a stream, performed operations on it, specified the sink and started the query. Now if we exit the program here, nothing would happen. The streams are running on spark and your primary thread is free. We need to make sure our application doesn’t exit till the streams (known as query) aren’t terminated. To achieve that we can make use of the following:
So, now we have started getting our data on Kafka. We need to store this data to InfluxDB.
Writing to influxDB is quite simple. We would first create a InfluxDBWriter Class. This class has two methods – switch_database and write_rows.
We would also be creating a simple Kafka consumer to fetch the data from Kafka. We would use value_deserializer to transform the incoming records to JSON for easier parsing downstream.
Till now have the data in database, the only thing left is to show the data on the UI. For that we would need to add a data source for InfluxDb in Grafana. Follow the steps here
- From the top menu click on Dashboards and then new dashboard.
- You would see a small green icon on the page. Click on it and choose “add panel” -> “graph”
- In the From choose the name of the database and in the where choose the topic. These would be the same ones which we use in the database writer.
- Do select field(count).
- Now you should see something like the following:
Click on save dashboard on the bar and it should be saved.
We can play more around various options here.
Hope you find the steps easy and have as much fun as we guys had while developing this.
We can use Spark Structured Streaming in a variety of places, like analyzing the real time stock prices and comparing them with their historical values.
Or else, we can use analyze two different sources of data to find the correlation between them.
Possibilities are endless. We’re only limited by our thinking 🙂