<?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 Gaurav Mishra on Medium]]></title>
        <description><![CDATA[Stories by Gaurav Mishra on Medium]]></description>
        <link>https://medium.com/@gauravmishra_82578?source=rss-9550a43409d9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*eKhUcRJA11sPv3Hx.jpg</url>
            <title>Stories by Gaurav Mishra on Medium</title>
            <link>https://medium.com/@gauravmishra_82578?source=rss-9550a43409d9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 07:34:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gauravmishra_82578/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[UDP: How We Rewrote Our Data Platform to Save 30% On Cloud Costs (Part 2)]]></title>
            <link>https://medium.com/@gauravmishra_82578/udp-how-we-rewrote-our-data-platform-to-save-30-on-cloud-costs-part-2-c2f9f2cfe75c?source=rss-9550a43409d9------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2f9f2cfe75c</guid>
            <category><![CDATA[real-time-streaming-data]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[dataflow]]></category>
            <category><![CDATA[cost-savings]]></category>
            <category><![CDATA[apache-beam]]></category>
            <dc:creator><![CDATA[Gaurav Mishra]]></dc:creator>
            <pubDate>Fri, 02 Jan 2026 18:56:30 GMT</pubDate>
            <atom:updated>2026-01-02T18:56:30.775Z</atom:updated>
            <content:encoded><![CDATA[<p>In <strong>Part 1</strong> of this series, we focused on the high-level architectural overhaul that led to significant cost savings by implementing a <strong>multi-tenant</strong> and <strong>consolidated</strong> Unified Data Platform (UDP). While the ETL (Extract, Transform, Load) side of our data pipeline remained relatively straightforward, the aggregation jobs presented the biggest technical challenge and the greatest opportunity for performance gains.</p><p>This post will dive into the specific Dataflow design and implementation changes we made for the Aggregation service, which were crucial for operating reliably and efficiently at a hyper-scale of <strong>22 million records per second</strong>.</p><h3><strong>Choosing the Right Level of Abstraction</strong></h3><p>When building streaming pipelines on Dataflow, the first decision is often: “How much code do we actually want to write?”</p><h4>The Legacy Approach: Beam SQL</h4><p>Our legacy jobs relied heavily on <strong>Beam SQL</strong>. This is a high-level abstraction that allows developers to write standard SQL queries which the runner compiles into a set of underlying beam transforms. It is incredibly convenient for rapid development.</p><ul><li><strong>Pros:</strong> Fast to write, easy to read.</li><li><strong>Cons:</strong> It acts as a black box. You lose granular control over how windows are configured and triggered.</li></ul><h4>The UDP Approach: Beam Combiners</h4><p>For the UDP project, we made the conscious decision to drop down a level of abstraction. Instead of SQL, we utilized <strong>Beam Combiners</strong>. While Beam SQL uses combiners under the hood, writing them manually gave us direct access to the “gears” of the pipeline.</p><p><strong>The Trade-off:</strong> This approach required significantly more boilerplate code. We had to:</p><ol><li>Define Key Protobufs manually.</li><li>Implement custom Accumulators.</li><li>Write logic to merge the Key and Accumulated value into the final output.</li></ol><p><strong>The Payoff:</strong> The upside of this lower-level abstraction outweighed the development cost. By manually configuring the Combiner Transforms, we gained full control over the <strong>Windowing</strong> and <strong>Triggering</strong> behaviors. This flexibility proved crucial for the optimizations discussed in the next section.</p><h3><strong>Taming the Thundering Herd: Custom Windows</strong></h3><p>This was perhaps the most critical optimization in the entire project. To understand why, we first need to look at how Beam handles time.</p><h4>The Concept: Windowing in Beam</h4><p>In streaming processing, data is infinite. To aggregate it (e.g., “count events per 5 minutes”), we must chop the stream into finite chunks called <strong>Windows</strong>.</p><p>In a standard setup, records arriving between 09:00 and 09:05 are placed into a [09:00, 09:05) window. At 09:05, the window closes, the aggregation is calculated, and the result is emitted.</p><h4>The Problem: The “Spiky” Reality of Fixed Windows</h4><p>The standard FixedWindows implementation works perfectly for small scales. However, our job handles hundreds of <strong>millions of keys</strong>.</p><p>When you have millions of keys all assigned to standard 5-minute fixed windows, they all align perfectly on the clock.</p><ul><li><strong>09:00–09:05:</strong> Data is buffered. CPU usage is moderate (ingestion only).</li><li><strong>09:05:00:</strong> <strong>BOOM.</strong> Millions of windows trigger simultaneously.</li></ul><p>The Dataflow workers are suddenly hit with a massive computation demand to materialize aggregates for every single key at the exact same second.</p><p>As the image above illustrates, we saw a “sawtooth” CPU pattern.</p><ul><li><strong>Valley:</strong> ~50% CPU saturation (Steady state).</li><li><strong>Peak:</strong> 90–100% CPU saturation (Window boundaries).</li></ul><p><strong>The Cost Consequence:</strong> Dataflow’s autoscaler must provision enough workers to survive the <strong>peak</strong> (the 100% spike). This means that for the majority of the 5-minute window, we are paying for workers that are sitting half-idle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*Jb4cdKBmh7betnzZkWfqsw.png" /></figure><h4><strong>The Fix: Key-Smeared Fixed Windows</strong></h4><p>To solve this, we implemented a custom WindowFn. The goal was to break the alignment of the triggers. We kept the start times aligned (so records are still logically grouped correctly) but added a <strong>deterministic random jitter</strong> to the <em>end</em> of the window.</p><p>A record arriving at 09:03 might be assigned to a window tuple of (09:00, 09:08). The “logical” window is still 5 minutes, but the firing time is delayed by a 3-minute jitter.</p><p><strong>Crucial Technical Detail:</strong> The jitter <strong>must be stable</strong> for a given key. If Key A has a jitter of 3 minutes on Worker 1, it must also have a jitter of 3 minutes on Worker 2. If the jitter is not deterministic, the number of windows “explode” — Beam treats them as different windows, and the pipeline halts.</p><ul><li><em>Do not use java.util.hashCode():</em> It is not stable across different JVMs.</li><li><em>Use:</em> Hashing.farmHashFingerprint64() on specific fields in your Key Proto.</li></ul><h4>The Result: Smeared CPU</h4><p>By applying a max jitter equal to the window length (e.g., 5 minutes), we effectively spread the computation load across the entire duration of the window.</p><p>The CPU spikes vanished. The load curve flattened, allowing us to run the pipeline with a significantly lower, consistent worker count.</p><p><strong>The Downside:</strong> There is no free lunch. The cost of this optimization is <strong>latency</strong>.</p><ul><li><strong>Old way:</strong> Records emitted at 09:05.</li><li><strong>New way:</strong> Records emitted between 09:05 and 09:10.</li><li><strong>Average Delay:</strong> 1/2 of the tumble window duration.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*TqMhDEZxR1kuvzgA6v0cqQ.png" /></figure><p>Here is the implementation of the KeySmearedFixedWindows class:</p><p><strong>Note</strong>: This code was given to us by the Dataflow Engineering team as part of our debugging sessions with them.</p><pre>public class KeySmearedFixedWindows &lt;T&gt; extends NonMergingWindowFn&lt;T, IntervalWindow&gt; {<br>    /** Size of this window. */<br>    private final Duration size;<br><br>    /** Jitter of the firing of this window. */<br>    private final Duration jitter;<br><br>    /** Used to spread windows for a key deterministically within the [0, jitter) range. */<br>    private final SerializableFunction&lt;T, Long&gt; keyFingerprintFunction;<br><br>    /**<br>     * Smear of this window. Windows will be [N * size, N * (size+1) + offset) where offset is in<br>     * range [0, jitter) and deterministic per key. <br>     */<br>    public static &lt;T&gt; KeySmearedFixedWindows&lt;T&gt; of(<br>            Duration size, Duration jitter, SerializableFunction&lt;T, Long&gt; keyFingerprintFunction) {<br>        return new KeySmearedFixedWindows&lt;T&gt;(size, jitter, keyFingerprintFunction);<br>    }<br><br>    KeySmearedFixedWindows(<br>            Duration size, Duration jitter, SerializableFunction&lt;T, Long&gt; keyFingerprintFunction) {<br>        if (jitter.isShorterThan(Duration.ZERO) || size.isShorterThan(jitter)) {<br>            throw new IllegalArgumentException(<br>                    &quot;FixedWindows WindowingStrategies must have 0 &lt;= jitter &lt; size&quot;);<br>        }<br>        this.size = size;<br>        this.jitter = jitter;<br>        this.keyFingerprintFunction = keyFingerprintFunction;<br>    }<br><br>    @Override<br>    public final Collection&lt;IntervalWindow&gt; assignWindows(AssignContext c) {<br>        long hashValue = keyFingerprintFunction.apply(c.element());<br>        if (hashValue &lt; 0) {<br>            hashValue = hashValue &amp; 0x7FFFFFFFL;<br>        }<br>        return Collections.singleton(<br>                assignWindow(c.timestamp(), hashValue));<br>    }<br><br>    private IntervalWindow assignWindow(Instant timestamp, long keyFingerprint) {<br>        // Based upon FixedWindows.assignWindow logic<br>        Instant start = Instant.ofEpochMilli(<br>                        timestamp.getMillis() - timestamp.plus(size).getMillis() % size.getMillis());<br>        <br>        Instant endOfGlobalWindow = GlobalWindow.INSTANCE.maxTimestamp().plus(Duration.millis(1));<br>        <br>        // Add deterministic jitter based on the key fingerprint<br>        Duration sizeWithJitter = size.plus(Duration.millis(Math.abs(keyFingerprint) % jitter.getMillis()));<br>        <br>        Instant end = start.isAfter(endOfGlobalWindow.minus(sizeWithJitter))<br>                        ? endOfGlobalWindow<br>                        : start.plus(sizeWithJitter);<br><br>        return new IntervalWindow(start, end);<br>    }<br>    <br>    // ... Additional standard overrides (verifyCompatibility, windowCoder, etc.) omitted for brevity ...<br>}</pre><h3>Switching Time Domains: Processing Time vs. Event Time</h3><p>The final major optimization involved changing the “clock” our pipeline used to trigger results. In Beam, there are two main time domains:</p><ol><li><strong>Event Time:</strong> The time the event actually happened (based on the timestamp inside the data).</li><li><strong>Processing Time:</strong> The wall-clock time on the Dataflow worker processing the data.</li></ol><h4>The Problem with Event Time and SECU Costs</h4><p>In an <strong>Event Time</strong> domain, the pipeline relies on a “Watermark.” The Watermark is the system’s guess that “no data older than time X will arrive.” If a single upstream shard of data is lagging, the Watermark holds back.</p><p>While the Watermark is held back, Dataflow must buffer the state of all open windows. <strong>This gets expensive.</strong> Dataflow charges for “Streaming Engine Compute Units” (SECU), which is billed based on the volume of state stored and the <em>duration</em> that state is held. If late data holds your Watermark back, your state buffer duration increases, and your SECU costs rise.</p><p>In our case, we were using kafkaIo to consume from multiple topics, with a single job sometimes configured to consume from over 1000 Kafka topics, each having vastly different throughput. When the mix of throughput was too great, some of the heavier partitions started to lag behind. This caused the Watermark to be held back for <em>all</em> other partitions, resulting in the data from all other partitions being buffered in the Dataflow state, leading to unnecessarily high costs.</p><h4>The Fix: Processing Time Triggers</h4><p>For UDP, we switched to the <strong>Processing Time</strong> domain. We no longer wait for the “completeness” of data based on Event Time watermarks. When the wall clock hits the target, we emit what we have.</p><p><strong>The Benefit:</strong> We drastically reduced the duration that data sat in the state buffer. By evicting state aggressively based on machine time, we reduced the “Storage x Time” component of the SECU bill.</p><p><strong>The Trade-off:</strong> If “late data” arrives after the processing time trigger has fired, it is not discarded, but it is emitted as a separate “partial aggregate.”</p><ul><li><strong>Impact:</strong> We saw about a <strong>5% increase</strong> in total records emitted (due to late partials).</li><li><strong>Verdict:</strong> The cost of writing 5% more rows to BigQuery was negligible compared to the massive savings in Dataflow SECU costs.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*rXyw9xU58xKTiPKqlk0jLA.png" /></figure><h3><strong>Working with Kafka At Scale</strong></h3><h4>Idle Topic Problem</h4><p>Our decision to consolidate our data pipeline into a few large multi-tenant jobs, while yielding massive compute savings, introduced a new set of challenges when consuming from Kafka. Our new architecture had to consume more than 1.2 Million Kafka topics in total. While only about 25% of topics were active on average, we were required to consume from all of them, as any idle topic could become active at any moment.</p><p>The problem arose because Dataflow workers, utilizing the underlying Kafka consumer, must commit offsets to a special Kafka internal topic called __consumer_offset. Even for the vast number of idle topics, the Dataflow jobs would continuously attempt to commit “no-op” offsets. This created an excessive and unnecessary load on the __consumer_offset topic, often exceeding the throughput of our actual data topics. This excessive traffic made some of our Kafka clusters unstable and caused hiccups for upstream producers.</p><p><strong>The Fix: Suppressing No-Op Commits</strong></p><p>To resolve this, we implemented a hack by providing a custom implementation of KafkaUnboundedReader on the classpath. In this custom reader, we modified the commitCheckpointMark function to check for actual offset movement before committing. If an offset had not advanced since the last successful commit, the commit for that TopicPartition was skipped, drastically reducing the commit-log traffic. Following code does not completely eliminate such no-op commits but ensures from a given instance of the reader object a single such no-op commit will be made at max which is significantly better than previous situation.</p><pre>private void commitCheckpointMark() {<br>    KafkaCheckpointMark checkpointMark = finalizedCheckpointMark.getAndSet(null);<br>    if (checkpointMark == null) {<br>      return;<br>    }<br><br>    // consumer is set in start(); keep the existing null-check semantics<br>    final Consumer&lt;byte[], byte[]&gt; c = this.consumer;<br>    if (c == null) {<br>      return;<br>    }<br><br>    try {<br>      // Build a commit map only for partitions whose offsets actually advanced.<br>      // We commit &quot;nextOffset&quot; (the next record to read), which is Beam&#39;s existing behavior.<br>      Map&lt;TopicPartition, OffsetAndMetadata&gt; toCommit = new HashMap&lt;&gt;();<br><br>      for (KafkaCheckpointMark.PartitionMark pm : checkpointMark.getPartitions()) {<br>        long next = pm.getNextOffset();<br>        if (next == UNINITIALIZED_OFFSET) {<br>          // keep original behavior: skip uninitialized<br>          continue;<br>        }<br>        TopicPartition tp = new TopicPartition(pm.getTopic(), pm.getPartition());<br><br>        // Suppress no-op commits: skip if we already committed &gt;= this offset on this reader.<br>        Long prev = lastCommittedOffsets.get(tp);<br>        if (prev == null || next &gt; prev) {<br>          toCommit.put(tp, new OffsetAndMetadata(next));<br>        }<br>      }<br><br>      if (toCommit.isEmpty()) {<br>        // Nothing advanced since the last successful commit on this reader; avoid noisy commit.<br>        return;<br>      }<br><br>      // Commit synchronously (preserves Beam&#39;s at-least-once semantics)<br>      c.commitSync(toCommit);<br><br>      // Update the tracker only after a successful commit.<br>      for (Map.Entry&lt;TopicPartition, OffsetAndMetadata&gt; e : toCommit.entrySet()) {<br>        lastCommittedOffsets.put(e.getKey(), e.getValue().offset());<br>      }<br><br>    } catch (Exception e) {<br>      // Preserve Beam behavior: log and continue; data safety relies on CheckpointMark, not Kafka commit.<br>      LOG.warn(String.format(&quot;%s: Could not commit finalized checkpoint %s&quot;, this, checkpointMark), e);<br>    }<br>  }</pre><h4>Wide Range Of Load On Topics</h4><p>The core issue stemmed from jobs consuming data from multiple Kafka topics, each with drastically different throughputs. When high-throughput topics were processed alongside very low-throughput ones, the high-volume topics and their partitions lagged, leading to a backlog. This imbalance was clearly reflected in the jobs’ CPU graphs: certain workers were completely saturated at 100% CPU, while others remained significantly underutilized, operating at only 20% CPU.</p><p>To fix this uneven split, we use two solutions today:</p><ol><li><strong>K-means Clustering:</strong> We run the k-means algorithm to divide the topics into groups of similar load. This fixes the issue for most of the times. When running k-means, we look at the average throughput across a 7-day period.</li><li><strong>Redistribute Transform:</strong> In some cases, we see some jobs still behave badly due to the spiky nature of the load on some of the topics. When certain topics become super hot at certain times of the day, they still show the backlog symptoms. In those cases, we have to add a <strong>“Redistribute”</strong> in the pipeline just after the KafkaIO stage. This causes the work from Kafka reading threads to be offloaded to a new set of worker threads whose parallelism we can control via the bucket count parameter. The downside of this approach is that all the data has to be shuffled via Google’s streaming backend. This causes some overhead on CPU costs and SECU costs, and therefore, this approach is used only in cases where all other approaches fail.</li></ol><h3><strong>Conclusion</strong></h3><p>Rewriting our Aggregation service was not about finding a single “silver bullet,” but rather about peeling back the layers of abstraction to regain control over our pipeline’s behavior. By moving from Beam SQL to Combiners, implementing key-smeared windows to tame CPU spikes, and optimizing our Kafka consumption strategy, we transformed a volatile, resource-hungry process into a stable, cost-efficient engine. While these optimizations introduced complexity and required deliberate trade-offs — such as sacrificing minimal latency for massive stability — the results speak for themselves. These low-level engineering changes were the primary drivers behind cutting down the compute costs by 40%, proving that at a large scale, the “default” settings are rarely enough.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2f9f2cfe75c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[UDP: How We Rewrote Our Data Platform to Save 30% On Cloud Costs (Part 1)]]></title>
            <link>https://medium.com/@gauravmishra_82578/udp-how-we-rewrote-our-data-platform-to-save-30-on-cloud-costs-part-1-5f1419d2b957?source=rss-9550a43409d9------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f1419d2b957</guid>
            <category><![CDATA[dataflow]]></category>
            <category><![CDATA[real-time-streaming-data]]></category>
            <category><![CDATA[apache-beam]]></category>
            <category><![CDATA[cost-savings]]></category>
            <category><![CDATA[gcp]]></category>
            <dc:creator><![CDATA[Gaurav Mishra]]></dc:creator>
            <pubDate>Fri, 02 Jan 2026 18:55:13 GMT</pubDate>
            <atom:updated>2026-01-02T18:55:13.570Z</atom:updated>
            <content:encoded><![CDATA[<p>I work as a software engineer in the VnA (Visualisation and Analytics) team within the NetSec organization at Palo Alto Networks. Our core mission is to handle massive data streams: exposing time-series events coming out of firewalls to customers in both raw and aggregated form.</p><p>Recently, I was given the opportunity to work on a project that was both complex and urgent: rewriting a couple of our existing services with the primary goal of slashing our cloud costs. This was a high-stakes endeavor due to the sheer scale of data involved and the wide breadth of live consumers across various organizational teams.</p><p>This post focuses solely on the technical architecture, results, and design choices we made. Given the depth of this subject, I will be setting aside the deep code details for now and focusing only on the high-level results. I plan to write a follow-up post to take a deeper dive into specific areas around our Dataflow implementation.</p><h3><strong>Diagnosing the “Old” Architecture</strong></h3><p>To navigate this rewrite, we established some basic nomenclature: The new architecture is built by the <strong>Unified Data Platform</strong> (UDP) team, and systems that were replaced are referred to by the “Old” prefix.</p><p>The “Old” system was fundamentally divided into two service types that needed replacement:</p><ol><li>ETL Service: Responsible for storing raw data into Bigquery tables, deployed as Flink jobs running on self-managed Kubernetes.</li><li>Aggregation Service: Responsible for processing and aggregating data, writing results to Aggregated BQ tables or Pub/Sub Topics, deployed as Dataflow jobs in Google Cloud.</li></ol><p>Across all the components we highlighted for impact, our previous operating costs were more than $2.7 Million per month. The cause of this colossal bill was rooted in architectural decisions made over time that optimized for quick feature delivery rather than cost efficiency.</p><p><strong>Flaw 1: The Single-Tenanted Design</strong></p><p>Both the ETL and Aggregation services were <strong>single-tenant</strong>. This meant an instance of a Dataflow job or a Flink job was <strong>spun up</strong> for <em>every</em> active customer.</p><p>For customers generating high volume, this system utilized resources effectively. But for low-volume customers — say, 100 records per second — it was massively inefficient.</p><ul><li>Every active tenant required 1.5 vCPU for the Flink job and 2 vCPU for the Dataflow job.</li><li><strong>2 vCPU</strong> was often overkill, but since most machine families in Dataflow do not support 1 vCPU VMs, this was the minimum we could allocate.</li></ul><p><strong>Flaw 2: The Streaming Inserts Tax</strong></p><p>Initially, our data platform’s ETL jobs relied on Bigquery’s <strong>Streaming Inserts</strong> to manage peak ingestion rates of over 20 GB per second into BigQuery (BQ) across our production environments. However, while capable of handling this massive volume, this method was expensive. This high cost has since been eliminated, thanks to the recent <strong>Improvements of the Storage Write API from Google</strong>, which now allows us to write significantly larger data volumes at a much lower cost.</p><figure><img alt="Figure 1: Old System Producer Costs (Wasted Compute and Expensive Ingestion)" src="https://cdn-images-1.medium.com/max/512/1*HdqvyyskGKe-jPtlT3NS8g.jpeg" /><figcaption><strong>Old System Producer Costs (Wasted Compute and Expensive Ingestion)</strong></figcaption></figure><p><strong>Flaw 3: The Triple Subscription Tax</strong></p><p>The Aggregator Job’s output was directed to both BigQuery (BQ) and Pub/Sub. Since Pub/Sub Write costs are associated with the project that owns the topic, analyzing the system from the consumer perspective reveals the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*qQqyxm-dpt3fc1yquUumKg.png" /><figcaption><strong>Old System Consumer Costs (JSON, Duplication, and BQ Sinks)</strong></figcaption></figure><p><strong>Paying 4x for Every Record</strong></p><p>If you look closely at the consumer flow (Figure 2), every Pub/Sub topic was being consumed by three subscriptions:</p><ul><li>Two subscriptions fed into the Data Stitching Job. One was the standard subscription for consuming incoming data, and the second was a special subscription created automatically by Dataflow for watermark tracking.</li><li>Because two subscriptions were pulling the <strong>exact same data</strong>, we were paying double for data transfer. Since December 2025, Google has changed this billing behaviour for the special subscription. Now we are billed only for the Pub/Sub attributes and not the full payload on this subscription.</li><li>We also had a dedicated Kubernetes based BQ Sink Service which was sinking Pub/Sub data into BQ tables. This Sink was being used to insert the data from Aggregated Pub/Sub topics to Aggregated BQ tables.</li></ul><p>When the BQ Sink subscription was included, we were paying four times (one write, three reads) for every record written to certain Pub/Sub topics</p><p><strong>Costly Inefficiency: JSON Serialization</strong></p><p>Another subtle but major cost driver was the use of <strong>JSON Serialization</strong> instead of a more compressed format like Protobuf. This choice was made years prior for ease of integration when throughput was minimal (maybe 1 MB/sec). Without changes, the same framework was now handling streams well <strong>above 2GB/sec in a single production environment</strong>.</p><h3><strong>The UDP Design: Engineering Our Way to Savings</strong></h3><p>Armed with the luxury of hindsight and that “big fat cloud bill” as motivation, we decided to fundamentally change the design.</p><h4>1. Multi-Tenancy and Consolidation</h4><p>Moving to <strong>multi-tenant</strong> jobs was a “no-brainer” to eliminate the huge amount of wasted compute resources we saw in the previous <strong>single-tenant</strong> jobs.</p><p>We also fused the ETL Job and the Aggregator Job into a single entity. While ETL jobs have much stricter SLA requirements than aggregators, our initial attempt to separate the two (where ETL output went to Pub/Sub and the Aggregator picked it up) was abandoned. Why? Because the resulting <strong>Pub/Sub costs in the US region alone were coming out to be higher than our total budget for the entire project</strong> across all regions. For now, both the ETL and Aggregator functions are fused into one job.</p><p>We also eliminated the use of the BQ Sink job and decided to write directly to BQ from our Dataflow jobs</p><h4>2. Pub/Sub Serialization</h4><p>Addressing the massive Pub/Sub costs, which were <strong>more than $800k/month</strong>, we decided to <strong>use protobuf to serialize data</strong> for Pub/Sub output. This was considered a “no brainer” given the scale of operation and costs, especially since the previous system utilized costly <strong>JSON Serialization</strong></p><h4>3. Dataflow Implementation</h4><p>We also changed the implementation of the aggregator jobs to extract maximum performance. While the previous code utilized <strong>Apache Beam’s SQL transforms</strong> for filtering and aggregations, we found that this abstraction was too high for our required scale. We made the strategic decision to instead <strong>use Combiners</strong>, which is a <strong>lower-level abstraction in Beam</strong> (and is what the SQL transform uses behind the scene). This move was crucial as it gave us granular control over two critical operational aspects: <strong>how data is Windowed into time bins and how the triggers are fired</strong>. Furthermore, to handle the unique challenges we faced due to our intense scale, we needed to make <strong>a few customizations to some of the Beam’s lower-level libraries</strong>. These customizations were essential to ensure our code could function reliably at the scale we are operating at, but I cannot cover all those changes here. The details of these critical, low-level Beam customizations will be the primary focus of my follow-up post.</p><h4>4. Using Storage Write API</h4><p>On the UDP side, we are using BQ’s Storage Write API for inserting all data into BQ tables</p><h4>5. Sharding BQ Output</h4><p>To prevent service issues we experienced in the past when writing too much data to a single table, all output BQ tables in UDP are now <strong>multi-tenant</strong> but are also <strong>sharded</strong>.</p><p>We shard the data using a simple tenant_id MOD N. Where N is a parameter fixed for a given prod environment. This does not impact cost, but it fundamentally changed how we deploy and operate our jobs, allowing us to operate at hyper-scale without hiccups from the BQ service. It also helps with read performance, as large index files in monolithic tables had previously led to extremely long query planning phases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*dyDfUS5HAJ20mgQcgcWf6A.jpeg" /><figcaption>Before Vs Now</figcaption></figure><h3><strong>Operating at Hyper-Scale: The UDP Metrics</strong></h3><p>The Unified Data Platform is not just cheaper; it is built for extreme scale. Following are some of the stats from our dataflow jobs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*3x2qzJT79m1nIjEWyEYgTQ.png" /><figcaption><strong>Dataflow Throughput Metrics</strong></figcaption></figure><p>At peak times, we are processing around <strong>22 million records per second</strong>. Most of these records are being aggregated into <strong>5-minute bins</strong> via <strong>6 different group-by operations</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*75Ep_G997NQiNJUVeS0kxA.png" /><figcaption><strong>Dataflow Parallel Key Metrics</strong></figcaption></figure><p>At peak, our jobs are processing <strong>8 billion parallel keys</strong>.</p><ul><li>We currently maintain about 400 billion timers in the pending state at any given time.</li><li>We are outputting <strong>24 GB/second</strong> of data to BQ.</li><li>Including both raw and aggregated records, we insert more than 1 trillion records in a day</li><li>We have deployed 3,000 jobs consuming 1.2M<strong> Kafka topics</strong>.</li></ul><h3>The Bottom Line</h3><p>The strategic rewrite paid off dramatically.</p><p>The previous operating costs across the targeted components were approximately <strong>$2.7 Million per month</strong>. Now UDP is deployed in all regions. Based on the data from the last 2 months, <strong>we are saving around $1 Million per month</strong>.</p><p>The architectural overhaul, driven by the need to eliminate unnecessary compute, optimize ingestion, and eradicate data duplication tax, successfully delivered a highly scalable and financially responsible data platform.</p><p><strong>Next Up:</strong> In a follow-up post, I’ll dive deeper into the specific implementation details of our <strong>Beam</strong> code, including how we utilized <strong>Combiners</strong> to achieve aggregation efficiency at this massive scale.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f1419d2b957" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stream Enrichment with Apache Beam: Enhancing Datastreams from Another Stream]]></title>
            <link>https://medium.com/@gauravmishra_82578/stream-enrichment-with-apache-beam-enhancing-datastreams-from-another-stream-852edee59f6e?source=rss-9550a43409d9------2</link>
            <guid isPermaLink="false">https://medium.com/p/852edee59f6e</guid>
            <category><![CDATA[data-processing]]></category>
            <category><![CDATA[real-time-streaming-data]]></category>
            <category><![CDATA[data-enrichment]]></category>
            <category><![CDATA[apache-beam]]></category>
            <dc:creator><![CDATA[Gaurav Mishra]]></dc:creator>
            <pubDate>Wed, 31 May 2023 14:35:22 GMT</pubDate>
            <atom:updated>2023-05-31T14:35:22.670Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Working in a team that processes data streams from various sources within the company, we often come across the need to fetch metadata from one data stream and enrich another data stream for building APIs or dashboards. In this blog post, we will explore a simple trick to accomplish this using Apache Beam.</p><h3>Join vs Enrichment</h3><p>Before diving into the trick, it’s important to distinguish between a join operation and enrichment. Joining involves merging records from two or more streams into a single record, combining metadata and statistics for each time window. Apache Beam provides functionalities to perform joins by setting up windows, and triggers, and utilizing SDK functions to merge records.</p><p>On the other hand, enrichment focuses on enhancing one stream with metadata carried by records from another stream. This metadata typically consists of information that doesn’t change frequently.</p><h3>Problem Statement</h3><p>Imagine we have two data streams flowing through a message bus: one containing slow-changing metadata information and the other containing primary statistics used for building dashboards and APIs.</p><pre>message PrimaryStreamRecord {<br>     string customer_id; <br>     Int32 money_spent;  <br>     int64 event_time;<br>}</pre><pre>message MetadataStreamRecord {<br>     string customer_id;<br>     string address; // field of interest<br><br>     // other fields which we dont care about<br>     int64 event_time;<br>     Int32 some_metrics;<br>}</pre><p>Our goal is to enrich the primary stream’s records with addresses from the MetadataStreamRecord stream.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QoudTKkaNPz2_x19GAKnag.png" /></figure><h3>Solution</h3><p>We are going to use a stateful DoFn to do the enrichment. In this DoFn we would like to cache the metadata fields from the metadata stream and emit out enriched records for the primary stream.</p><p>To write such a DoFn we will have to make sure both the streams are using a common model and they share the same key. In our example, we can use customer_id as the key. The common model will look something like this</p><pre>message CommonModel {<br>      // only one of the following two fields will be set in any record<br>      PrimaryStreamRecord primary_stream_record;<br>      MetadataStreamRecord metadata_stream_record;<br>}</pre><p>This model is simply composed of the two models which are flowing through the two streams. In any instance of this new model, only one of the fields will be set.</p><p>A sketch of the full pipeline code will look something like this</p><pre>PCollection&lt;PrimaryStreamRecord&gt; primaryStream = pipeline.apply(PubsubIO.read(...))<br>.apply(“Convert pubsub message to PrimaryStreamRecord instances”, new ConvertToPrimaryModelTransform());<br><br>PCollection&lt;MetadataStreamRecord&gt; metadataStream = pipeline.apply(PubsubIO.read(...))<br>.apply(“Convert pubsub message to MetadataStreamRecord instances”, new ConvertToMetadataModelTransform());<br><br>// convert both streams to KV pairs, where key is customerId and value is the CommonModel  <br>// instance<br>PCollection&lt;KV&lt;String, CommonModel&gt;&gt; primaryKVPairs  = primaryStream.apply(Pardo.of(new ConvertPrimaryToCommonDoFn()));<br><br>PCollection&lt;KV&lt;String, CommonModel&gt;&gt; metadataKVPairs  = metadataStream.apply(Pardo.of(new ConvertMetadataToCommonDoFn()));<br><br>// merge  both kvpairs pcollections into one<br>PCollection&lt;KV&lt;String, CommonModel&gt;&gt; mergedStream = PCollectionList.of(primaryKVPairs)<br>.and(metadataKVPairs).apply(Flatten.pCollections());<br><br>// finally run this merged stream through our stateful DoFn which will do the caching and <br>// enrichment, output of this DoFn will be enriched PrimaryStreamRecord instances.<br>PCollection&lt;PrimaryStreamRecord&gt; finalOutput = mergedStream.apply(Pardo.of(new EnrichDoFn()));<br><br>// send the finalOutput to a sink<br>finalOutput.apply(....write to BQ…)</pre><p>Now we will look at some of the DoFns mentioned in the sketch closely. The first one is ConvertPrimaryToCommonDoFn whose job is to convert the incoming PrimaryStreamRecord into a KV pair. In this example, I have used a single field aka `customer_id` from the incoming records as key, but the idea can be extended if there are multiple fields that need to be used to join the two streams. In that case, KV&lt;String, CommonModel&gt; will be replaced with KV&lt;KeyModel, CommonModel&gt; everywhere in the code.</p><pre>Class ConvertPrimaryToCommonDoFn extends DoFn&lt;PrimaryStreamRecord, KV&lt;String, CommonModel&gt;&gt; {<br><br> @ProcessElement<br> Public void processElement(@Element PrimaryStreamRecord input, OutputReceiver&lt;KV&lt;String, CommonModel&gt;&gt; out) {<br>    String key = input.getCustomerId();<br>    CommonModel value = CommonModel.newBuilder()<br>                             .primaryStreamRecord(input)<br>                             .build();<br>    out.output(KV.of(key,value));<br>  }<br>}</pre><p>ConvertMetadataToCommonDoFn will similar to the above.</p><p>EnrichDataDoFn looks like following</p><pre>class EnrichDoFn extends DoFn&lt;KV&lt;String, CommonModel&gt;, PrimaryStreamRecord&gt; {<br><br>    @StateId(&quot;metadataCache&quot;)<br>    private final StateSpec&lt;ValueState&lt;MetadataStreamRecord&gt;&gt; metadataCache =<br>        StateSpecs.value(MetadataStreamRecord.class);<br><br>    @ProcessElement<br>    public void processElement(<br>        @Element KV&lt;String, CommonModel&gt; input,<br>        @StateId(&quot;metadataCache&quot;) ValueState&lt;MetadataStreamRecord&gt; metadataCacheState,<br>        OutputReceiver&lt;PrimaryStreamRecord&gt; output) {<br>  <br>      CommonModel commonModel = input.getValue();<br>     // only one of the following two models will be set<br>      PrimaryStreamRecord primaryRecord = commonModel.hasPrimaryRecord() ? commonModel.getPrimaryStreamRecord() : null;<br>      MetadataStreamRecord metadataRecord = commonModel.hasMetadataStreamRecord() ? commonModel.getMetadataStreamRecord(): null;<br>  <br>      // Check if the metadata cache is already populated<br>      if (primaryRecord != null &amp;&amp; metadataCacheState.read() != null) {<br>        // Metadata cache is already populated, enrich the primary record<br>        primaryRecord = enrichPrimaryRecord(primaryRecord, metadataCacheState.read());<br>        output.output(primaryRecord);<br>      } else if(metadataRecord != null) {<br>        // Metadata cache is empty, store the metadata record in the cache for future enrichment<br>        metadataCacheState.write(metadataRecord);<br>      }<br>    }<br><br>    private PrimaryStreamRecord enrichPrimaryRecord(<br>        PrimaryStreamRecord primaryRecord, MetadataStreamRecord metadataRecord) {<br>      // Perform the enrichment logic here<br>      // Example: Set the address field of the primary record using the metadata record<br>      primaryRecord = primaryRecord.toBuilder().setAddress(metadataRecord.getAddress()).build();<br>      return primaryRecord;<br>    }<br>}<br><br></pre><h3>Alternate Solution</h3><p>An alternative approach would be to use an external key-value data store like Redis. Instead of caching the metadata within the pipeline, you can store the metadata from the metadata stream in Redis and read the stored Redis keys while processing the primary stream. This approach can be beneficial when dealing with large amounts of metadata and you are fine with maintaining a key-value store.</p><h3>Conclusion</h3><p>Enriching one data stream with metadata from another stream is a common requirement in data processing scenarios. By leveraging Apache Beam and its stateful DoFn, we can easily accomplish this task. If you choose to cache the metadata within the pipeline, the trick covered in this blog post provides a flexible solution for enriching data streams.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=852edee59f6e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Schema Aware Generic Pipelines Using Apache Beam Rows]]></title>
            <link>https://medium.com/@gauravmishra_82578/schema-aware-generic-pipelines-using-apache-beam-rows-e0a36b11b929?source=rss-9550a43409d9------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0a36b11b929</guid>
            <category><![CDATA[generic-pipeline]]></category>
            <category><![CDATA[beam-sql]]></category>
            <category><![CDATA[apache-beam]]></category>
            <category><![CDATA[row]]></category>
            <category><![CDATA[schema-aware]]></category>
            <dc:creator><![CDATA[Gaurav Mishra]]></dc:creator>
            <pubDate>Thu, 25 Nov 2021 21:01:13 GMT</pubDate>
            <atom:updated>2021-11-25T21:01:13.211Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>For the last few months I have been using Apache Beam to write data processing pipelines. Most of these pipelines have been ingestion pipelines, whose job was to take incoming data from a pubsub topic, transform it, enrich it and forward it to another topic. We have a bunch of these pipelines, one pipeline for each type of data. Each of these ingestion pipelines has its own codebase. These pipelines do share a lot of code via a library written using Java Generics which allows us to create a new ingestion pipeline by defining a new java model and implementing a couple of thin layers of code. Recently we had a requirement of writing a new kind of pipeline for generating alerts which was supposed to be completely config driven. For this pipeline we ended up using a different code pattern using Beam Rows. <a href="https://beam.apache.org/releases/javadoc/2.27.0/org/apache/beam/sdk/values/Row.html">Row</a> is a generic data structure which is tied to a particular schema. When you look at the code which uses Rows, the DoFns will look like XyzDoFn&lt;Row, Row&gt; instead of XyzDoFn&lt;Pojo1, Pojo2&gt;.</p><p>This does reduce code readability a bit but it opens up doors for writing very generic code which can be controlled via configs. So instead of writing a DoFn&lt;InputPojo, OutputPojo&gt; for each type of data now we can write one DoFn&lt;Row, Row&gt; which takes in <a href="https://beam.apache.org/releases/javadoc/2.27.0/org/apache/beam/sdk/schemas/Schema.html">beam schema</a> for incoming data, some encoded form of transform logic as input and can map incoming rows to outgoing rows.</p><p>In this post I will first go over the requirements of our pipelines and thereafter will go over some key components of the pipeline where Rows were used.</p><h3>Problem Statement</h3><p>Given any data stream, send out alerts when any resource goes into an unstable state. Definition of unstable state will come from the user of the pipeline. The intended users here are other engineering teams who want to use this kind of alerting capability. The code is supposed to be completely config driven. No new code should be added for any new type of data. The schema for the output alert model was fixed and was also independent of the incoming data type.</p><h3>Why Beam Row</h3><p>When we did a proof of concept for this pipeline, the pipeline was written using Pojos. For any new data type, the user was supposed to add a new model class which implemented an interface and had few lines of code. Given the restriction of no new code, using Pojos for each data type are automatically out of the window. At this point the only two viable options were using some flavour of JsonObject or Row. In theory everything in the current pipeline could have been implemented using Row as well as JsonObject but we chose Row since it provided type safety and also reduced the amount of code in certain components of pipeline, like after ingestion the pipeline was supposed to filter data and evaluate if any given current data point is in an unstable state. Both these operations can be done using Beam SQL which is a Beam extension which allows us to run SQLs on PCollections. In our pipeline using one SQL we can do both the filtering and evaluation of the state. Something like</p><pre>SELECT *,</pre><pre>(CASE WHEN <strong>field1=1 AND field2 &lt; 5</strong> THEN ‘Raise’ ELSE ‘Clear’ END) as alert_state</pre><pre>FROM PCOLLECTION</pre><pre>WHERE <strong>field3=123 AND field4=345</strong>.</pre><p>This SQL can be generated by code using a couple of expressions defined by the user.</p><p>This approach saves us from writing code for expression parsing and doing any validations on those since Beam caches any mistakes in these expressions. For instance in the above example, if the user made a typo and specified fie1d4=345 in the filter expression, pipeline wont start and will complain about not able to find fie1d4 in the schema of input rows. Similarly, it catches type mismatch issues, for instance if field4 was a string field then Beam will complain about the type mismatch on field4 (correct expression here would be field4=”345&quot; )</p><p>Since we had a working pipeline written during the proof of concept phase, we wanted to retain as much code as possible so we took a hybrid approach where initial phases of the pipeline used Row and later phases continued to use Pojos. We just had to write one extra DoFn after the Ingestion phase to transform the incoming Row into a Pojo which is data type agnostic. In the next section we will look closely into the parts of the pipelines which use Rows.</p><h3>Building Blocks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0zVvumABH72N-yBDLzm4VQ.png" /></figure><h4>Input Transform</h4><p>This transform is supposed to read msges from pubsub and deserialize the strings into Rows. Incoming Pubsub messages are json strings. This transform also takes in as input the Beam Schema for incoming data. Beam SDK has provided Utils for deriving Beam Schema from a variety of source schemas. In our case since we wanted users to not write any code(no code recompilation), we picked avro as our schema format. So for any new data type, the user has to create a .avsc file. Once we have a .avsc file deriving Beam schema is few lines of code.</p><pre>public Schema getBeamSchema(String avroSchemaFilePath) throws IOException {</pre><pre>    InputStream inputStream = Application.class.getClassLoader()<br>                        .getResourceAsStream(avroSchemaFilePath);</pre><pre>    org.apache.avro.Schema avroSchema = <br>           new org.apache.avro.Schema.Parser().parse(inputStream);</pre><pre>    return AvroUtils.toBeamSchema(avroSchema);</pre><pre>}</pre><p>Once we have Beam schema, we can implement our input transform like this</p><pre>JsonToRow.ParseResult parseResult = input.apply(&quot;Read From Pubsub&quot;,       PubsubIO.readMessagesWithAttributesAndMessageId()<br>.fromSubscription(inputSubscriptionId))</pre><pre>.apply(&quot;Convert to string&quot;, MapElements.into(TypeDescriptors.strings())<br>.via(msg -&gt; new String(msg.getPayload())))</pre><pre>.apply(&quot;Deserialize to Row&quot;, JsonToRow.withExceptionReporting(<strong>schema</strong>).withExtendedErrorInfo());</pre><p>parseResult above contains two PCollections, first one contains Rows corresponding to valid data points and second one is the discard PCollection with bad data points and a reason text generated by Beam explaining why any given data point is invalid.</p><h4>Sql Transform</h4><p>Second transform in the pipeline does two things -</p><ol><li>Copies the incoming stream into multiple output streams, each stream satisfying a given filter condition. This allows users to run multiple pipelines each having different settings for generating the alerts. Eg — two sqls can be WHERE resource_type=”internal” and WHERE resource_type=”external”. Given two sqls this transform will emit two PCollections/Streams one with resource_type set to “internal” and other one with resource_type set to “external”.</li><li>This transform also evaluates if a given data point corresponds to an unstable state. It adds a new field into the incoming row called alert_state which can have two values — “Raise” and “Clear”.</li></ol><p>Implementation wise here most of the logic is to generate the Sql from users configuration. As mentioned earlier final Sql for us looks something like this -</p><pre>sql = SELECT *,</pre><pre>(CASE WHEN <strong>field1=1 AND field2&lt;5</strong> THEN ‘Raise’ ELSE ‘Clear’ END) as alert_state</pre><pre>FROM PCOLLECTION</pre><pre>WHERE <strong>field3=123 AND field4=345;</strong></pre><pre>// apply the sql on input pcollection</pre><pre>rowPCollection.apply(SqlTransform.query(sql));</pre><p>As we can see the sql transform is inserting a new column into the incoming rows, the schema has changed now. So be mindful of that fact when configuring any later components of the pipeline. For instance if we need to define RowCoder.of(schema) we should provide the updated schema to that RowCoder method.</p><pre>Schema newScheme = Schema.builder()</pre><pre>.addFields(inputDataSchema.getFields())</pre><pre>.addField(&quot;alert_state&quot;, Schema.FieldType.STRING)</pre><pre>.build();</pre><h4>Convert To Pojo DoFn</h4><p>The next building block in the pipeline is where we convert the incoming rows into domain agnostic Pojos. Rest of the pipeline after this DoFn uses Pojos.</p><p>Implementation wise this is pretty straightforward, we can rely on good old setters.</p><pre>pojo.setUserId(row.getInt64(“user_id”));</pre><pre>pojo.setFieldX(row.getString(“field_x”));</pre><p>There are however some utils provided by Beam sdk which can make our code a bit less verbose. We can use utils provided by beam sdk like Cast.castRow.</p><pre>Schema pojoSchema = new JavaBeanSchema().schemaFor(TypeDescriptor.of(Pojo.class));</pre><pre>// map fields from incoming row to the pojo row</pre><pre>Row pojoRow = Cast.castRow(input, inputDataSchema, pojoSchema);</pre><pre>// Convert the pojo row into actual java object</pre><pre>SerializableFunction&lt;Row, Pojo&gt; fromRowFn = new JavaBeanSchema().fromRowFunction(TypeDescriptor.of(Pojo.class));</pre><pre>Pojo output = fromRowFn.apply(pojoRow.build());</pre><p>Obviously the above works only for the fields which have the same name in the input row as the fields in the Pojo.</p><p>I will skip the rest of the pipeline, since those are mostly business logic related to how to generate the alerts. And these components are anyways tied to the Pojos so they are not relevant to this post.</p><h3>Conclusion</h3><p>In this post we saw one use case where we can leverage Beam Rows to generic pipelines which can be controlled by configs. In my opinion from a code readability point of view nothing beats code which is contracted on Pojos. Where we can take help of modern IDEs to navigate through the code. However in certain situations we can leverage Rows to write generic config driven components of a pipeline. Also using rows allows us to use SqlTransform which can be a powerful tool for certain use cases.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0a36b11b929" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unit testing Apache Beam Pipelines]]></title>
            <link>https://medium.com/@gauravmishra_82578/unit-testing-apache-beam-pipelines-c387855d27e7?source=rss-9550a43409d9------2</link>
            <guid isPermaLink="false">https://medium.com/p/c387855d27e7</guid>
            <category><![CDATA[apache-beam]]></category>
            <category><![CDATA[mocking]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[external-dependencies]]></category>
            <category><![CDATA[end-to-end-testing]]></category>
            <dc:creator><![CDATA[Gaurav Mishra]]></dc:creator>
            <pubDate>Sun, 25 Jul 2021 03:30:00 GMT</pubDate>
            <atom:updated>2021-07-25T03:34:05.958Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>At my current workplace, I work with a team where we build dashboards to give our customers insights into their network traffic data. To power these dashboards we have to process a lot of data from various sources within the company. For ingesting, enriching and aggregating that data we rely heavily on Apache Beam for building data processing pipelines. Which is an awesome framework to build data processing pipelines. And just like any good engineering team we also rely on our unit tests for making sure pipelines are doing what they are supposed to do. Figuring out how to do certain things in these unit tests was not a straightforward affair, but thanks to the apache beam mailing list I was able to figure out what I wanted. I was looking for a way to write end to end tests for my pipeline where you test the full pipeline as a single unit. In this post I will explain how to write such tests.</p><p>This post is intended for anyone who is using Apache Beam and looking for a way to set up end to end unit tests for their pipelines.</p><h3>Background</h3><p>My pipeline that I was looking to unit tests were reading and writing to PubSub. In one of the DoFns this pipeline was reading data from an external Redis and using that to enrich incoming input data. There was some other stuff like windowing and aggregation going on in the pipeline but it’s not important for this post. In my tests I wanted to test the full pipeline except for the IO portion. Below is a high level diagram of how my pipeline looks like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FKFbHKf3X0DJW6wz" /></figure><p>I wanted my tests to be self-contained tests which could test all business logic in the pipeline without having to do network calls to PubSub service or Redis Server. For Redis I could have spin off a docker container with a redis server running inside but I thought that would be an overkill for my use case given that I am simply using Redis as a distributed Hashmap. So I was looking for a way to replace the real Redis client with a Fake one for my unit tests. Something like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*33_nD7_uErUZ_iDs" /></figure><p>In my tests I am using a utility called TestStream for generating data which gives you a lot of control on how the data flows into your pipeline. <a href="https://beam.apache.org/blog/test-stream/">This</a> is a nice post about how you can use TestStreams. For output I am relying on another utility provided by the framework called PAssert which tests if the given output PCollection matches my expectations. In this unit test the tricky part was to figure out a way to inject a Mock Redis client in my pipeline without hacking the real code.</p><p>Now let’s jump into the code and see how we need to setup our dependencies in a way which allows for easy mocking of those dependencies.</p><h3>Production Code Setup</h3><p>For managing singletons like RedisClient we are using InstanceFactory. In pipeline options we define setter and getters for RedisClient like this</p><pre>@Default.InstanceFactory(RedisClientFactory.class)<br>RedisClient getRedisClient();</pre><pre>void setRedisClient(RedisClient client);</pre><p>Here <em>RedisClient</em> is an interface which will be implemented by the real redis client in production code and fake redis client in our unit test code. Now to tell the factory which class to instantiate we have another field declared in our pipeline options like this</p><pre>@Default.Class(RedisClientImpl.class)<br>Class&lt;? extends RedisClient&gt; getRedisClientClass();</pre><pre>void setRedisClientClass(Class&lt;? extends RedisClient&gt; redisClientClass);</pre><p>We will take help from this field in our unit test to tell the <em>RedisClientFactory</em> to instantiate <em>FakeRedisClient</em>. The factory is setup like this</p><pre>public class RedisClientFactory implements DefaultValueFactory&lt;RedisClient&gt; {<br>  <a href="http://twitter.com/Override">@Override</a><br>  public RedisClient create(PipelineOptions options) {</pre><pre>    CommonPipelineOptions pipelineOptions =   options.as(CommonPipelineOptions.class);</pre><pre>    return InstanceBuilder.ofType(RedisClient.class)<br>        .fromClass(pipelineOptions.getRedisClientClass())<br>        .fromFactoryMethod(&quot;fromOptions&quot;)<br>        .withArg(PipelineOptions.class, options)<br>        .build();<br>  }<br>}</pre><p>This is basically telling the framework to use the class defined in <em>pipelineOptions.getRedisClientClass()</em> to instantiate the <em>RedisClient</em> and expect a static method called <em>fromOptions</em> in the <em>RedisClient</em> implementor class. This method will be supplied with a single argument which is of type <em>PipelineOptions.class.</em></p><p>In our production code we want the factory to instantiate <em>RedisClientImpl</em>. And therefore <em>redisClientClass</em> is set to <em>RedisClientImpl.class</em> by default.</p><p>Code for instantiating RedisClientImpl looks like this -</p><pre>public class RedisClientImpl implements RedisClient {</pre><pre>private JedisPool pool;</pre><pre>  public static RedisClientImpl fromOptions(PipelineOptions options)   {<br>    return new RedisClientImpl(options.as(CommonPipelineOptions.class));<br>  }</pre><pre>public RedisClientImpl(CommonPipelineOptions commonPipelineOptions) {<br>   this.pool = setup jedis pool ....  <br>  }<br>}</pre><h3>Unit Test Code</h3><p>Now that we have all the necessary hooks in place that allows us to inject a fake Redis Client into our pipelines. Let’s see how to leverage those hooks in test code.</p><p>We start off by writing <em>FakeRedisClient</em> class and that code looks something like this</p><pre>public class FakeRedisClient implements RedisClient {</pre><pre>public static Map&lt;String, String&gt; keyToValueMap = new HashMap&lt;&gt;();</pre><pre>public static FakeRedisClient fromOptions(PipelineOptions options) {<br>    return new FakeRedisClient();<br>  }</pre><pre><a href="http://twitter.com/Override">@Override</a><br>  public String getByKey(String key) {<br>    return keyToValueMap.getOrDefault(key,&quot;&quot;);<br>  }<br>}</pre><p>As you can see this class is nothing but a wrapper around a HashMap.</p><p>Now in our tests, we have to tell the <em>RedisClientFactory</em> to instantiate <em>FakeRedisClient</em>. We do this by setting the <em>redisClientClass</em> property in pipeline options. So the unit test code looks like this</p><pre><a href="http://twitter.com/RunWith">@RunWith</a>(MockitoJUnitRunner.class)<br>public class PipelineTest {</pre><pre>  private CommonPipelineOptions options;<br>    <br>  <a href="http://twitter.com/Rule">@Rule</a><br>  public TestPipeline pipeline = TestPipeline.create();</pre><pre>  @Test<br>  public void endToEndTest() {<br>    options =       PipelineOptionsFactory.as(CommonPipelineOptions.class);<br>    TestStream&lt;InputDataClass&gt; inputStream =<br>        TestStream.create(SerializableCoder.of(InputDataClass))<br>            .addElements(createInput(...))<br>            .advanceWatermarkToInfinity();</pre><pre>   PCollection&lt;OutputClass&gt; outputStream = pipeline.apply(inputStream)<br>               .apply(Pardo.of(new DoFn1())<br>               .apply(Pardo.of(new EnrichDoFn())<br>               .apply(Pardo.of(new DoFn2())<br>               .apply(Pardo.of(new DoFn3()))<br>               ....</pre><pre><strong>   options.setRedisClientClass(FakeRedisClient.class);</strong></pre><pre>   String redisKey = ...<br>   String redisReturnVal = ...  objectMapper.writeValueAsString(cachedData);<br>    FakeRedisClient.keyToValueMap.put(redisKey, redisReturnVal);</pre><pre>   PAssert.that(outputStream).containsInAnyOrder(expectedData);</pre><pre>   pipeline.run(options);<br>   <br>  }<br>}</pre><p>Now when you run this test code the Redis dependent DoFn will receive instance of <em>FakeRedisClient</em> when it will do <em>options.getRedisClient()</em>. That’s it !!!</p><h3>Why not set RedisClient directly</h3><p>Now you might be thinking that why not simply set the RedisClient in the pipelineOptions.If you have time then I will encourage you to try doing just that. I tried doing that and encountered errors which led me to find the approach that I explained in the previous section.</p><p>You can set redis client directly by doing</p><pre>RedisClient redisClient = new FakeRedisClient()</pre><pre>options.setRedisClient(redisClient)</pre><pre>. . .</pre><pre>pipeline.run(options);</pre><p>Now when you run this code framework will serialize pipelineOptions along with the FakeRedisClient contained in it. Which enforces certain constraints on your implementation of FakeRedisClient. This client must be serializable which is not that big of a challenge. Now once pipelineOptions has been serialized, the serialized pipelineOptions will be passed to your DoFn. This DoFn will try to deserialize the pipelineOptions into a java object where it will fail, because the framework does not know how to deserialize that to a concrete implementation of <em>RedisClient</em>.</p><p>Now you can use Jackson to solve the puzzle of Serialization and Deserialization but that will require you to put some Unit test related code into your production code. You will most likely have to annotate your Interface with annotations like these</p><pre>@JsonTypeInfo(...)<br>@JsonSubTypes({@Type(value = FakeRedisClient.class, name = &quot;fakeRedisClient&quot;)})<br>Public interface RedsClient {...}</pre><p>This approach will also work but as you can see this is not a very clean solution since you have to add your FakeRedisClient as part of your production code.</p><h3>Summary</h3><p>In this post we saw an approach to write unit tests for apache beam pipelines which can test the full pipeline. If your pipeline depends on external data sources or apis you can use the approach documented above to mock those data sources of api calls.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c387855d27e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>