<?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 Vijay Shekhawat on Medium]]></title>
        <description><![CDATA[Stories by Vijay Shekhawat on Medium]]></description>
        <link>https://medium.com/@vijay_31043?source=rss-9d8d4e5a31d3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*WZ22ElyVK46Dq51oHIgqnQ.jpeg</url>
            <title>Stories by Vijay Shekhawat on Medium</title>
            <link>https://medium.com/@vijay_31043?source=rss-9d8d4e5a31d3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 13:59:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vijay_31043/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[Apache Iceberg Is Just the Tip of the Iceberg -Part 1]]></title>
            <link>https://medium.com/@vijay_31043/apache-iceberg-is-just-the-tip-of-the-iceberg-part-1-8f9cf6505795?source=rss-9d8d4e5a31d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f9cf6505795</guid>
            <category><![CDATA[apache-iceberg]]></category>
            <category><![CDATA[data-lakehouse]]></category>
            <dc:creator><![CDATA[Vijay Shekhawat]]></dc:creator>
            <pubDate>Mon, 05 May 2025 16:44:15 GMT</pubDate>
            <atom:updated>2025-05-27T10:18:03.431Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PHqtpLn7VHB7JJaWFNdSNw.png" /></figure><p>You&#39;ve probably seen a seismic shift if you’ve been following the data world lately. Snowflake <a href="https://www.snowflake.com/en/news/press-releases/snowflake-unveils-apache-iceberg-innovations/">announced</a> full support for Apache Iceberg, claiming Iceberg tables perform on par with their proprietary storage. Databricks then <a href="https://www.databricks.com/company/newsroom/press-releases/databricks-agrees-acquire-tabular-company-founded-original-creators">invested</a> over a billion dollars to acquire Tabular, an Iceberg-focused company, despite having its own battle-tested Delta Lake format. <a href="https://cloud.google.com/blog/products/data-analytics/announcing-bigquery-tables-for-apache-iceberg">BigQuery</a> and <a href="https://docs.aws.amazon.com/athena/latest/ug/querying-iceberg.html">Athena</a> have rolled out Iceberg compatibility, and Snowflake and Databricks have open-sourced their <a href="https://www.snowflake.com/en/blog/polaris-catalog-open-source/">Polaris</a> and <a href="https://www.databricks.com/blog/open-sourcing-unity-catalog">Unity catalog</a> offerings, respectively.</p><p><strong>What’s driving this whirlwind of activity?</strong> Beyond the headlines, there’s a deeper story about cost, control, and genuine openness.</p><h3>The Promise: Cost Efficiency and Architectural Freedom</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*2ZdMKyKfaG-34RoDthxSng.png" /><figcaption>Diagram 1: Iceberg Ecosystem</figcaption></figure><p>At first glance, Apache Iceberg’s appeal often centres on <strong>storage cost savings</strong>, which are cheaper than many proprietary alternatives. But saving money is only the beginning.</p><p>More importantly, Iceberg <strong>decouples storage from compute</strong>. In principle, you write data once into Iceberg and can then query it with Spark, Trino, or Snowflake interchangeably (see Diagram 1). This “write once, query anywhere” model promises architectural freedom, allowing you to:</p><ul><li><strong>Optimise costs</strong> by choosing the most efficient engine for each workload</li><li><strong>Experiment freely</strong> with new compute engines without data migration.</li><li><strong>Avoid lock-in</strong> by standardising on an open storage format.</li></ul><h3><strong>Reality Check: Lock-In by Any Other Name</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*xWgnQnFHlaCUQdxDusgHoQ.png" /><figcaption>Diagram 2</figcaption></figure><p>Despite adopting Iceberg, many organisations are still tethered to their original compute platform. Why?</p><ul><li><strong>Monolithic Architectures.</strong> Most databases bundle their storage, compute engine, and API’s into a single system(Diagram 3). Simply swapping out the storage layer(Diagram 4) for Iceberg doesn’t give you true strategic autonomy — teams naturally fall back on the same compute engine they know.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*Q_ZUTXErSRTd2_mU1gWl5g.png" /><figcaption>Diagram 3:Monolithic Design of Modern Databases</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*KKTaX4pe6stRCNESY0cwRA.png" /><figcaption>Diagram 4</figcaption></figure><ul><li><strong>Proprietary APIS and Extensions.</strong> Developers continue using vendor-specific SQL extensions, UDF, and SDK, making switching engines without rewriting code practically impossible.</li><li><strong>Migration Overhead.</strong> Changing compute engines involves swapping binaries, retraining teams, refactoring pipelines, and revalidating performance.</li></ul><p>The result? Storage might be portable, but your compute layer remains firmly in place.</p><h3><strong>The Missing Piece: A Unified Query Interface</strong></h3><p>To unlock Iceberg’s full promise, we need <strong>more than</strong> an open storage format — That’s because <a href="https://github.com/apache/iceberg">Apache Iceberg</a> is only part of the story<strong>, just the tip of the iceberg.</strong> Decoupling storage is an essential first step, but an “open data lake” requires more than an open storage format. This is where <a href="https://github.com/substrait-io/substrait"><strong>Apache Substrait </strong></a>comes in. If Iceberg serves as the <strong>lingua franca for storage</strong>, then Substrait is the <strong>lingua franca for compute operations</strong>:</p><ul><li><strong>Engine-Agnostic Plans.</strong> <a href="https://github.com/substrait-io/substrait">Apache Substrait</a> defines a standardised relational-algebra interface. SQL queries are compiled into a uniform plan that any substrait-compatible engine can execute.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*g9JdzVgUEbRO5uHsh0bVSw.png" /><figcaption>Diagram 5</figcaption></figure><h4><strong>Example:</strong></h4><p><strong>Before Substrait:</strong> Each engine compiles SQL into its proprietary query plan, requiring custom connectors and duplicated optimisation logic for every platform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dqd_IA6dx6h_obITZ7umJQ.png" /><figcaption>Diagram 6: Typical Database request</figcaption></figure><p><strong>After Substrait:</strong> Clients emit a unified Substrait plan — every compatible engine interprets the exact relational-algebra representation, enabling portable, consistent, and streamlined query execution across systems.</p><blockquote>One engine might execute it in a distributed cluster(e.g Trino); another might optimise it for a single-node(e.g DuckDB), in-memory run — yet the logic and results stay consistent.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gC3V8lHEWYc32KlITurfug.png" /><figcaption>Diagram 7: Database request with Apache Substrait</figcaption></figure><h3><strong>What’s Next: Bringing It All Together</strong></h3><p>Apache Iceberg and Apache Substrait lay the groundwork for an open, flexible lakehouse, yet the story isn’t complete. Substrait’s standardised query plans offer tremendous promise, but the ecosystem still needs broader adoption by open-source projects and commercial vendors to unlock its full potential.</p><p>In Part 2, I’ll explore <a href="https://github.com/apache/arrow">Apache Arrow</a> — an in-memory, columnar format that removes serialisation bottlenecks and makes Substrait plans truly portable. <strong>As a lingua franca for data in-memory or in-motion</strong>, Arrow lets engines exchange data in zero-copy batches measured in microseconds, enabling:</p><p>• <strong>Seamless data interchange</strong> across heterogeneous compute engines</p><p>• <strong>Ultra-low latency</strong> analytics pipelines</p><p>• <strong>Hybrid architectures</strong> that stitch together best-of-breed tools</p><p>Together — Iceberg for open storage, Substrait for engine-agnostic computation, and Arrow for high-performance data interchange — these three projects appear to form the blueprint for the next generation of analytics platforms. The industry seems to be aligning around this trio of standards, and early adopters are beginning to see benefits in vendor neutrality, faster innovation cycles, and improved scalability.</p><blockquote>Stay tuned to see how <a href="https://github.com/apache/arrow">Apache Arrow</a> fills in the final piece and why this emerging open-standards stack could reshape what’s possible in the lakehouse landscape.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f9cf6505795" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes through the lens of Data Engineering]]></title>
            <link>https://medium.com/@vijay_31043/kubernetes-through-the-lens-of-data-engineering-9a486c7efe5b?source=rss-9d8d4e5a31d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a486c7efe5b</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Vijay Shekhawat]]></dc:creator>
            <pubDate>Sat, 16 Mar 2024 14:27:17 GMT</pubDate>
            <atom:updated>2024-03-16T14:27:17.225Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rEpl_S3R5yOyWVIFdMdNTQ.png" /></figure><p>As a data platform engineer, my journey with Kubernetes was initially sporadic, touching upon its capabilities in various projects. However, in the last few months, my engagement with Kubernetes has deepened, as I’ve deployed critical data products using this powerful platform. This experience has led me to ponder whether learning Kubernetes is beneficial for data engineers.</p><blockquote>The short answer is <strong>YES</strong>.</blockquote><p>While it’s true that many data engineers can excel in their roles without Kubernetes, embracing it can equip you with a potent tool that’s likely to benefit your career trajectory.</p><p>This blog isn’t meant to polarize opinions on Kubernetes; I recognize the diversity of perspectives ranging from skepticism to outright enthusiasm. Instead, I aim to share insights for those interested in Kubernetes, especially from a data engineering viewpoint. I will start by discussing how Kubernetes fits in the data world and then go on to break down the general concepts of Kubernetes, followed by lessons I learned along the way and tips.</p><h3>Does Data Engineering and Kubernetes even fit together well?</h3><p>The intersection of data engineering and Kubernetes is particularly special due to the unique challenges and opportunities it presents — Here’s why</p><h4>Stateful Applications in a Stateless Environment</h4><p>Kubernetes was initially designed to support stateless applications, but data engineering is inherently stateful. This posed a challenge that has led to significant advancements in Kubernetes, like StatefulSets and Persistent Volumes. These allow data engineers to run databases and other stateful services reliably, maintaining the state required for complex data operations.</p><h4>Scalability Meets Data Volume</h4><p>Data engineering is characterized by the need to process large volumes of data. Kubernetes excels in its ability to scale applications on the fly. Data engineers can leverage Kubernetes to dynamically scale their data processing jobs up or down to match the demand, ensuring efficient use of resources and timely insights.</p><h4>Complex Workflows Simplified</h4><p>Data engineering involves complex workflows that can benefit from Kubernetes’ sophisticated orchestration capabilities. Kubernetes can manage dependencies and the execution order of tasks, handle retries and failures, and enable rolling updates with no downtime — features that are essential for the continuous operation of data pipelines.</p><h4>Ephemeral Environments for Immutable Deployments</h4><p>Data engineers often need to create and dispose of environments for testing and experimentation. Kubernetes supports the concept of immutable deployments through ephemeral environments, making it easier to test data processing applications in conditions close to production.</p><h4>Enhanced Collaboration Across Teams</h4><p>Kubernetes not only streamlines deployment but also fosters collaboration between data engineers, developers, and operations teams. The use of declarative configurations and the Kubernetes API facilitates a common language and understanding among these diverse groups, leading to more cohesive and robust data solutions.</p><h3>Understanding Kubernetes: The Core Concepts</h3><p>Kubernetes, at its heart, is a container orchestration system. It automates the deployment, scaling, and management of containerized applications. Here are some key concepts every data engineer should know:</p><ul><li><strong>Containers</strong>: Encapsulated application environments that contain all the necessary executables, binary code, libraries, and configuration files.</li><li><strong>Pods</strong>: The smallest deployable units created and managed by Kubernetes. A pod represents a single instance of a running process in your cluster.</li><li><strong>Nodes</strong>: These are the physical or virtual machines that make up the cluster. Each node can host multiple pods.</li><li><strong>Services</strong>: An abstract way to expose an application running on a set of Pods as a network service.</li><li><strong>Ingress</strong>: An API object that manages external access to the services in a cluster, typically HTTP.</li><li><strong>Helm</strong>: A package manager for Kubernetes, allowing you to define, install, and upgrade even the most complex Kubernetes applications.</li></ul><p>Additionally, understanding managed Kubernetes services like Google Kubernetes Engine (GKE) can significantly reduce the overhead of setting up and maintaining Kubernetes clusters. These platforms offer automated scaling, updates, and more, making Kubernetes more accessible to teams without deep infrastructure expertise.</p><p>Here are some of the key lessons learned and tips that I’ve gathered along my journey, which I believe will be beneficial for fellow data engineers also venturing into Kubernetes.</p><h3>Lesson 0: Path to Kubernetes goes via Containerization</h3><p>To deploy containerized apps and services to Kubernetes it’s paramount to understand containerization. Containerized data applications are powerful, efficient, and portable. Containers encapsulate your application’s environment, ensuring that it works uniformly across different platforms. Docker is a popular containerization platform that allows you to create a containerized application using a DockerFile.</p><p><strong>Tip</strong>: Invest time in learning Docker before jumping into Kubernetes. Understanding how to containerize your data processing applications will make your Kubernetes journey smoother and more productive.</p><h3>Lesson 1: Embrace the Kubernetes Ecosystem Gradually</h3><p>Kubernetes boasts a vast ecosystem, filled with tools and extensions that can significantly enhance your data engineering projects. However, trying to learn everything at once can be overwhelming. Start with the basics — understand pods, nodes, and services, and how they can be orchestrated to manage your applications. Gradually incorporate more complex concepts like Helm for package management and operators for automating application management.</p><h3>Lesson 3: Declarative Configuration is Your Friend</h3><p>Kubernetes operates on a declarative model, where you describe the desired state of your application in YAML or JSON format, and Kubernetes works to maintain that state. This approach simplifies the management of complex applications.</p><p><strong>Tip</strong>: As you start to work with Kubernetes, practice writing and maintaining your deployment configurations. Use version control systems like Git to track changes to these configurations, enhancing collaboration and rollback capabilities.</p><h3>Lesson 4: Understand the Importance of Monitoring and Logging</h3><p>Monitoring and logging are crucial in Kubernetes to ensure the health and performance of your applications. Kubernetes and its ecosystem provide powerful tools for this, like Prometheus for monitoring and Fluentd for logging.</p><p><strong>Tip</strong>: Set up monitoring and logging early in your Kubernetes journey. This will help you troubleshoot issues efficiently and understand the behavior of your applications in a production-like environment.</p><h3>Lesson 5: Community and Collaboration are Key</h3><p>The Kubernetes community is one of its greatest strengths. There’s an immense pool of knowledge and resources available, from forums and Slack channels to meetups and conferences.</p><p><strong>Tip</strong>: Don’t hesitate to engage with the community. Whether it’s asking questions, sharing your learnings, or contributing to projects, participation can significantly enhance your understanding and appreciation of Kubernetes.</p><h3>Final thoughts</h3><p>Kubernetes has been more than just a tool; it’s been a journey of learning and discovery. For data engineers willing to embark on this journey, the rewards extend far beyond the immediate technical capabilities. Kubernetes as a toolkit opens up new avenues for scalability, reliability, and performance in data engineering. This journey from novice to practitioner is not just about acquiring skills but about embracing a new way to think about and manage data pipelines and infrastructure.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a486c7efe5b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Architecting Real-Time Blockchain Intelligence at TRM Labs Part 1]]></title>
            <link>https://medium.com/trmlabs/architecting-real-time-blockchain-intelligence-at-trm-labs-part-1-e356d22cbab5?source=rss-9d8d4e5a31d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/e356d22cbab5</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[real-time-streaming-data]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[realtime-analytics]]></category>
            <dc:creator><![CDATA[Vijay Shekhawat]]></dc:creator>
            <pubDate>Wed, 10 Jan 2024 04:00:20 GMT</pubDate>
            <atom:updated>2024-01-10T04:00:20.169Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RRDpx8pM8XbMdwpTw-TsPQ.jpeg" /></figure><h3>Architecting Real-Time Blockchain Intelligence at TRM Labs Part 1: Evaluating Stream Processing Architectures and Engines</h3><h3>Why Real-Time Stream Processing</h3><p>At TRM Labs, a leader in monitoring, detecting, and investigating crypto fraud and financial crime, we routinely ingest and analyze petabytes of blockchain data daily. To support real-time blockchain intelligence at scale, we built an in-house real-time data processing pipeline to reliably and cost-effectively process petabytes of blockchain data.</p><h3>Exploring Architectures</h3><p>We began by exploring various architectures, notably the Lambda and Kappa models.</p><h4>Lambda Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hx4-LVgPlbgSZGFu7RLDzA.png" /></figure><p>Lambda architecture is a dual data processing technique comprised of a Batch Layer and a Stream Layer (also known as Speed layer), that is capable of dealing with huge amounts of data efficiently.</p><ul><li><strong>Batch layer: </strong>New data keeps coming as a feed to the data system. Any new data stream that comes to the batch layer of the data system is computed and processed on top of a Data Lake at a predefined cadence.</li><li><strong>Stream Layer: </strong>New data is computed and processed in real-time using a stream processing engine.</li><li><strong>Serving Layer: </strong>The outputs from the batch layer in the form of batch views and from the stream layer in the form of near-real-time views are forwarded to the serving layer which merges the results from both layers to provide a comprehensive view of the data.</li><li><strong>Pros</strong>: Robust, fault-tolerant, and suitable for complex processing tasks.</li><li><strong>Cons:</strong> Complexity in maintaining two separate systems.</li></ul><h4>Kappa Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4pKprGgCsHpwy9IFv0c_tQ.png" /></figure><p>Kappa Architecture is a streamlined approach where a single processing layer handles both real-time and historical data.</p><ul><li><strong>Single Processing Layer: </strong>Unlike Lambda Architecture, which uses both batch and stream processing, Kappa Architecture relies solely on stream processing. This simplification means that all data, both historical and real-time, is treated as a stream.</li><li><strong>Serving Layer:</strong> After processing, the data is typically pushed to a serving layer, which might consist of databases or other storage systems that enable quick data retrieval and querying.</li><li><strong>Pros:</strong> Simplified architecture, easier to maintain.</li><li><strong>Cons:</strong> Less efficient for complex, multi-step processing.</li></ul><p>We opted for the Lambda architecture due to its dual-layered processing framework. This dual approach offers a significant benefit in terms of fault tolerance. In scenarios where the stream processing pipeline encounters issues or failures, we can seamlessly fall back on the batch processing pipeline. This redundancy ensures that our data processing operations can continue without significant interruptions, maintaining the integrity and continuity of our data workflows.</p><p>Moreover, the batch layer is particularly useful and effective for tasks like data backfills. It can efficiently process and load petabytes of data, using bulk load operators like <a href="https://www.postgresql.org/docs/current/sql-copy.html">COPY</a>.</p><h3>Choosing the Right Stream Processing Engine</h3><p>The next step in our journey to building the Real-Time Blockchain Stream Processing Architecture at TRM Labs was choosing the right processing engine. In our case, the decision revolved around finding the right balance between Performance, Scalability, Maintenance Overhead, Compatibility with our existing systems, and, Cost. We also considered factors like the skill set of our team and the specific requirements of our blockchain data processing needs. This comprehensive evaluation guided us to choose an engine that not only met our current requirements but also aligned with our vision for scalable and efficient real-time data processing in the domain of crypto asset compliance and risk management.</p><p>We compared various engines, including Spark Structured Streaming, Apache Beam, Apache Flink, and Kafka Streams, across several critical dimensions:</p><h4>Performance</h4><p>Performance in stream processing refers to the system’s ability to process high volumes of data with minimal latency. This was of prime importance given the nature of the data and stakes involved at TRM Labs. We needed a stream-processing engine that could achieve the sub-second latency of a block being mined.</p><p><strong>Key Aspects:</strong></p><ul><li><strong>Throughput:</strong> The amount of data the system can process within a given time frame.</li><li><strong>Latency: </strong>The time taken for data to be processed and for results to be available after ingestion.</li><li><strong>Efficiency:</strong> How well the system utilizes resources like CPU, memory, and network.</li><li><strong>Impact:</strong> High performance ensures timely data processing, which is critical for real-time applications like fraud detection or live monitoring systems.</li></ul><h4>Scalability</h4><p>Scalability is the ability of the system to handle increasing volumes of data, increasing number of data pipelines, or more complex processing demands without a significant drop in performance. This was a key requirement as TRM supports over 30 blockchains, including high TPS blockchains such as Solana, Tron, and Binance Smart Chain.</p><p><strong>Key Aspects:</strong></p><ul><li><strong>Horizontal vs. Vertical Scaling: </strong>Whether the system can scale by adding more machines (horizontal) or by adding resources to a single machine (vertical).</li><li><strong>Elasticity:</strong> The ease with which the system can scale up or down in response to changing demands.</li><li><strong>Impact:</strong> Scalable systems can accommodate growth in data volume and complexity, ensuring longevity and adaptability of the investment.</li></ul><h4>Maintenance Overhead</h4><p>This refers to the effort and resources required to keep the system running smoothly. We wanted to keep this as minimal as possible to reduce spending time maintaining the system and focus on building new software.</p><p><strong>Key Aspects:</strong></p><ul><li><strong>Operational Complexity:</strong> Minimize operational complexity to ensure that monitoring and remediation can be handled with a simple runbook by any engineer in our follow-the-sun on-call rotation.</li><li><strong>Online Migration: E</strong>ase with which the system can be updated or upgraded without significant downtime</li><li><strong>Reliability:</strong> The frequency and impact of system failures or bugs.</li><li><strong>Impact:</strong> Systems with lower maintenance overhead reduce the total cost of ownership and free up resources for other tasks.</li></ul><h4>Compatibility</h4><p>Compatibility concerns how well the new system integrates with existing technologies and infrastructure. We use the GCP stack and needed this new processing engine to fit well with our batch-processing stack of BigQuery/Postgres/Redis/Airflow.</p><p><strong>Key Aspects:</strong></p><ul><li><strong>Integration with Existing Tools:</strong> Compatibility with current data sources, storage solutions, and other tools.</li><li><strong>Data Formats and Protocols:</strong> Ability to handle various data formats and communication protocols.</li><li><strong>Impact:</strong> High compatibility reduces integration challenges and leverages existing investments in technology.</li></ul><h4>Cost</h4><p>Cost involves the total expenditure associated with implementing and operating the system.</p><p><strong>Key Aspects:</strong></p><ul><li><strong>Initial Setup Costs:</strong> Expenses related to acquiring the technology, including licensing fees if applicable, infrastructure setup, and, development and testing costs.</li><li><strong>Operational Expenses:</strong> Ongoing costs such as hosting, maintenance, and monitoring.</li><li><strong>Scalability-Related Costs:</strong> Costs associated with scaling the system in response to increased demands.</li><li><strong>Impact:</strong> Understanding and optimizing cost is crucial for ensuring that the solution is financially viable and delivers a good return on investment.</li></ul><h4><strong>Evaluating stream processing engine</strong></h4><figure><img alt="Evaluating streaming engine in Context of TRM Labs stack" src="https://cdn-images-1.medium.com/max/1024/1*B0elPzO0rfjeW8WAZiy_fw.png" /></figure><h4>Decision: Apache Beam with GCP Dataflow</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*L0Ct2E9n_Hjp7ew6rmFzjg.png" /></figure><h4><strong>Explanation:</strong></h4><ul><li><strong>Performance:</strong> Apache Beam with GCP Dataflow: Exceptional performance, especially for data processing tasks within the GCP ecosystem. Dataflow optimizes and manages the execution environment, leading to enhanced performance.</li><li><strong>Scalability: </strong>Apache Beam with GCP Dataflow: As a managed service it provides excellent scalability, as Dataflow seamlessly manages resource allocation and scaling, making it highly efficient for handling varying data loads.</li><li><strong>Maintenance Overhead: </strong>Apache Beam with GCP Dataflow: Lower maintenance overhead due to the managed nature of GCP Dataflow. It abstracts much of the operational complexity associated with running large-scale data processing jobs.</li><li><strong>Compatibility:</strong> Apache Beam with GCP Dataflow: Superior compatibility with GCP services, offering seamless integration with other cloud services and tools such as GCP monitoring. This makes it an ideal choice for teams heavily invested in the GCP stack.</li><li><strong>Cost:</strong> Apache Beam with GCP Dataflow: While generally cost-effective, especially for GCP users, the costs can vary based on the scale of data processing and the specific resources used. The managed nature of Dataflow can lead to higher costs at scale, Dataflow prime mitigates that to a great extent and it also offers significant savings in terms of operational overhead and time.</li></ul><h4>Additional Considerations:</h4><ul><li><strong>Flexible Execution and Portable Code:</strong> Apache Beam supports a variety of execution engines, including Apache Spark, Google Cloud Dataflow, and Apache Flink. This offers us the flexibility to choose the execution engine that best meets our needs or change it in the future with limited to no code changes.</li><li><strong>Beam Unified Model:</strong> Apache Beam provides a unified model for batch and streaming data processing. This means that we can use the same Beam code to process data that is either coming in as a stream or that has already been collected into a batch.</li></ul><h3>Up Next: Architecting Real-Time Blockchain Intelligence at TRM Labs Part 2: Navigating Stream Processing Challenges</h3><p>There are a lot more exciting things to unpack as we unfold our journey for building real-time processing at TRM Labs, and discuss how we navigated stream processing challenges — stay tuned in for Part 2!</p><p><strong>We are hiring – </strong><a href="https://www.trmlabs.com/careers"><strong>Join us</strong></a><strong> in building the future of finance!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e356d22cbab5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/trmlabs/architecting-real-time-blockchain-intelligence-at-trm-labs-part-1-e356d22cbab5">Architecting Real-Time Blockchain Intelligence at TRM Labs Part 1</a> was originally published in <a href="https://medium.com/trmlabs">TRM Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling High Throughput Real-Time Pipelines Writes to Databases: Challenges and Strategies]]></title>
            <link>https://medium.com/@vijay_31043/handling-high-throughput-real-time-pipelines-writes-to-databases-challenges-and-strategies-6f3a4e8254bc?source=rss-9d8d4e5a31d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f3a4e8254bc</guid>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[streaming]]></category>
            <category><![CDATA[real-time-analytics]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Vijay Shekhawat]]></dc:creator>
            <pubDate>Sun, 05 Nov 2023 19:31:55 GMT</pubDate>
            <atom:updated>2024-05-29T04:08:03.892Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*IuR3RnHKQZkZv6Ahv3txmA.jpeg" /></figure><p>In the fast-paced realm of digital interactions, the capability to handle and write high volumes of data in real-time is not just advantageous but essential. The challenge lies not only in the interaction with the data but more critically in the systems’ ability to process and record this information swiftly and reliably. Whether it’s managing customer service requests, processing e-commerce transactions, or conducting financial operations, the robustness of real-time data writing systems is at the core of service reliability.</p><p>These systems are tasked with a complex challenge: orchestrating the data flow to ensure responsiveness and accuracy, regardless of the volume. It’s about ensuring that the system architecture is robust enough to handle the velocity of data ingestion. This is where the intricate work of configuring real-time data writes becomes pivotal. Adjusting data pipeline configurations, optimizing database session settings, and managing concurrent data updates are key to achieving the high throughput necessary for maintaining the integrity of real-time data systems.</p><h3>Stages of streaming data pipelines</h3><p>The architecture of a real-time data pipeline is typically segmented into two primary stages: processing and writing. Each stage plays a critical role in the data lifecycle and demands a unique set of strategies to handle the real-time requirements effectively.</p><h4>Processing Stage</h4><p>In the processing stage, the data pipeline ingests raw data streams from various sources. Real-time processing involves filtering, aggregation, and sometimes complex event processing to detect patterns or specific conditions within the data stream. Systems leverage stream processing frameworks like Apache Kafka, Apache Flink, or Apache Storm to handle these tasks with minimal latency. This won’t be the focus of this article.</p><h4>Writing Stage</h4><p>The writing stage is where processed data is persisted in a storage system, typically a database, for future retrieval and analysis. This stage must be optimized to handle high throughput while maintaining data consistency and integrity. It is here that the choice of database becomes critical, as each type has its own set of protocols and optimizations for data writing.</p><h4>Handling Writes to Various Databases</h4><p>Databases like PostgreSQL, Apache Pinot, and ClickHouse each offer distinct advantages for different use cases, but they also present unique challenges in the context of real-time data writes.</p><ul><li><strong>PostgreSQL</strong>: As a powerful relational database, PostgreSQL excels in transactional integrity and complex queries. However, high-throughput real-time writes may require partitioning, write-ahead logging configurations, and replication to balance the load and ensure data durability.</li><li><strong>Apache Pinot</strong>: Designed for real-time analytics, Pinot provides low latency on high throughput writes but demands careful schema design and indexing strategies to optimize for real-time query performance.</li><li><strong>ClickHouse</strong>: ClickHouse thrives on columnar storage, making it suitable for analytics over large datasets. It requires meticulous management of data parts and replication to ensure efficient real-time writes and availability.</li></ul><p>For the purpose of this article, we will focus on PostgreSQL but these approaches should generally be applicable to others as well.</p><h4>Engine Choice and Configuration Impact</h4><p>The choice of the data processing engine such as Apache Spark or Apache Beam plays a significant role in the writing stage, particularly in how data is prepared and loaded into the database.</p><ul><li><strong>Apache Spark</strong>: Spark’s in-memory processing capabilities can be configured for efficient partitioning and memory management, influencing the speed and consistency of data writes.</li><li><strong>Apache Beam</strong>: With Beam, the windowing and batching of data writes are central to managing and optimizing the flow of data into storage systems, affecting real-time data handling.</li></ul><p>Proper engine configuration can have a profound impact on performance. Batch sizes, buffering strategies, autoscaling, and data partitioning must be calibrated to balance load, minimize latency, and maximize throughput. The interplay between the engine’s capabilities and the database’s write protocols is a determining factor for the system’s overall performance.</p><h3>Real-Time Data Pipeline Write Optimization: A Multilayered Approach</h3><p>Real-time data pipeline writes require a harmonized approach to optimization that spans multiple layers of the technology stack. To achieve the necessary performance for high-throughput, real-time writes, configurations must be carefully adjusted at the database level, pipeline level, and network level. Each layer plays a pivotal role in the overall efficiency and reliability of the system.</p><h3>Layer 1: Pipeline Configuration</h3><p>The pipeline configuration dictates how data flows from the source to the database. It involves several components that can be fine-tuned to enhance performance.</p><h4><strong>Batch Real-Time Writes</strong></h4><p>Utilizing batching in real-time writes can dramatically reduce the number of write operations, thereby enhancing throughput. By configuring an appropriate batch size, we can combine multiple records into a single database operation, which is particularly useful when interfacing with databases through JDBC.</p><p>Apache Beam Example:</p><pre>// Example for Apache Beam using JDBC IO<br>pipeline.apply(JdbcIO.&lt;KV&lt;Integer, String&gt;&gt;write()<br>    .withDataSourceConfiguration(JdbcIO.DataSourceConfiguration.create(<br>        &quot;org.postgresql.Driver&quot;, &quot;jdbc:postgresql://hostname:port/databaseName&quot;))<br>    .withStatement(&quot;insert into KV values(?, ?)&quot;)<br>    .withPreparedStatementSetter((element, statement) -&gt; {<br>      statement.setInt(1, element.getKey());<br>      statement.setString(2, element.getValue());<br>    })<br>    .withBatchSize(500)); // Sets the JDBC batch size</pre><p>Apache Spark Example:</p><pre>// Spark example for batching writes <br>df.write.format(&quot;jdbc&quot;)<br>.option(&quot;url&quot;, &quot;jdbc:postgresql:dbserver&quot;)<br>.option(&quot;dbtable&quot;, &quot;schema.tablename&quot;)<br>.option(&quot;batchsize&quot;, 500)<br>.save()</pre><h4><strong>Buffer Writes</strong></h4><p>Buffering writes means temporarily storing data in memory before writing it to the database. Apache Beam’s windowing feature can be employed to aggregate data into temporal batches or windows. This not only aligns with the natural ebb and flow of data but also avails the opportunity to perform deduplication before the data persists (this is more efficient as it involves a much smaller subset of data), which can be crucial for maintaining data integrity.</p><pre>// Example of windowing with Apache Beam<br>PCollection&lt;KV&lt;String, String&gt;&gt; input = ...;<br>input.apply(Window.&lt;KV&lt;String, String&gt;&gt;into(FixedWindows.of(Duration.standardMinutes(2)))<br>    .triggering(AfterWatermark.pastEndOfWindow()<br>        .withEarlyFirings(AfterProcessingTime.pastFirstElementInPane()<br>            .plusDelayOf(Duration.standardMinutes(1)))<br>        .withLateFirings(AfterPane.elementCountAtLeast(100)))<br>    .discardingFiredPanes())<br>    .apply(GroupByKey.create())<br>    .apply(ParDo.of(new DoFn&lt;KV&lt;String, Iterable&lt;String&gt;&gt;, Void&gt;() {<br>      @ProcessElement<br>      public void processElement(ProcessContext c) {<br>        // Handle deduplication logic here<br>      }<br>    }));</pre><h4><strong>Scaling</strong></h4><p>When it comes to handling large volumes of data, scaling is often the go-to solution. However, scaling, particularly auto-scaling, must be managed with prudence. Unrestricted scaling can lead to an excessive number of write connections to the database, which could overwhelm it and degrade performance. Thus, while scaling is an effective strategy to handle increasing loads, it should be implemented with thresholds and limits to prevent overloading the system.</p><h3>Layer 2: Network Layer Configuration</h3><p>The network layer is often overlooked, but it’s just as critical for performance, especially in distributed systems where components may span across different physical locations.</p><h4>Bandwidth and Latency Optimization</h4><p>The physical proximity of processing services and databases can significantly affect the performance of data operations. Deploying both components within the same region or zone of a cloud provider can minimize network latency, leading to faster data transfers. Besides geographical considerations, it’s important to select the right network tier that offers optimal bandwidth for the expected data load, ensuring that the network does not become a bottleneck.</p><h4>Timeout Settings</h4><p>Properly configured timeouts are essential to prevent a temporary network issue from causing long-term disruption. Socket timeouts and session timeouts must be fine-tuned to balance between giving enough time for a legitimate operation to complete and not allowing a stuck process to hold resources indefinitely.</p><h4>Socket Timeout for JDBC</h4><p>When using JDBC to connect to a database, the socket timeout can be set to define how long the driver will wait for a response from the database before timing out.</p><p>Example Code for Setting Socket Timeout:</p><pre>Properties connectionProps = new Properties();<br>connectionProps.put(&quot;user&quot;, &quot;myUsername&quot;);<br>connectionProps.put(&quot;password&quot;, &quot;myPassword&quot;);<br>// Set the socket timeout to 300 seconds<br>connectionProps.put(&quot;socketTimeout&quot;, &quot;300000&quot;);<br>Connection conn = DriverManager.getConnection(&quot;jdbc:postgresql://hostname:port/dbname&quot;, connectionProps);</pre><p>In this example, the socket timeout is set through the properties object which is passed to the DriverManager.getConnection() method when establishing a connection to a PostgreSQL database.</p><p>Additional Techniques:</p><ul><li><strong>Content Delivery Networks (CDNs)</strong>: For distributed systems, employing CDNs can cache data closer to the end-user, reducing latency.</li><li><strong>Direct Connections</strong>: Services like AWS Direct Connect or Google Cloud’s Dedicated Interconnect provide a direct link from on-premises to the cloud, bypassing the public internet for more consistent network performance.</li></ul><h3>Layer 3: Database Layer Configuration</h3><p>The configuration at the database level is critical for handling the high-volume, high-velocity demands of real-time data pipelines. Below are some techniques and considerations to optimize database performance:</p><h4>Connection Pooling</h4><p>Managing database connections efficiently is paramount. Connection pooling, for instance using HikariCP, allows for a significant performance boost. HikariCP is renowned for its lightweight nature and excellent connection management features, including a fast connection borrowing mechanism and a highly optimized pool configuration that can dramatically reduce the latency of connection acquisition.</p><pre>// Example of HikariCP configuration in <br>Java HikariConfig config = new HikariConfig(); <br>config.setJdbcUrl(&quot;jdbc:postgresql://localhost:5432/database&quot;); <br>config.setUsername(&quot;user&quot;); config.setPassword(&quot;password&quot;); <br>config.addDataSourceProperty(&quot;cachePrepStmts&quot;, &quot;true&quot;); <br>config.addDataSourceProperty(&quot;prepStmtCacheSize&quot;, &quot;250&quot;); <br>config.addDataSourceProperty(&quot;prepStmtCacheSqlLimit&quot;, &quot;2048&quot;); <br>HikariDataSource dataSource = new HikariDataSource(config);</pre><h4>Timeouts</h4><p>Properly setting timeouts can prevent prolonged waits that tie up resources. There are several timeouts to consider:</p><ul><li><strong>Connection Timeout</strong>: The time it takes to establish a connection. If set. too high, failing connections can hog resources.</li><li><strong>Statement Timeout</strong>: The maximum time for a SQL statement to execute, helping to avoid running costly operations that could degrade performance.</li><li><strong>Idle Timeout</strong>: The maximum amount of time that a connection can sit idle in the pool before being closed.</li></ul><pre>-- Example of setting a statement timeout in PostgreSQL <br>SET statement_timeout = &#39;5min&#39;;</pre><h4>Indexing</h4><p>Efficient indexing is crucial for performance. Avoid unnecessary indexes as they can degrade write performance.</p><h4>Partitioning</h4><p>In the realm of real-time writes, both types of partitioning (Horizontal and Vertical) need to be carefully considered:</p><ul><li><strong>Horizontal Partitioning</strong>: Generally favored in real-time scenarios due to its scalability benefits. It is essential to ensure that the partition key is chosen to evenly distribute the write load.</li></ul><pre>-- Example of horizontal partitioning by user ID <br>CREATE TABLE user_data (<br>  user_id INT NOT NULL,<br>  data JSONB,<br>  PRIMARY KEY (user_id) <br>) <br>PARTITION BY RANGE (user_id);</pre><ul><li><strong>Vertical Partitioning</strong>: This can be beneficial when certain columns are updated more frequently than others. For instance, if a ‘last_updated’ timestamp column is frequently modified, keeping it separate from the rest of the user data can optimize write operations.</li></ul><pre>-- Example of vertical partitioning where &#39;data&#39; is infrequently updated <br>CREATE TABLE user_static (     <br>  user_id INT NOT NULL,     <br>  static_data JSONB,     <br>  PRIMARY KEY (user_id) ); <br> <br>CREATE TABLE user_dynamic (     <br>  user_id INT NOT NULL,     <br>  last_updated TIMESTAMP NOT NULL,     <br>  FOREIGN KEY (user_id) REFERENCES user_static(user_id) );</pre><p>Both partitioning strategies can be effective for real-time writes, but they require strategic planning and a deep understanding of the data access patterns to ensure they enhance rather than hinder performance. It’s a delicate balance: optimizing partitions for write operations without compromising the ability to read and query the data efficiently.</p><h4>Primary Key Impact on Upsert Strategies</h4><ul><li><strong>On Conflict Do Update</strong>: This strategy, used in databases like PostgreSQL, allows the database to perform an update when a proposed record conflicts with an existing one on a unique key (often the primary key). The existence of a primary key ensures that each record is unique and can be efficiently located and updated. However, this also means that every upsert operation involves an index lookup, potentially followed by a row update which can be I/O intensive. This can be beneficial when changes to existing records are frequent and the cost of maintaining data consistency is prioritized over the overhead of write operations.</li></ul><pre>-- Example of ON CONFLICT DO UPDATE in PostgreSQL <br>INSERT INTO table_name (id, column_a, column_b) <br>VALUES (1, &#39;A&#39;, &#39;B&#39;) <br>ON CONFLICT (id) DO UPDATE SET column_a = EXCLUDED.column_a, column_b = EXCLUDED.column_b;</pre><ul><li><strong>On Conflict Do Nothing</strong>: Alternatively, “ON CONFLICT DO NOTHING” avoids the update and simply ignores the write operation if it violates a unique constraint. This approach can be advantageous when it’s acceptable to skip the update of existing data, as it avoids the additional overhead of the update operation. This can lead to a reduction in I/O and CPU usage, which is beneficial in high-throughput environments where the cost of checking for conflicts outweighs the need for updating records.</li></ul><pre>-- Example of ON CONFLICT DO NOTHING in PostgreSQL <br>INSERT INTO table_name (id, column_a, column_b) <br>VALUES (1, &#39;A&#39;, &#39;B&#39;) ON CONFLICT (id) DO NOTHING;</pre><p>The decision to use “DO UPDATE” or “DO NOTHING” is often based on the specific requirements of the data model and the expected data access patterns. For instance, if a table serves as an event log where each event is unique and updates are not required, “DO NOTHING” would be appropriate. Conversely, for a table representing the latest state of entities that need to be frequently updated, “DO UPDATE” would be the correct choice.</p><h4>Unlogged Tables and Their Equivalents</h4><p>In the realm of database configurations for real-time writes, one often overlooked but highly impactful setting is the use of unlogged tables, especially in PostgreSQL. These tables can significantly increase write performance but come with trade-offs that need to be carefully considered.</p><p><strong>Unlogged Tables in PostgreSQL</strong></p><p>Unlogged tables are a feature specific to PostgreSQL that does not write to the write-ahead logging (WAL), which is used for crash recovery and data replication. Because they bypass WAL, unlogged tables offer improved write performance, which can be especially beneficial in scenarios where data persistence is not a critical concern, such as with temporary data or caches.</p><p><strong>Benefits for Write Throughput:</strong></p><ul><li><strong>Increased Speed</strong>: Without WAL I/O, unlogged tables reduce disk write overhead, resulting in faster data insertion rates.</li><li><strong>Reduced I/O Load</strong>: Systems that are I/O bound can benefit significantly from unlogged tables, as the reduction in disk activity can alleviate bottlenecks.</li></ul><p>Example Code for Creating Unlogged Tables in PostgreSQL:</p><pre>CREATE UNLOGGED TABLE example_table (<br>    id SERIAL PRIMARY KEY,<br>    data TEXT<br>);</pre><p>This SQL command creates an unlogged table named example_table with an auto-incrementing primary key and a text column for data.</p><p><strong>Trade-offs:</strong></p><ul><li><strong>No Crash Safety</strong>: Unlogged tables are not crash-safe. In the event of a crash, data in unlogged tables will be truncated upon recovery.</li><li><strong>No Replication</strong>: Changes to unlogged tables are not replicated to standby servers, making them unsuitable for environments where replication is critical.</li></ul><p><strong>Equivalents in Other Databases:</strong></p><ul><li><strong>MySQL’s HEAP Tables</strong>: Similar to PostgreSQL’s unlogged tables, HEAP tables in MySQL are held in memory and are not written to disk, providing faster access but at the risk of data loss in case of a server crash.</li><li><strong>SQL Server’s Memory-Optimized Tables</strong>: These tables are designed for high performance and can be durable or non-durable, where the non-durable option resembles the behavior of unlogged tables with no data written to disk.</li></ul><p>Example Code for Creating Memory-Optimized Tables in SQL Server:</p><pre>CREATE TABLE dbo.example_table<br>(<br>    id INT PRIMARY KEY NONCLUSTERED,<br>    data NVARCHAR(MAX)<br>) WITH (MEMORY_OPTIMIZED = ON, DURABILITY = SCHEMA_ONLY);</pre><p>In this example, DURABILITY = SCHEMA_ONLY makes the table&#39;s schema durable, but the data is non-durable, similar to an unlogged table.</p><p>In conclusion, leveraging unlogged tables in PostgreSQL and similar concepts in other databases can provide a significant boost to write throughput for real-time data pipelines. However, it is essential to use them judiciously, considering the durability requirements and the nature of the data being handled.</p><h3>Conclusion</h3><p>By carefully tuning each layer — database, pipeline, and network, real-time data pipelines can achieve the high throughput and low latency required for demanding real-time applications. It is a delicate balance that must be maintained to ensure that the system can handle the data load efficiently and reliably.</p><blockquote>Don’t forget to hit the Clap and Follow buttons to help me write more articles like this.</blockquote><blockquote><em>Disclaimer:</em></blockquote><ol><li>The opinions expressed here are strictly my own, basis my current work.</li><li>The logo of different tools/technologies used, if any, in the architecture diagram is the copyright of respective software companies/foundations.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f3a4e8254bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Stream Joins in Real-Time Data Processing: A Comprehensive Guide]]></title>
            <link>https://medium.com/@vijay_31043/mastering-stream-joins-in-real-time-data-processing-a-comprehensive-guide-772a986913bc?source=rss-9d8d4e5a31d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/772a986913bc</guid>
            <category><![CDATA[realtime]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[apache-beam]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[streaming]]></category>
            <dc:creator><![CDATA[Vijay Shekhawat]]></dc:creator>
            <pubDate>Sun, 29 Oct 2023 15:30:18 GMT</pubDate>
            <atom:updated>2024-05-29T04:08:19.746Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*PSPHmKnGDVPpFFs7lRaj-Q.jpeg" /></figure><p>Stream joins are pivotal in real-time data processing for instantaneous data enrichment and connection. Nevertheless, they can pose substantial challenges, especially when it comes to handling out-of-order events and ensuring the availability of reference data. This extensive guide dives deep into stream-stream and stream-table joins, providing actionable solutions, best practices, and real-world examples to navigate through these complexities.</p><h3>Types of Stream Joins</h3><p>In the realm of real-time data processing, stream joins play a crucial role in correlating different data flows to derive meaningful insights. While there are various types of stream joins, this guide will focus on two predominant types: Stream-Stream joins (Windowed) and Stream-Table joins (Enrichment).</p><ol><li>Stream-Stream join (Windowed): This type of join is essential when you need to correlate events from two different streams within a specified time window. It’s particularly useful for scenarios where both streams have a temporal aspect, and you want to combine related events based on their timestamps.</li><li>Stream-Table join (Enrichment): This join type is crucial for enriching data in a stream with additional information stored in a static table or dataset. It’s a common scenario in real-time data processing where you have a stream of events that need to be augmented with reference data for comprehensive analysis.</li></ol><h3>Stream-Stream Join</h3><h4>The Challenge: Taming Data Disorder — Managing Out-of-Order Events</h4><p>In the fast-paced world of real-time data processing, events may only sometimes arrive in the expected order, leading to potential inaccuracies.</p><h4>The Solution: Windowing, Watermarks, and Triggers</h4><p>Addressing this issue requires a strategic approach to windowing, as well as the implementation of watermarks and triggers, all of which are crucial for managing event time and ensuring data accuracy.</p><h4>Real-World Apache Beam Example</h4><p>Let’s consider a scenario where you need to join click and impression events for real-time click-through rate calculation:</p><pre>PCollection&lt;KV&lt;String, Click&gt;&gt; clicks = ...;<br>PCollection&lt;KV&lt;String, Impression&gt;&gt; impressions = ...;<br>PCollection&lt;KV&lt;String, KV&lt;Click, Impression&gt;&gt;&gt; joined =<br>    PCollectionTuple.of(&quot;clicks&quot;, clicks)<br>                    .and(&quot;impressions&quot;, impressions)<br>                    .apply(Join.innerJoin());<br><br>joined.apply(Window.&lt;KV&lt;String, KV&lt;Click, Impression&gt;&gt;&gt;into(FixedWindows.of(Duration.standardMinutes(10)))<br>             .withTimestampCombiner(TimestampCombiner.EARLIEST)<br>             .withAllowedLateness(Duration.standardHours(2))<br>             .triggering(AfterWatermark.pastEndOfWindow()<br>                                     .withEarlyFirings(AfterProcessingTime.pastFirstElementInPane()<br>                                                                         .plusDelayOf(Duration.standardMinutes(1)))<br>                                     .withLateFirings(AfterPane.elementCountAtLeast(1)))<br>             .discardingFiredPanes());</pre><p>In this Apache Beam example, clicks and impressions are joined and windowed into 10-minute fixed windows. The system accommodates events that arrive up to two hours late, and a mix of early and late firing triggers ensures timely results while still accounting for late-arriving data.</p><h4>Best Practices for Stream-Stream Join</h4><ul><li>Fine-Tune Window Sizes: Adapt the window size based on your data’s specific characteristics.</li><li>Implement Watermarks and Triggers: Employ these tools for accurate event time management.</li><li>Ensure Scalability: Prepare your infrastructure to scale and handle peak data volumes horizontally.</li></ul><h3>Stream-Table Join</h3><h4>The Challenge: Ensuring Reference Data is At Hand-Balancing Availability and Performance</h4><p>Maintaining access to up-to-date reference data is imperative, but it should not compromise the performance of your production database.</p><h4>The Solution: In-memory and External Data Stores</h4><p>Opting for in-memory storage solutions or external data stores can help strike the right balance between data availability and system performance.</p><h4>A Spark Example: In-memory</h4><p>Let’s say you are working with Spark, and you need to join a small Customers DataFrame with a large Orders stream:</p><pre>val customersDF = ... // Small DataFrame<br>val ordersStream = ... // Large Stream<br>val broadcastCustomers = spark.sparkContext.broadcast(customersDF)<br>ordersStream.join(broadcastCustomers.value, &quot;customer_id&quot;)</pre><p>In this example, the Customers DataFrame is broadcasted to all nodes, ensuring that the join can be performed efficiently without shuffling the large Orders stream across the network.</p><h4>Real-World Example with Redis: External data store</h4><p>Imagine enriching e-commerce transactions in real-time with product information:</p><pre>import redis<br>r = redis.Redis(host=&#39;localhost&#39;, port=6379, db=0)<br>def enrich_transaction(transaction):<br>    product_id = transaction[&#39;product_id&#39;]<br>    product_info = r.hgetall(f&#39;product:{product_id}&#39;)<br>    transaction.update(product_info)<br>    return transaction</pre><p>In this Python example, product information is stored in a Redis hash. Transactions are enriched in real-time by fetching the necessary product data from Redis, showcasing a practical application of using external data stores for stream-table joins.</p><h4>Best Practices for Stream-Table Join</h4><ul><li>Adopt In-Memory Storage: Utilize memory storage for frequently accessed reference data to reduce access times.</li><li>Utilize External Data Stores: External data stores like Redis are excellent for high-speed data retrieval if the lookup table is too big to fit in memory.</li><li>Protect Your Production Database: Although tempting avoid direct reads from your production database to maintain overall system performance and prevent potential bottlenecks.</li></ul><h3>In Conclusion</h3><p>Mastering the intricacies of stream joins is a game changer in real-time data processing, transforming complex data flows into streamlined and potent operations. By understanding stream-stream and stream-table joins, and adhering to best practices, you ensure that your real-time data is not just connected and enriched, but also primed for delivering valuable insights precisely when needed.</p><blockquote>Don’t forget to hit the Clap and Follow buttons to help me write more articles like this.</blockquote><blockquote><em>Disclaimer:</em></blockquote><ol><li>The opinions expressed here are strictly my own, basis my current work.</li><li>The logo of different tools/technologies used, if any, in the architecture diagram is the copyright of respective software companies/foundations.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=772a986913bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>