Apache Kafka is the perfect base for any streaming application: a solid, highly-available, fault-tolerant platform that makes reliable communication between streaming components as easy as writing to a disk.
Apache Flink adds the power of stateful data transformations to the picture. It's able to calculate, persist, recover and process data in a similar distributed, highly-available, fault-tolerant fashion to that provided by Kafka. Apache Flink is available from a variety of languages: from the more traditional Java and Scala all the way to Python and SQL.
A previous post showed how you can create your Docker version of Apache Flink including its SQL Client. In this post, we will demonstrate how you can use the best streaming combination — Apache Flink and Kafka — to create pipelines defined using data practitioners' favourite language: SQL!
Apache Kafka is our basic data storage platform. We can create a cluster via Aiven's Command line interface in our terminal:
Loading code...
This sets up an Apache Kafka cluster named demo-kafka in google-europe-west3, enabling Kafka REST APIs and topic auto creation. If you want to wait until the demo-kafka service is ready to use, you can use the following command:
Loading code...
2. Set up Apache Flink on Docker
In my previous post I outlined how to properly set up Apache Flink on Docker. With Docker, we can have a working environment running in minutes without needing to fiddle with installation and configuration. The previous post provides instructions on how to set up such an environment and how to create a file-to-PostgreSQL data pipeline. In this article, I'm going to assume that you correctly configured Apache Flink, and that the service is up and running.
Here's a quick summary of the required steps if you didn't follow the previous post. Clone the aiven/flink-sql-cli-docker repository with the following code in your terminal
Loading code...
Now open the flink-sql-cli-docker folder and start the docker compose:
Loading code...
At this stage, when running
Loading code...
you should get an output like this:
Loading code...
This tells you that Flink's job manager, task manager and sql-client containers are all ready to be used.
Aiven for Apache Flink®
A fully managed service for Apache Flink for all your real time ETL and streaming analytics use cases.
Aiven for Apache Kafka enables SSL authentication by default. To safely connect to it from Apache Flink, we need to use the Java Keystore and Truststore. We can generate them with the following command in our terminal, assuming we are in the flink-sql-cli-docker folder you created in the previous steps:
Loading code...
The command creates a folder named certs under settings and stores the certificate files together with a Keystore and Truststore (named client.keystore.p12 and client.truststore.jks), secured with the password123 password string.
4. Create some test data with Kafkacat
Now we can use Kafkacat to create some data. After installing it, let's create a file kafkacat.config under our certs folder with the following content:
Loading code...
To find the <host> and <port> parameters, use the following call:
Loading code...
Now open a new terminal, navigate to the certs folder, and execute this:
Loading code...
Kafkacat sends every new line appearing in the terminal as message to Kafka in the people topic. Paste the following lines into the terminal:
Loading code...
Four messages have been sent to people topic in our Apache Kafka environment. Keep this window open - you'll use it again later to insert more messages.
5. Define the source Kafka topic as Flink Table
As mentioned in the previous post, we can enter Flink's sql-client container to create a SQL pipeline by executing the following command in a new terminal window:
Loading code...
Now we're in, and we can start Flink's SQL client with
Loading code...
Define a source for the people Kafka topic with the following code (replace the <host> and <port> parameters to correctly point to Kafka as mentioned):
Loading code...
The command above defines a Flink table named people_source with the following properties:
Three columns: name, country and age
Connecting to Apache Kafka (connector = 'kafka')
Reading from the start (scan.startup.mode) of the topic people (topic) which format is JSON (value.format) with consumer being part of the my-working-group consumer group.
Connecting via the bootstrap.servers and using the SSL security protocol (properties.security.protocol) with the client.truststore.jks and client.keystore.p12 stores.
After executing it, we should receive a message saying [INFO] Table has been created.. Please note that this doesn't mean it's working! We can test it properly by issuing the following sql statement from the sql-client terminal:
Loading code...
Which will result in
Loading code...
To leave Flink's table view, press Q.
Solving the volume permission problem on Linux
If you're on Linux, you'll probably hit an error like this:
Loading code...
This error is caused by a couple of factors:
The client.keystore.p12 file generated is by default readable only from the user who created it (-rw -- --)
The way docker-compose mounts the volumes: the folder where keystore files resides is owned by user root (uid 1000)
The combination of the two make the file client.keystore.p12 inaccessible by Flink (executed by user flink with uid 9999). To solve the problem, make the keystore readable by the flink user by redefining the folder ownership:
Find its id with the following command in a terminal from the flink-sql-cli-docker folder in your host:
Loading code...
The result should be similar to this:
Loading code...
Now we can use flink's uid to set the settings folder ownership, always by executing the following command in the same terminal window (replacing the 9999 with flink's uid from the above call if necessary)
Loading code...
After executing it, retry the select * from people_source; statement. It should now succeed.
6. Transform and insert data
Now it's time to see the beauty of Flink in action: we're going to set up a process that analyses streaming data coming from the people Kafka topic, calculates some aggregated KPIs and publishes them to a target datastore, in our case a new Kafka topic. And we're doing everything using only SQL statements.
Flink is so flexible that you can run a similar exercise with a huge variety of technologies as sources or targets. The Kafka examples shown in this blog could be replaced with any JDBC database, local files, OpenSearch or Hive with only a few changes in our SQL definitions. The list of supported connectors can be found on Flink's website.
Defining the target Kafka topic as a Flink table
For the purposes of this article, let's assume we want to push aggregated data to a new Kafka topic containing the average age and number of people in a specific country. To do so, we first need to define Flink's target table structure with the following code in Flink's sql-cli terminal window (replacing, as before, the <host>:<port> section with Kafka's endpoint):
Loading code...
The above SQL creates a Flink table with three columns: country primary key, avg-age, and nr_people. The connector is upsert-kafka since we want to update the topic always with the most updated version of the KPIs per country (PRIMARY KEY (country)). The WITH clause specifies that we will push data to the country_agg Kafka topic using the same connection properties as the people_source connector.
What's even cooler about this is that with a few small amendments to the WITH statement above, we could publish the result of our data pipeline to a completely different technology endpoint.
Setting up the data pipeline
Once the country_target destination endpoint is defined, we can finally create the SQL pipeline by defining the query aggregation logic and related insert statement. The following code provides exactly what we need, so we can paste it in Flink's sql-cli terminal window:
Loading code...
We should receive a message telling us that our SQL pipeline was successfully deployed, like this:
Loading code...
Now if we query the country_target table from Flink's SQL client with:
Loading code...
We should see something like this:
Loading code...
This tells us that we have one entry for USA and England as expected, but three entries for Italy - which is weird, since we only pushed two records for that country. This is becasue we want to keep only the current KPIs status, and are experiencing Flink's sql-client changelog result-mode. The above result tells us that we had, in order:
Insert entry for Italy with 1 people of average age of 25 -> Sign +
Delete entry #1 -> Sign -
Insert entry for Italy with 2 people of average age of 35 -> Sign +
Flink's changelog view is great if we want to check how KPIs have been calculated over time. On the other hand, if we just want to browse the up-to-date situation we can move to Flink's table result mode by executing the following in Flink's sql-cli terminal:
Loading code...
And now, when re-issuing the select * from country_target; it will show just the current situation:
Loading code...
7. Check the pipeline output
Now we want to verify that the Flink records have been successfully written to the desired Kafka topic. From a new terminal window positioned on the flink-sql-cli-docker/settings/certs we can execute this:
Loading code...
The command will start Kafkacat in consumer mode (-C) listening on topic country_agg (the same that we used in Flink's table definition). The output will be the list of updated records on the various KPIs:
Loading code...
If we now add a row to our people topic via the first Kafkacat window in producer mode, thus:
Loading code...
We can immediately see the streaming pipeline in action with a new line appearing in the country_agg Kafka topic on the Kafkacat consumer terminal, containing the updated avg_age and nr_people KPIs:
Loading code...
Wow, we just built a whole analytics pipeline!
We started by inserting JSON records into a Kafka topic with kafkacat representing our streaming input. The topic was then registered in Flink which we later configured to transform and aggregate the data. The output was finally stored in a new Kafka topic.
The whole pipeline was built with just three SQL statements and, with minor changes, we could quickly swap the data source or target using Flink as an "abstraction layer" on top of our data technology. This was a very simple use case, but Flink can be a game changer in a huge variety of situations. Your batch ETL now seems a bit dated, doesn't it?
Build a streaming anomaly detection system
Use Aiven for Apache Flink® for data transformation, Aiven for Apache Kafka® for data streaming, and Aiven for PostgreSQL® for data storage/query.
SQL is the best known and most loved language among data practitioners. The union of Apache Kafka and Flink provides a simple, highly available and scalable toolset that allows them to focus on building real time data pipelines rather than learning and debugging complex code. Flink SQL capabilities enhance all the benefits of building Kafka-based data hubs, with the capability of joining in external data assets and delivering data pipeline output to a huge variety of targets.
Additional resources that you might find interesting:
In the meantime, make sure you follow our changelog and blog RSS feeds or our LinkedIn and Twitter accounts to stay up-to-date with product and feature-related news.
Name Command State Ports
--------------------------------------------------------------------------------------------------------------
flink-sql-cli-docker_jobmanager_1 /docker-entrypoint.sh jobm ... Up 6123/tcp, 0.0.0.0:8081->8081/tcp
flink-sql-cli-docker_sql-client_1 /docker-entrypoint.sh Up 6123/tcp, 8081/tcp
flink-sql-cli-docker_taskmanager_1 /docker-entrypoint.sh task ... Up 6123/tcp, 8081/tcp
[INFO] Submitting SQL update statement to the cluster...
[INFO] Table update statement has been successfully submitted to the cluster:
Job ID: 95b57225d702ab9c9402daba10fe6a84
select * from country_target;
+/- country avg_age nr_people
+ USA 40 1
+ England 35 1
+ Italy 25 1
- Italy 25 1
+ Italy 35 2
SET execution.result-mode = table;
country avg_age nr_people
USA 401England 351 Italy 352
kafkacat -F kafkacat.config -C -t country_agg
{"country":"USA","avg_age":40,"nr_people":1}{"country":"England","avg_age":35,"nr_people":1}{"country":"Italy","avg_age":25,"nr_people":1}{"country":"Italy","avg_age":35,"nr_people":2}% Reached end of topic country_agg [0] at offset 4
{"name":"Mark","country":"England","age":37}
{"country":"England","avg_age":36,"nr_people":2}
% Reached end of topic country_agg [0] at offset 5