Stream Data Processing using Apache Beam
While collecting data in big scale is already difficult, extracting insights from them is even more exhausting. Fortunately, with the rise of high-level alternatives like Apache Beam, things are now much easier to manage (though not completely painless).
In this tutorial we will guide you through the steps of writing a Beam App as well as executing such an App on a Spark cluster.
Overview
As a brief introduction, Apache Beam is a high-level data processing framework. One of the most outstanding features about Beam is its unified data model design. That means:
- There’s no (or little) differences between different data sources, no matter they are a static file, a database table, or a unbounded Kafka stream. Beam will do the abstraction and unify them.
- Different kinds of data can be joined together as if they were from the same data source.
On top of that, Beam is also runner-independent. Beam App can be run inside a local machine, in a Spark cluster, in the Flink application, and even by Google Data Flow, a fully managed service that you don’t need to manage any machine provisioning.
With all the available runners supported by Beam, keep in mind that the application code stays the same: write once, run anywhere.
We will write a Beam Application that:
- Reads a file stored in the cloud storage, including Google Cloud Storage and AWS S3,
- Performs a word count transformation in the Beam pipeline,
- Writes the results to a local file system or the cloud storage.
We will develop and test the App in a local environment. Once we finish the development, we will deploy it to AWS cloud by:
- packaging the whole App into a stand-alone JAR file using Apache Maven, and
- provisioning an AWS EMR cluster and executing the Beam App in Apache Spark
Prerequisites
All resources are published in the following GitHub repo:
We also assume that you have:
- An AWS account
- Installed AWS CLI with pre-configured credentials
This demo is run on the region us-west-2.
Beam Setup
We will be building our Beam App using Apache Maven. First we have to install the tools.
For Mac users, Homebrew installation is recommended:
Install Java 8 and Apache Maven
brew tap caskroom/versions
brew cask install java8
brew install mavenOr, if Docker is preferred, simply launch a Maven container from the official image:
docker run -it \
-v /path/to/wordcount-spark-runner-example:/app \
-w /app \
maven:3.6.0-jdk-8 /bin/bash> mvn ...
Apache Maven is an automation tool for compiling, testing, and packaging Java projects. As npm in Node.js, pip in Python, composer in PHP, Apache Maven is yet another management tool to automate engineers’ day to day work.
The Classic “Word Count” Beam App
The official MinimalWordCount example already covered the details. This section complements the official tutorial by:
- Introducing a proper project setup, and
- Re-writting the codes in Scala, as an alternative for those who prefer Scala over Java
Bootstrap Project from Template
Instead of writing everything from scratch, it’s much easier to use a template.
mvn archetype:generate \
-DgroupId=com.example.beam \
-DartifactId=wordcount-app \
-Dversion=1.0.0 \
-DarchetypeGroupId=net.alchim31.maven \
-DarchetypeArtifactId=scala-archetype-simple \
-DarchetypeVersion=1.7 \
-DinteractiveMode=falseThe above command generates a project namely wordcount-app in Scala. When the command ends, the generated project is ready to be compiled and run by:
cd wordcount-app
mvn scala:run -DmainClass=com.example.beam.App
[INFO] Scanning for projects...
...
[INFO] --- scala-maven-plugin:3.3.2:run (default-cli) @ wordcount-app ---
Hello World!
concat arguments =The next step is to extend this project into a production Beam App. It’s highly recommended to use Java IDE like IntelliJ IDEA or Visual Studio Code in order to enjoy features like auto import and syntax hints.
Adding dependencies
Let’s take a look at the pom.xml inside the project directory.
The POM stands for Project Object Model, which is used for defining project configurations such as which libraries to install, how to build and test, etc. If you are familiar with Node.js, it’s almost the same as the package.json, albeit in different syntax.
Like NPM offers an official repository https://www.npmjs.com/ for everyone to look for useful packages, Maven also maintains a central repository https://mvnrepository.com/.
Apache Beam SDK are also hosted in that repo. To include them, simply add the following lines between the <dependencies> and </dependencies>:
What libraries are included?
- The Beam SDK, to write our Beam App.
- The Beam Direct Runner, to run our App in local machine (more on other running modes later).
- The GCP library for Beam, to read the input file from Google Cloud Storage.
These libraries will be automatically installed when the App is running in Maven.
Now, we are good to start writing our sample App.
The Application Code
Open the App file src/main/scala/com/example/beam/MinimalApp.scala in your favourite editor. Then, replace the Hello World code with the following Scala code:
The official tutorial already documented the basic concepts of a Beam pipeline. For more implementation details, refer to the annotated codes of the MinimalWordCountExample.
Running the App in Local
Simply run the App by the command (or using IDE):
mvn scala:run -DmainClass=com.example.beam.MinimalAppand see it in action.
You will see files are created in the output/ directory. Let’s check out its contents:
$ ls -1 output
wordcount-00000-of-00005
wordcount-00001-of-00005
wordcount-00002-of-00005
wordcount-00003-of-00005
wordcount-00004-of-00005$ head output/wordcount-00000-of-00005
Dismissing: 1
blasts: 2
after: 13
temper: 2
approves: 2
warrant: 2
V: 6
policy: 1
o: 38
embossed: 1
Yep, it’s the word count we desired for.
Parameterize the App
In the above codes, we are hardcoding everything. This is not so good.
We will improve it by allowing the App to accept custom configurations. Fortunately, Beam’s PipelineOptions already did most of the heavy lifting, only minor code changes are needed.
First, extend the PipelineOptions and define our parameters:
The newly defined parameters will be passed into the App via CLI. Update the codes to accept the input arguments:
(Note: the _* is the varargs expansion in Scala. Check out this SO Question for details.)
When executing the App, supply the arguments as follows.
mvn scala:run -DmainClass=com.example.beam.App \
-DaddArgs="--inputPath=gs://apache-beam-samples/shakespeare/kinglear.txt|--outputPath=output/wordcount"Logging
The Beam SDK itself produces a bunch of logs which describes what’s going on under the hood. However, we have to supply our own logger or it will just show SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
Get Gene Ng’s stories in your inbox
Join Medium for free to get updates from this writer.
One popular choice is the Logback. Simply add one more dependency in the pom.xml:
And create a file src/main/resources/logback.xml with this minimal config:
This is to simply tell the App to log messages with log level equal or higher than INFO to STDOUT. Check out the official manual for more configurations.
Now re-run the App. You should be able to see Beam SDK messages are properly logged onto the console.
Adding Custom Log
With the logging features configured, why not also log some custom messages?
In the output, the custom logs will take the name com.example.beam.App$ so as to differentiate from the Beam logs.
10:59:30.415 [direct-runner-worker] INFO org.apache.beam.sdk.io.WriteFiles - Finalizing 4 file results
10:59:30.415 [direct-runner-worker] INFO org.apache.beam.sdk.io.FileBasedSink - Finalizing for destination null num shards 4.
...
10:59:30.528 [main] INFO com.example.beam.App$ - Done.Deploying to AWS EMR
Before Putting on Cloud …
We have to realize that our local machine is quite different from a Spark cluster on AWS. To name a few:
- Saving the results to the local file system is not reliable. The data should be stored in somewhere permanent and highly available, such as AWS S3;
- Spark cluster do not have Beam dependencies or Maven installed, which means the Beam App needs to be self-contained.
We will go through the tweaks in order to make it runnable on cloud.
Putting the Output to AWS S3
To enable writing files to S3, we have to include one more library:
When using AWS SDK, it’s always better to specify a default AWS region.
Next, all we need to do is to specify a S3 path in the format s3://<bucket>/<path> in the argument.
mvn scala:run -DmainClass=com.example.beam.App \
-DaddArgs="--inputPath=s3://example-bucket/kinglear.txt|--outputPath=s3://example-bucket/beam/wordcount"Beam will match the file protocol and automagically find the suitable adapter. (gs:// → GCP adapter, s3:// → AWS adapter)
Create a single executable JAR
We will be using the spark-submit command to run the App in Spark. That means we have to:
- Add Spark Runner support to the App
- Package the whole App with all of the dependencies into a single JAR.
(In the Java world, this “JAR with all dependencies packed as a single executable” thing is sometimes called Uber JAR. This name originates from the German word “Über”, meaning “over”, “above” or “across”.)
To enable Spark support, we need to install the beam-runner-spark dependencies. And to be safe, also include the Spark libraries explicitly:
To compile a Uber JAR, a popular choice is to use the Maven Shade plugin. Not only does it include all dependencies, it can also avoid potential conflicts (e.g. two libraries importing different versions of the same package) by renaming them.
Put this inside the <build><plugins></plugins></build> brackets:
(NOT <build><pluginManagement><plugins>! Read the XML tags carefully!)
Note: If you are using names other than com.example.beam.App, update the value in the <mainClass> bracket.
Now we can compile and run the Uber JAR simply by:
mvn package
java -jar target/wordcount-app-1.0.0-shaded.jar \
--inputPath=s3://example-bucket/kinglear.txt \
--outputPath=s3://example-bucket/beam/wordcountIn the last step, upload this Uber JAR (yes, the >100MB bulk) to a S3 bucket you own.
(Replace the example-bucket with a unique name)
aws s3api create-bucket \
--bucket example-bucket \
--region us-west-2 \
--create-bucket-configuration LocationConstraint=us-west-2aws s3 cp ./target/wordcount-app-1.0.0-shaded.jar \
s3://example-bucket/wordcount-app-1.0.0-shaded.jar
Provision a EMR Cluster
To run Beam App in Spark, we first launch a Hadoop cluster with Spark support.
AWS EMR (Elastic MapReduce) is a managed service to provision and maintain Hadoop clusters with various features like auto scaling and Spark job management. This would be a good place to start.
All configurations are provided in this tutorial file, except one that requires user input:
In the wordcount-spark-runner-example/setup/cloudformation.yml, look for the LogUri property:
Uncomment and replace it with a proper S3 bucket location. This step is optional, but if there’s no log config, the EMR will not write any logs and thus it will be harder to debug.
After that, run the command to create EMR cluster using AWS CloudFormation. This may take around 10 minutes to finish.
aws emr create-default-rolesaws cloudformation create-stack \
--stack-name DataBeamEmr \
--template-body file://wordcount-spark-runner-example/setup/cloudformation.yml \
--capabilities CAPABILITY_NAMED_IAM \
--region us-west-2
Visit the CloudFormation console, click into the DataBeamEmr stack, and look for the Resources tab.
Remember the Physical ID j-XXXXXXXXXXXXX for later use.
Add a Job Flow Step
Now we have a working cluster, it’s time to actually run the Beam App in Spark.
Instead of SSH-ing into the instance and run the App within the terminal, AWS provided a neat integration call Job Flow Steps. It’s basically a sequence of commands to run in the cluster, but with better GUI and logging support.
To add a Job Flow Step, run the command:
aws emr add-steps \
--cluster-id j-XXXXXXXXXXXXX \
--steps Type=CUSTOM_JAR,Name="Beam",Jar="command-runner.jar",ActionOnFailure=CONTINUE,Args='[spark-submit,--deploy-mode,client,--class,com.example.beam.App,s3://example-bucket/wordcount-app-1.0.0-shaded.jar,--runner=SparkRunner,--inputPath=s3://example-bucket/kinglear.txt,--outputPath=s3://example-bucket/beam/wordcount]'The command looks clumsy due to the CLI syntax, but basically, it tells EMR to run the packaged Beam App JAR (stored in the S3 bucket) with the input arguments.
When running the command on your EMR cluster, replace the values of:
--cluster-id j-XXXXXXXXXXXXXs3://example-bucket/wordcount-app-1.0.0-shaded.jar--inputPath=s3://example-bucket/kinglear.txt--outputPath=s3://example-bucket/beam/wordcount
If successful, the CLI will return a Step ID like the following.
Review the Logs
If LogUri is configured correctly, AWS will upload all job execution logs to the specified S3 location.
In addition, the AWS EMR console also provides a simple UI to checkout the logs:
Just click into the cluster, select “Steps” and then “View logs”:
Extra: The “java.lang.NoSuchMethodError”
Sometimes this error will happen when running in EMR:
The exact reason is unknown, but after seeking help from the community(1, 2), it seems this error only happen in Scala 2.12 or later.
One of the possible workaround is to use Scala 2.11 instead. To do so, update the <properties> in pom.xml:
<properties>
...
<scala.version>2.11.8</scala.version>
<scala.compat.version>2.11</scala.compat.version>
...
</properties>And re-package the project.
Cleanup
Finally, cleanup the resources that are provisioned in the tutorial:
- CloudFormation Stack
DataBeamEmr - S3 Buckets to Beam App and EMR logging
Summary
Finaaaaaally that’s all the basics for Apache Beam. Yes, basics.
To be honest, the learning curve is still somewhat steep and requires quite an effort to pick up. Guess this is the nature of the big data.
In the contrast, being able to orchestrate all these resources and to see the potential of a scalable, distributed data processing platform would also be fulfilling. Hope this tutorial could help.









