<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Tony Moulton on Medium]]></title>
        <description><![CDATA[Stories by Tony Moulton on Medium]]></description>
        <link>https://medium.com/@tnymltn?source=rss-42f0ac734d32------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*_wxK9Oh-Ac6C_R70.</url>
            <title>Stories by Tony Moulton on Medium</title>
            <link>https://medium.com/@tnymltn?source=rss-42f0ac734d32------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 22:02:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tnymltn/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Enrichment Pipeline Patterns using Apache Beam]]></title>
            <link>https://medium.com/@tnymltn/enrichment-pipeline-patterns-using-apache-beam-4b9b81e5d9f3?source=rss-42f0ac734d32------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b9b81e5d9f3</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[apache-beam]]></category>
            <dc:creator><![CDATA[Tony Moulton]]></dc:creator>
            <pubDate>Tue, 22 Jan 2019 16:26:00 GMT</pubDate>
            <atom:updated>2019-01-23T06:01:28.528Z</atom:updated>
            <content:encoded><![CDATA[<h3>Enrichment Patterns With Apache Beam</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CdO59tyswdKbDj1o" /><figcaption>Photo by <a href="https://unsplash.com/@asoggetti?utm_source=medium&amp;utm_medium=referral">asoggetti</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When working with data it’s likely you’ll need to use another dataset to enrich it for use in downstream systems. If you’re using an RDBMS you can create a table and leverage the various JOIN variants to enrich your data as you query it. This won’t work well once you’ve exhausted the constraints of the underlying database and you’re forced to explore other options.</p><p>Lucky for us we’re in the golden age of massively parallel data processing systems and there are dozens of solutions to this problem. Powering the open source ecosystem we’re looking at Apache Hadoop, Spark, Flink, Samza, Nemo, Storm and NiFi while organizations like Google and IBM offer cloud and commercial solutions. The ecosystem is large enough to make your head spin, especially when you’re just looking to find a solution and move on. To make matters more complicated you’re forced to define your problem well enough to decide which platform to develop on while ensuring you’re not painting yourself into a corner.</p><h3>Beam Overview</h3><p>Apache Beam solves this problem by allowing developers to abstract the pipeline away from the underlying execution engine. Your pipeline will work on any engine that supports all the features you’re using. This is a major reason why I’ve adopted it as my go-to platform for developing large scale data processing solutions. If you look at the <a href="https://beam.apache.org/documentation/runners/capability-matrix/">Beam Compatibility Matrix</a>, you can see which features are supported by each execution engine and make informed decisions based on your requirements. Flink is perfectly suitable in [local] mode for smaller pipelines and I prefer that over a bespoke Python or Java program running as a service for reliability. Once the pipeline outgrows the available resources you can spin up a Flink cluster, potentially leverage an existing Spark cluster or move to <a href="https://cloud.google.com/dataflow/">Google Cloud Dataflow</a> with very little effort.</p><p>I suggest reading <a href="https://beam.apache.org/documentation/pipelines/design-your-pipeline/">Designing your Pipeline</a> if you’re new to these concepts but if you want to skip that let’s make sure we have a shared vocabulary.</p><ul><li><a href="https://beam.apache.org/releases/javadoc/current/org/apache/beam/sdk/transforms/DoFn.html"><strong><em>DoFn</em></strong> </a>— A user defined function invoked for each input element and emits zero or more elements. A DoFn may or may not have side effects and the programming guidelines suggest ensuring your <a href="https://beam.apache.org/contribute/ptransform-style-guide/#runtime-errors-and-data-consistency">DoFn is idempotent</a> because of the <strong><em>Bundle</em></strong> error handling semantics. You can read more about error handling in Beam by learning about its <a href="https://beam.apache.org/documentation/execution-model/">execution model</a>.</li><li><a href="https://beam.apache.org/releases/javadoc/current/org/apache/beam/sdk/transforms/PTransform.html"><strong><em>PTransform</em></strong></a> — Defines an operation which takes a specific type of input data and produces an output of a specific type. The composition of these transforms represent the data processing graph interpreted by the execution engine which also ensures type compatibility.</li><li><a href="https://beam.apache.org/releases/javadoc/current/org/apache/beam/sdk/values/PCollection.html"><strong><em>PCollection</em></strong></a> — Represents data passed between transforms in the data processing graph. They are used during graph construction to represent input and output types of a <strong><em>PTransform</em></strong>.</li><li><strong><em>Bundle</em></strong> — A set of data to be processed on a worker at a given time. The <strong><em>DoFn</em></strong> API supports notification of the beginning and end of each bundle. A bundle is a resilient representation of data which can be split between workers. When failures occur, the bundle can be retried on another worker node.</li></ul><p>You can think of an Apache Beam pipeline as a Directed Acyclic Graph of functions operating on data using batch (historic) and streaming (near real time) jobs with a unified API across various execution engines.</p><p>There are a few different ways to implement the <a href="https://www.enterpriseintegrationpatterns.com/patterns/messaging/DataEnricher.html">Content Enricher, or Data Enricher Pattern</a> using Beam. Each one has it’s advantages and disadvantages worth exploring.</p><ul><li><strong>*IO.ReadAll Pattern</strong> — <em>Use an input </em><strong><em>PCollection</em></strong><em> to define what the IO </em><strong><em>PTransform</em></strong><em> will read. {RedisIO.ReadAll, JdbcIO.ReadAll, SpannerIO.ReadAll, HBaseIO.ReadAll, TextIO.ReadAll, AvroIO.ReadAll, TFRecord.ReadAll}</em></li><li><strong><em>Side Inputs — </em></strong><em>A very clever feature which allows you to build a materialized </em><strong><em>PCollection</em></strong><em> to be made available for key or index based lookups. It’s surprising scalable and something to explore in a future post.</em></li><li><strong>Custom</strong> <strong><em>DoFn — </em></strong><em>Write your own </em><strong><em>DoFn</em></strong><em> that will take the input element and output the enriched data using the data source specific SDK. If you go this route, please read about the </em><a href="https://beam.apache.org/blog/2017/08/16/splittable-do-fn.html"><em>Splittable DoFn</em></a><em> and where Beam is heading.</em></li></ul><h3>Problem</h3><p>Let’s start with a concrete problem and work out our solution(s) from there.</p><p>There is a PubSub subscription of [Referer] headers from web server logs and your CEO wants to do analytics to better understand where users are coming from in order to develop a better affiliate compensation strategy. She wants to research the data herself so you just need to get the data into BigQuery and she’ll use a tool like Data Studio.</p><p>Since the stream of URLs contains the domain it can be used to find information about the affiliate contracts in place at the time of the hit and send the full referrer URL affiliate information to a PubSub topic for later ingestion into BigQuery.</p><h3>A Solution</h3><p>Because the Java SDK is the most mature we’re going to use it for our examples and focus on the <strong><em>ReadAll</em></strong> pattern for enrichment using <strong><em>JdbcIO</em></strong> since it offers the most flexibility and you probably know something about JDBC already.</p><p>Most examples show the *IO.read() functions being used to source data for your dataflow job. The read PTransform is defined as:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bdb3d2b5b4ee7607a29f3a3739f1d9e3/href">https://medium.com/media/bdb3d2b5b4ee7607a29f3a3739f1d9e3/href</a></iframe><p>You can see <a href="https://beam.apache.org/releases/javadoc/2.8.0/org/apache/beam/sdk/values/PBegin.html"><strong><em>PBegin</em></strong></a> defined as the input for the <strong><em>PTransform</em></strong>. This means the transform is a root or source of data for your pipeline. Initialization of the transform defines how data is produced. Astute readers might notice these configuration values are defined on a <strong><em>PTransform</em></strong> meaning they can only affect pipeline construction. It’s possible to pass these values to a <strong><em>DoFn</em></strong> using<strong><em> </em></strong>a <a href="https://beam.apache.org/releases/javadoc/current/org/apache/beam/sdk/options/ValueProvider.html"><strong><em>ValueProvider</em></strong></a><strong><em> </em></strong>however you can’t parameterize the query based on input data.</p><p>Thankfully there is a pattern for this and the Beam roadmap is moving all IO sources to support this interface. If you look at the definition of <strong><em>JdbcIO.ReadAll</em></strong> you will see that it accepts the input from another <strong><em>PCollection </em></strong>instead of <strong><em>PBegin</em></strong>. This means we can have an opportunity to dynamically modify the query and execute it once for each input element.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4929275c833432707d128f525b763e5d/href">https://medium.com/media/4929275c833432707d128f525b763e5d/href</a></iframe><p>How do we use this capability? <strong><em>JdbcIO.ReadAll</em></strong> has a method <strong><em>withPreparedStatementSetter</em></strong> which allows you to specify a function to set the parameters of a parameterized SQL statement based on the input element. This is extremely powerful as you can very easily pull dynamic data from any data source with a JDBC driver and use it to enrich data within your pipeline.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d00870162071ee1e1802cc7e16180596/href">https://medium.com/media/d00870162071ee1e1802cc7e16180596/href</a></iframe><p>The output of the transform is based on a second function that transforms a result set into an element for the next transform.</p><p>Let’s put this all together and watch it work. The example below will read from a PubSub subscription with each message being a simple URL, lookup data in a SQL database for enrichment, and output a JSON dictionary to a PubSub topic.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a98af7287f81889a981842bcf37a6f5f/href">https://medium.com/media/a98af7287f81889a981842bcf37a6f5f/href</a></iframe><p>One thing you might notice about this pipeline is that the original data is not available to our <strong><em>RowMapper</em></strong> function. This means your CEO can’t understand the performance of specific referrers on each domain. One way to solve this problem is using constant values in the SQL projection that allow the <strong><em>RowMapper</em></strong> function to have access to all the data it needs for the required output. Another and more Beam centric way of addressing this problem is to split the pipeline into two streams, one with the original data and one with the enriched data, then combine the results. Let’s take a look at an example that shows both of these methods at the same time.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/481266f196963fab1053ab6afc32758c/href">https://medium.com/media/481266f196963fab1053ab6afc32758c/href</a></iframe><p>In this example we’re starting with one <strong><em>PCollection</em></strong>, creating another off that to perform the enrichment, then joining the data together. You might notice another <strong><em>PTransform</em></strong> being applied to the data before any of this. In order to use <strong><em>CoGroupByKey</em></strong>, we need a unique identifier for a key so the original message and enriched data can be shuffled to the same worker to be grouped together.</p><p>The next change you’ll notice is the use of <strong><em>PreparedStatementSetter</em></strong> which gets called for each element of the input <strong><em>PCollection</em></strong> and is responsible for setting the parameters of each query to be made. The type of the input to the function is the same as the incoming <strong><em>PCollection</em></strong> and it returns void.</p><p>Next you’ll notice the <strong><em>? as __key</em></strong> in the SQL projection which is used to pass the randomly generated key to the <strong><em>RowMapper</em></strong> so it has access to the key to ensure it’s available further in the pipeline. This is a pattern which you’ll likely use throughout your pipeline unless you can leverage natural keys.</p><p>It’s important to note that there will be one SQL query made for each element coming from the topic. There are no optimizations made in this pipeline which is fine for our example which makes no assumptions about the incoming data but if you have a lot of repeated data coming into <strong><em>JdbcIO.ReadAll</em></strong> you’re going to be making a lot of repeated queries to your datastore.</p><p>There is a lot going on here and if you’re not already familiar with <strong><em>CoGroupByKey</em></strong>, it’s a great place to explore and learn about some core fundamentals of Apache Beam. Combining multiple streams of data is critical in today’s production data pipelines. Understanding the various methods available to combine data will ensure you’re using the right tools for the job.</p><p>There are plenty of improvements to this pipeline worth exploring and in a future post we will dive into more complex constructs within Apache Beam that can be used to better control interaction with external systems</p><h3>Finishing Up</h3><p>This post introduced a couple of core concepts of Apache Beam and how the <strong><em>ReadAll</em></strong> methods and <strong><em>CoGroupByKey </em></strong>can be used together to create enrichment pipelines. If you’re building a custom enrichment <strong><em>DoFn</em></strong> I highly suggest taking a look at other <strong><em>ReadAll</em></strong> implementations in the various IO libraries and following the similar patterns.</p><p><strong><em>CoGroupByKey</em></strong> is an extremely powerful method of combining data from more than one <strong><em>PCollection</em></strong>. It could be used as an aggregator when implementing the <a href="https://www.enterpriseintegrationpatterns.com/patterns/messaging/BroadcastAggregate.html">Scatter/Gather </a>pattern or combine multiple streams of data from correlated IoT devices.</p><p>We also discussed using constants in SQL projections to pass data. This can be an extremely useful method of injecting auditing data into backend database logs as well as help with cross server joins. You’ve seen it used to pass data through from query to result and how it was used later to support <strong><em>CoGroupByKey</em></strong>.</p><p>If you’re writing custom scripts for ETLs you can explore using the <strong><em>FlinkRunner</em></strong> in [local] mode to execute your pipelines using the same execution infrastructure you’re using now whether that’s cron, systemd, or another orchestration tool. You’re likely going to write much less code and have a job that’s much more stable. <em>Note: Don’t use the </em><strong><em>DirectRunner</em></strong><em> in production as it is designed to exercise edge cases not for performance.</em></p><p>I hope this helps you in your next data enrichment project and saves you from reinventing any wheels. You can find the code in this post along with tests at <a href="https://github.com/0xdecaf/beam-enrichment-patterns">https://github.com/0xdecaf/beam-enrichment-patterns</a>. If you’re inspired by this post and want to learn more, you might explore some methods to “batch” repeated queries while using the <strong><em>ReadAll</em></strong> pattern. <em>Hint: you’ll need to look into </em><a href="https://beam.apache.org/documentation/programming-guide/#windowing"><em>windowing</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b9b81e5d9f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>