<?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[apache-hudi-blogs - Medium]]></title>
        <description><![CDATA[Repost of blogs from hudi.apache.org on medium - Medium]]></description>
        <link>https://medium.com/apache-hudi-blogs?source=rss----464bbeff5499---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>apache-hudi-blogs - Medium</title>
            <link>https://medium.com/apache-hudi-blogs?source=rss----464bbeff5499---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 17:41:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/apache-hudi-blogs" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building Analytical Apps on the Lakehouse using Apache Hudi, Daft & Streamlit]]></title>
            <link>https://medium.com/apache-hudi-blogs/building-analytical-apps-on-the-lakehouse-using-apache-hudi-daft-streamlit-3224766fe58a?source=rss----464bbeff5499---4</link>
            <guid isPermaLink="false">https://medium.com/p/3224766fe58a</guid>
            <category><![CDATA[streamlit]]></category>
            <category><![CDATA[apache-hudi]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-lakehouse]]></category>
            <dc:creator><![CDATA[Dipankar Mazumdar]]></dc:creator>
            <pubDate>Fri, 10 May 2024 14:33:46 GMT</pubDate>
            <atom:updated>2024-05-10T14:33:46.312Z</atom:updated>
            <content:encoded><![CDATA[<p>Building user-facing analytical apps and dashboards is critical for organizations that want to make decisions actionable. While traditional BI tools have been predominantly used for such tasks, they often lack integration with the Python ecosystem and require a dedicated effort and specialized skill set. Also, the need to quickly prototype and build data apps is becoming essential at different stages of the analytics lifecycle (not just last mile), including exploratory data analysis, ML model evaluation, data pipeline monitoring, and LLM-based apps.</p><p>To address these challenges, low-code tools like <a href="https://streamlit.io/">Streamlit</a>, which serve as a thin wrapper around the Python ecosystem, allow you to bring APIs, models, and business logic to life. Streamlit enables easy data consumption from a variety of sources such as databases, APIs, and file systems, allowing for easy integration into applications. In this blog, our focus would be on building a data app using data directly from an open lakehouse platform.</p><h3>Open Lakehouse Platform</h3><p>Lakehouse architectures are gaining traction as more organizations transition to using open table formats for transactions on data lakes. Open lakehouse platforms such as <a href="https://hudi.apache.org/docs/next/hudi_stack">Apache Hudi</a> allows organizations to build <em>flexible</em> architectures, enabling them to choose the best compute engine for their workloads without locking data into proprietary storage formats.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DrnHB2HdP5h1bBDq" /><figcaption>Fig 1: Apache Hudi’s Open Lakehouse Platform. Highlighted component in <strong><em>orange</em></strong> is the table format</figcaption></figure><p>At its core, a lakehouse integrates the transactional capabilities of traditional databases (such as OLAP) with the scalability and cost-efficiency of data lakes. Data files are stored in accessible, open table formats in cloud-based object stores like Amazon S3, Azure Blob, or Google Cloud Storage, with metadata managed by the ‘table format’ component. This modular approach creates a future-proof architecture where new compute engines can be added to the stack as needed. For example, you might use Hudi with <a href="https://flink.apache.org/">Apache Flink</a> today to build low-latency pipelines, and later add Presto or Trino or anything else for ad-hoc analytics.</p><h3>Hudi + Daft Integration</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*--9L4h-KwxCmKLSt" /><figcaption>Fig 2: Apache Hudi-Daft Read workflow</figcaption></figure><p>One important thing to note is that lakehouse platforms today are predominantly distributed to effectively handle large-scale, complex, and varied data workloads. This means you may need to spin up clusters with Spark, JVM, and other necessary configurations to interact with the data stored in underlying storage systems. However, the need to use data directly from lakehouses in a single node architecture is becoming critical, especially for doing ad hoc analytics and building analytical apps, which accelerates the time-to-insight process.</p><p>For such use cases, you don’t always need to go through the cumbersome process of setting up the infrastructure. This is where Python-based dataframes such as <a href="https://www.getdaft.io/">Daft</a> come into the picture. Daft is a distributed query engine designed for ETL, analytics, and ML/AI at scale. It offers a familiar Python DataFrame API that aims to surpass Spark in both performance and ease of use. Daft operates locally with a lightweight, multithreaded backend. So, works well on your local development environment, but when the local machine’s capacity is exceeded, it can transition to run out-of-core on a distributed cluster.</p><p>The recent release of Daft introduces support for reading Apache Hudi <a href="https://hudi.apache.org/docs/next/table_types#copy-on-write-table">Copy-on-Write</a> (CoW) tables. This means, users can now consume Hudi tables directly from an object store using pure Python. Daft’s query optimizer also enables partition pruning and file pruning (via file-level statistics) to skip non-relevant data files to return faster results.</p><h3>Hands-on Dashboard</h3><p>The goal of this hands-on example is to show how you can use Daft as the query engine to read Hudi tables, and then build a user-facing analytical application in Python. The specific dataset and use case are not the main focus of this blog. Instead, the goal is to demonstrate the practical workings of the Hudi-Daft integration.</p><p>Before we start working on the code, let’s outline a minimalistic lakehouse architecture as the foundation for our dashboard. This will also introduce the tools we are using for this exercise. All the tools used here are open source. Amazon S3 operates on a pay-as-you-go model with costs based on storage and API usage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TltZPOdK12Pz7UNikiZ3ng.png" /><figcaption>Fig 3: Lakehouse architecture for the exercise</figcaption></figure><p><strong>Architecture Stack:</strong></p><ul><li>Data Lake Storage — Amazon S3</li><li>File Format — CSV, Parquet</li><li>Table Format — Apache Hudi</li><li>Compute Engine — Apache Spark (writes), Daft (reads)</li><li>User Interface — Streamlit</li></ul><p><strong>Libraries to install: </strong>Streamlit, Plotly, Daft, Pandas, boto3</p><p>We will use Amazon S3 as the data lake storage, where all data files will be securely stored after the ingestion job completes. The source data will be a CSV file, and we will write the records as Parquet when creating the lakehouse table. Apache Hudi will be used as the table format and Hudi’s lakehouse platform including table services (clustering, indexing, file sizing, etc.) will be utilized for keeping the storage layout optimized.</p><p>For our compute needs, Apache Spark will handle the write tasks during the ingestion phase, while Daft will be the primary engine for reads and analytics, offering optimized performance for these operations. In the end, we will use Streamlit to create an interactive dashboard using the data directly from the lakehouse.</p><p>If you want to follow this example, clone the <a href="https://github.com/dipankarmazumdar/DaftHudi">GitHub repo</a>. Let’s get started!</p><h4>Create Hudi Table &amp; Ingest Records</h4><p>The first step is to create the Hudi table using Spark. Below are all the configurations required to use PySpark with Apache Hudi. This is an <em>optional</em> step if you already have a Hudi table in the data lake.</p><p>** Note that in a real-world setting, if you are a data analyst/scientist working on the analytics layer, these tasks will typically be handled by the data engineering team.</p><pre>from typing import *<br><br>from pyspark import Row<br>from pyspark.sql import SparkSession<br>from pyspark.sql.functions import col<br><br># Initialize Spark session<br>spark = SparkSession.builder \<br>    .appName(&quot;Hudi Table&quot;) \<br>    .config(&quot;spark.serializer&quot;, &quot;org.apache.spark.serializer.KryoSerializer&quot;) \<br>    .config(&quot;spark.jars.packages&quot;, &quot;org.apache.hudi:hudi-spark3.4-bundle_2.12:0.14.0,org.apache.hadoop:hadoop-aws:3.2.4,com.amazonaws:aws-java-sdk:1.12.262&quot;) \<br>    .config(&quot;spark.sql.catalog.spark_catalog&quot;, &quot;org.apache.spark.sql.hudi.catalog.HoodieCatalog&quot;) \<br>    .config(&quot;spark.sql.extensions&quot;, &quot;org.apache.spark.sql.hudi.HoodieSparkSessionExtension&quot;) \<br>    .config(&quot;spark.hadoop.fs.s3a.aws.credentials.provider&quot;, &quot;com.amazonaws.auth.profile.ProfileCredentialsProvider&quot;) \<br>    .config(&quot;spark.hadoop.fs.s3a.path.style.access&quot;, &quot;true&quot;) \<br>    .config(&quot;spark.hadoop.fs.s3a.impl&quot;, &quot;org.apache.hadoop.fs.s3a.S3AFileSystem&quot;) \<br>    .getOrCreate()<br><br>print(&quot;Spark Running&quot;)<br><br>s3_path = &quot;s3a://my-bucket/sandbox/daft_hudi/&quot;<br><br># Access SparkContext<br>sc = spark.sparkContext</pre><p>Now, let’s ingest the records.</p><pre># Read Source Data for Ingestion<br>TABLE_NAME = &#39;aldi_data&#39;<br>INPUT = &#39;s3a://my-bucket/input/retail/All_Data_Aldi.csv&#39;<br>df_cow = spark.read.csv(INPUT, header=True, inferSchema=True)<br><br># Minor Transformation<br>df_cow = df_cow.withColumnRenamed(&#39;prices_(¬£)&#39;, &#39;prices&#39;)<br>df_cow = df_cow.withColumnRenamed(&#39;prices_unit_(¬£)&#39;, &#39;prices_unit&#39;)<br><br># Write the Records <br>PATH = &#39;s3a://my-bucket/sandbox/daft_hudi/&#39;<br><br>hudi_options = {<br>        &#39;hoodie.table.name&#39;: TABLE_NAME,<br>        &#39;hoodie.table.keygenerator.class&#39; : &quot;org.apache.hudi.keygen.SimpleKeyGenerator&quot;,<br>        &#39;hoodie.datasource.write.hive_style_partitioning&#39; : &quot;false&quot;,<br>  &#39;hoodie.datasource.write.partitionpath.field&#39; : &quot;category&quot; <br>    }<br><br>spark.sql(&quot;DROP TABLE IF EXISTS &quot; + TABLE_NAME)<br>df_cow.write.format(&quot;hudi&quot;).mode(&quot;overwrite&quot;).options(**hudi_options).mode(&quot;overwrite&quot;).save(PATH)</pre><p>This will create a Hudi table named aldi_data in the S3 data lake and will be partitioned by the category field. Here is how the table looks like in the data lake.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rlprQtlKBqsuPxyy-baO6Q.png" /><figcaption>Fig 4: Hudi Table partitioned by <strong>Category </strong>in S3 data lake</figcaption></figure><h4>Read Hudi Table using Daft</h4><p>Now that we have the records written to a Hudi table, we should be good to start reading the data using Daft to build our downstream analytical app. Like mentioned before, Daft provides high performance I/O reads from cloud data lakes.</p><p>Here is a snippet that shows how to read Hudi table using Daft’s query engine.</p><pre> df = daft.read_hudi(&quot;s3://my-bucket/sandbox/daft_hudi&quot;)<br> df_analysis = df.select(&quot;supermarket&quot;, &quot;prices&quot;, &quot;names&quot;, &quot;date&quot;, &quot;own_brand&quot;, &quot;category&quot;)<br> df_analysis.collect()</pre><p>Let’s understand the methods from the Daft API.</p><ul><li>read_hudi() — used to read the Hudi table. You can specify the table location URI here</li><li>select() — this creates a new dataframe from the provided expression (similar to SQL SELECT)</li><li>collect() — this method executes the entire dataframe and materializes the results</li></ul><p>We begin by reading the Hudi table from the S3 bucket where the records were previously ingested. Next, we use the select() method to choose the fields necessary for our analysis. Since Daft dataframes are <a href="https://en.wikipedia.org/wiki/Lazy_evaluation">lazy</a> — meaning they do not evaluate until explicitly instructed — results are not immediately displayed after these operations.</p><p>In this example, we just use Daft to defer the tasks of reading the data and selecting columns. Practically, this approach of laziness allows Daft to optimize your queries more effectively before they are executed. Finally, we can tell Daft to execute our DataFrame and cache the results by using df_analysis.collect(). The important thing to note is that any subsequent operations on df_analysis will avoid recomputations and simply utilize this materialized result.</p><p>All of these query plans can be examined by calling the explain() method. To see the plan after Daft applies its optimizations, we can use explain(show_all=True). Here is what we have for our case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SGRZU4mZS-duqqLO" /><figcaption>Fig 5: Logical &amp; Physical Plans in Daft</figcaption></figure><p>We can see the Unoptimized, Optimized and Physical Plans for our dataframe. The Optimized Logical Plan (highlighted) presents the projection pushdown based on our query. When these query engine optimizations are combined with Hudi’s storage optimization capabilities (such as <a href="https://hudi.apache.org/docs/next/clustering/">clustering</a>, <a href="https://hudi.apache.org/docs/next/indexing">indexing</a>, <a href="https://hudi.apache.org/docs/next/file_sizing">file sizing</a>, etc.), they can deliver excellent performance for handling large datasets.</p><h4>Build the Streamlit Dashboard</h4><p>As of now, we have the Hudi table stored as a Daft dataframe df_analysis. To build the dashboard, we will use a combination of Python-based libraries, including Pandas and Plotly Charts, alongside Daft. While visualization libraries today predominantly work with Pandas — hence its use for this specific purpose — we will employ Daft in scenarios that benefit from its performance optimization capabilities.</p><p>For example, some charts in the dashboard require aggregated values (such as <em>Product Variety per Category</em>). In these instances, rather than performing aggregations in Pandas, we utilize Daft’s capabilities to aggregate the data first, then pass the results to the visualization library. This method proves especially effective when handling very large datasets, which are typical in lakehouse workloads. Here is a snippet that shows the same.</p><pre>distinct_names_per_category = df_analysis.select(&quot;category&quot;, &quot;names&quot;).distinct()<br>category_diversity_daft = distinct_names_per_category.groupby(&quot;category&quot;).agg(<br>        daft.col(&#39;names&#39;).count()<br>).to_pandas()<br>category_diversity_daft.columns = [&#39;Category&#39;, &#39;Number of Unique Products&#39;]</pre><p>We first select distinct names and categories from the dataframe, then group by category, and count the unique product names in each category. The results are then converted to a Pandas dataframe for use with the visualization chart.</p><p>From the dashboard’s design perspective, we will have four charts that answer some business questions and a filter to analyze data by category.</p><pre># Charts 1 &amp; 2<br>col1, col2 = st.columns(2, gap=&quot;large&quot;)<br>with col1:<br>    st.subheader(&#39;Price Distribution by Category&#39;)<br>    fig1 = px.box(df_filtered, x=&#39;category&#39;, y=&#39;prices&#39;, title=&#39;Price Distribution by Category&#39;, color_discrete_sequence=modern_mint)<br>    st.plotly_chart(fig1, use_container_width=True)<br><br>with col2:<br>    st.subheader(&#39;Product Variety per Category&#39;)<br>    filtered_category_diversity = category_diversity_pandas[category_diversity_pandas[&#39;Category&#39;].isin(df_filtered[&#39;category&#39;].unique())]<br>    fig_category_diversity = px.bar(filtered_category_diversity, x=&#39;Category&#39;, y=&#39;Number of Unique Products&#39;, title=&#39;Product Variety per Category&#39;, color_discrete_sequence=modern_mint)<br>    st.plotly_chart(fig_category_diversity, use_container_width=True)<br><br># Charts 3 &amp; 4<br>col3, col4 = st.columns(2, gap=&quot;large&quot;)<br>with col3:<br>    st.subheader(&#39;Share of Own Brand Products&#39;)<br>    own_brand_count = df_filtered[&#39;own_brand&#39;].value_counts(normalize=True).reset_index(name=&#39;proportion&#39;)<br>    fig4 = px.pie(own_brand_count, values=&#39;proportion&#39;, names=&#39;own_brand&#39;, title=&#39;Share of Own Brand Products&#39;, labels={&#39;own_brand&#39;: &#39;Brand Type&#39;}, color_discrete_sequence=modern_mint)<br>    st.plotly_chart(fig4, use_container_width=True)<br><br>with col4:<br>    st.subheader(&#39;Average Price by Brand Type and Category&#39;)<br>    # Group by both &#39;own_brand&#39; and &#39;category&#39; for a more detailed breakdown<br>    brand_category_price_comparison = df_filtered.groupby([&#39;own_brand&#39;, &#39;category&#39;])[&#39;prices&#39;].mean().unstack().fillna(0)<br>    fig5 = px.bar(brand_category_price_comparison, title=&#39;Average Price by Brand Type and Category&#39;, color_discrete_sequence=modern_mint, labels={&#39;value&#39;:&#39;Average Price&#39;, &#39;variable&#39;:&#39;Category&#39;})<br>    fig5.update_layout(barmode=&#39;stack&#39;)<br>    st.plotly_chart(fig5, use_container_width=True)</pre><p>Putting all of these together, here is the final application ready for analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*z8hrwlHtfyQqlTzg" /><figcaption>Fig 6: Analytics Dashboard built with Apache Hudi Table &amp; Daft</figcaption></figure><p>The dashboard also allows filtering the dataset by category and renders the relevant visualizations as per the filter. This allows users for a more granular analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*LgYK-ueEICvXLgGjQr9Pag.gif" /><figcaption>Fig 7: Dashboard in action</figcaption></figure><h3>Conclusion &amp; Future Work</h3><p>Building the dashboard directly on an open lakehouse brings several advantages.</p><ul><li><strong>Faster Insights</strong>: Direct access to the lakehouse (gold layer in a medallion architecture) accelerates the time-to-insight process, ensuring that analyses are timely and relevant.</li><li><strong>Reduced data redundancy:</strong> Traditional reporting often involves moving data across multiple systems (lakes to warehouses for BI), which can result in numerous copies and versions of data. This is avoided with an open data architecture that enables direct access to data.</li><li><strong>Cost Efficiency:</strong> Using an open lakehouse architecture reduces costs by eliminating the need for complex ETL pipelines and frequent data extracts, while cloud storages like Amazon S3 allows scaling as required.</li></ul><p>In this blog, we presented how quickly and seamlessly we can build user-facing analytical applications on open lakehouse platforms such as Apache Hudi, using high-performance query engines like Daft. This marks our first experience dealing with Hudi tables using pure Python, without the need to set up Spark in a Java-based environment.</p><p>The integration of Daft, which provides a familiar Python API while delivering superior performance, opens up interesting avenues for running analytical workloads on Hudi without the need for distributed computing like Spark. Some of the items we are working on for the immediate future are:</p><ul><li>Support <a href="https://github.com/Eventual-Inc/Daft/issues/2153">incremental query</a> for Copy-on-Write tables</li><li>Read support for <a href="https://github.com/Eventual-Inc/Daft/issues/2152">v1.0</a> table format</li><li>Read support (snapshot) for <a href="https://github.com/Eventual-Inc/Daft/issues/2154">Merge-on-Read</a> tables</li><li>Hudi <a href="https://github.com/Eventual-Inc/Daft/issues/2155">Write</a> support</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3224766fe58a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/apache-hudi-blogs/building-analytical-apps-on-the-lakehouse-using-apache-hudi-daft-streamlit-3224766fe58a">Building Analytical Apps on the Lakehouse using Apache Hudi, Daft &amp; Streamlit</a> was originally published in <a href="https://medium.com/apache-hudi-blogs">apache-hudi-blogs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Paimon v.s. Hudi write efficiency]]></title>
            <link>https://medium.com/apache-hudi-blogs/paimon-v-s-hudi-write-efficiency-fccb1f745ab5?source=rss----464bbeff5499---4</link>
            <guid isPermaLink="false">https://medium.com/p/fccb1f745ab5</guid>
            <category><![CDATA[apache-hudi]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-lakehouse]]></category>
            <category><![CDATA[benchmarking]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Apache Hudi]]></dc:creator>
            <pubDate>Mon, 25 Mar 2024 22:04:15 GMT</pubDate>
            <atom:updated>2024-03-25T22:04:14.882Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Translated from the o<a href="https://mp.weixin.qq.com/s/HPRrFj4POsztKhRqF5mxwA">riginal post (Chinese)</a> by Anryg(安瑞哥)</blockquote><p>The reason why I want to make such a comparison is that last week I saw an article posted on the Flink official account, which included a eye-catching comparison of the write efficiency of two data lake products, Paimon and Hudi.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/0*BXo6jm3fi2MduKQF" /><figcaption><em>Quoted from Flink official public account</em></figcaption></figure><p>It immediately attracted my attention. Judging from this comparison chart, Hudi was defeated in all aspects and behaved like an “Adou who cannot be helped.”</p><p>Just when I was curious about what kind of scenario this test conclusion was based on, I browsed through the full text and found that it didn’t seem to tell me the specific test details, but directly announced to you: “Well… this is our conclusion, it is just so awesome.”</p><p>But you know, there is no specifics about the scenarios (what is the data source? What is the table schema? How is the resource configuration during writing? How is the parallelism set? etc.), and test results without any process description, I definitely don’t believe it.</p><p>So on impulse, I posted my doubts about the test conclusion on WeChat, and soon attracted the attention of Alibaba Cloud technical experts, who asked me why I doubted their test results, then I walked through my views and doubts.</p><p>But it’s useless to just suspect, in order to confirm my above doubts and show respect for other people’s test results.</p><p>I decided to test it myself and expose the whole process to you.</p><p><em>(This test is based on Flink1.15, Hadoop3.1, Paimon0.6, Hudi0.13)</em></p><h3>0. Preparation before test</h3><p>Let’s talk about the data source first:</p><p>Since we are doing a write test, we must first find out where the data source comes from, and the selection of this data source is very important in my opinion.</p><p>For example, its reading efficiency must not become the bottleneck of the entire data processing process. In other words, <strong>the flow rate of the upstream data source must be greater than the downstream data writing speed</strong> , so that the writing efficiency can be truly reflected. Otherwise, this test is bullshit.</p><p>In order to ensure this, I poured all the data from a large file into the Kafka topic in advance, and then used Flink to consume this topic (using its default speed). In this way, there is no data source reading. Take the bottleneck problem.</p><p>As for why? <strong>The sequential reading efficiency of the disk (reading Kafka) must be much greater than the writing efficiency of indexing based on specific fields</strong> (writing Paimon or Hudi tables).</p><p>As for the data content, it is still my previous online behavior log. It has 9 fields, the file size is: 3.1G, and the number of data lines is: 24633164.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/0*w6CiP7-BojomvzkH" /></figure><h3>1. Flink writes Paimon: code preparation</h3><p>For the Paimon table, its table schema is as follows:</p><pre>CREATE TABLE if not exists data_from_flink2paimon01 (<br>`client_ip` STRING ,<br>domain STRING,<br>`time` STRING,<br>target_ip STRING,<br>rcode STRING,<br>query_type STRING,<br>authority_record STRING,<br>add_msg STRING,<br>dns_ip STRING,<br>PRIMARY KEY(client_ip,domain,`time`,target_ip) NOT ENFORCED<br>)</pre><p>In order to facilitate testing, I use String type for everything (don’t learn from me).</p><p>The code for Flink to read Kafka and write Paimon table is as follows:</p><pre>package com.anryg.bigdata.paimon;<br><br>import com.alibaba.fastjson.JSON;<br>import com.alibaba.fastjson.JSONObject;<br>import org.apache.flink.api.common.eventtime.WatermarkStrategy;<br>import org.apache.flink.api.common.functions.FilterFunction;<br>import org.apache.flink.api.common.functions.MapFunction;<br>import org.apache.flink.api.common.serialization.SimpleStringSchema;<br>import org.apache.flink.api.common.typeinfo.Types;<br>import org.apache.flink.connector.kafka.source.KafkaSource;<br>import org.apache.flink.connector.kafka.source.KafkaSourceBuilder;<br>import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer;<br>import org.apache.flink.streaming.api.CheckpointingMode;<br>import org.apache.flink.streaming.api.datastream.DataStreamSource;<br>import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;<br>import org.apache.flink.streaming.api.environment.CheckpointConfig;<br>import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;<br>import org.apache.flink.table.api.Table;<br>import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;<br>import org.apache.flink.types.Row;<br>/**<br> * @DESC: 通过 Flink DS 跟 SQL 混合模式读取 kafka 数据写入 Paimon 数据湖<br> * @Auther: Anryg<br> * @Date: 2023/12/19 20:36<br> */<br>public class FlinkFromKafka2Paimon {<br>    public static void main(String[] args) {<br>        //获取流任务的环境变量<br>        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment()<br>                .enableCheckpointing(10000, CheckpointingMode.EXACTLY_ONCE); //打开checkpoint功能<br>        env.getCheckpointConfig().setCheckpointStorage(&quot;hdfs://192.168.211.106:8020/tmp/flink_checkpoint/FlinkDSFromKafka2Paimon01&quot;); //设置checkpoint的hdfs目录<br>        env.getCheckpointConfig().setExternalizedCheckpointCleanup(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION); //设置checkpoint记录的保留策略<br>        /**创建flink table环境对象*/<br>        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);<br>        /**添加 Kafka 数据源*/<br>        KafkaSourceBuilder&lt;String&gt; kafkaSourceBuilder = KafkaSource.&lt;String&gt;builder() //一定注意这里的&lt;String&gt;类型指定，否则后面的new SimpleStringSchema()会报错<br>                                                                    .setBootstrapServers(&quot;192.168.211.107:6667&quot;)<br>                                                                    .setTopics(&quot;test&quot;)<br>                                                                    .setGroupId(&quot;FlinkFromKafka2Paimon01&quot;)<br>                                                                    .setStartingOffsets(OffsetsInitializer.timestamp(1703474520000L)) //确认消费模式为特定时间<br>                                                                    .setValueOnlyDeserializer(new SimpleStringSchema());<br><br>        /**将数据源生成DataStream对象*/<br>        DataStreamSource&lt;String&gt; kafkaDS = env.fromSource(kafkaSourceBuilder.build(), WatermarkStrategy.noWatermarks(), &quot;kafka-data&quot;);<br>        /**将原始DS经过处理后，再添加schema*/<br>        SingleOutputStreamOperator&lt;Row&gt; targetDS = kafkaDS.map((MapFunction&lt;String, String[]&gt;) line -&gt; {<br>                                                            JSONObject rawJson = JSON.parseObject(line);<br>                                                            String message = rawJson.getString(&quot;message&quot;);  //获取业务数据部分<br>                                                            String[] msgArray = message.split(&quot;,&quot;);  //指定分隔符进行字段切分<br>                                                            return msgArray;<br>                                                        }).filter((FilterFunction&lt;String[]&gt;) array -&gt; {<br>                                                            if (array.length == 9) return true;<br>                                                            else return false;<br>                                                        }).map((MapFunction&lt;String[], Row&gt;) array -&gt; Row.of( array[0], array[1], array[2], array[3], array[4], array[5], array[6], array[7], array[8]))<br>                                                                .returns(<br>                                                                        Types.ROW_NAMED(<br>                                                                                new String[]{&quot;client_ip&quot;, &quot;domain&quot;, &quot;time&quot;, &quot;target_ip&quot;, &quot;rcode&quot;, &quot;query_type&quot;, &quot;authority_record&quot;, &quot;add_msg&quot;, &quot;dns_ip&quot;},<br>                                                                                Types.STRING, Types.STRING, Types.STRING, Types.STRING, Types.STRING, Types.STRING, Types.STRING, Types.STRING, Types.STRING)<br>                                                                );<br>        /**将目标DS转化成Table对象*/<br>        Table table = tableEnv.fromDataStream(targetDS);<br>        /**创建属于paimon类型的catalog*/<br>        tableEnv.executeSql(&quot;CREATE CATALOG hdfs_catalog WITH (&#39;type&#39; = &#39;paimon&#39;, &#39;warehouse&#39; = &#39;hdfs://192.168.211.106:8020/tmp/paimon&#39;)&quot;);<br>        /**使用创建的catalog*/<br>        tableEnv.executeSql(&quot;USE CATALOG hdfs_catalog&quot;);<br>        /**建paimon表*/<br>        tableEnv.executeSql(&quot;CREATE TABLE if not exists data_from_flink2paimon01 (`client_ip` STRING ,domain STRING,`time` STRING,target_ip STRING,rcode STRING,query_type STRING,authority_record STRING,add_msg STRING,dns_ip STRING,PRIMARY KEY(client_ip,domain,`time`,target_ip) NOT ENFORCED)&quot;);<br>        /**将 Kafka 数据源登记为当前catalog下的表*/<br>        tableEnv.createTemporaryView(&quot;kafka_table&quot;, table);<br>        /**将Kafka数据写入到 paimon 表中*/<br>        tableEnv.executeSql(&quot;INSERT INTO data_from_flink2paimon01 SELECT * FROM kafka_table&quot;);<br>    }<br>}</pre><p>Note that in the code, in order to accurately consume all the Kafka data I wrote in advance, I used the timestamp method to specify the offset of data consumption.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/0*SeCH2LAz_uXIYo3D" /></figure><h3>2. Flink writes Hudi: code preparation</h3><p>For the Hudi table, its table schema is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/0*TDMFYYO7jgv7kwaq" /></figure><p>The code for Flink to read Kafka and write to the Hudi table is as follows:</p><pre>package com.anryg.bigdata.hudi;<br><br>import com.alibaba.fastjson.JSON;<br>import com.alibaba.fastjson.JSONObject;<br>import org.apache.flink.api.common.eventtime.WatermarkStrategy;<br>import org.apache.flink.api.common.functions.FilterFunction;<br>import org.apache.flink.api.common.functions.MapFunction;<br>import org.apache.flink.api.common.serialization.SimpleStringSchema;<br>import org.apache.flink.connector.kafka.source.KafkaSource;<br>import org.apache.flink.connector.kafka.source.KafkaSourceBuilder;<br>import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer;<br>import org.apache.flink.streaming.api.CheckpointingMode;<br>import org.apache.flink.streaming.api.datastream.DataStream;<br>import org.apache.flink.streaming.api.datastream.DataStreamSource;<br>import org.apache.flink.streaming.api.environment.CheckpointConfig;<br>import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;<br>import org.apache.flink.table.data.GenericRowData;<br>import org.apache.flink.table.data.RowData;<br>import org.apache.flink.table.data.StringData;<br>import org.apache.hudi.configuration.FlinkOptions;<br>import org.apache.hudi.util.HoodiePipeline;<br>import java.util.HashMap;<br>import java.util.Map;<br>/**<br> * @DESC: Flink 读取 Kafka 写 Hudi 表<br> * @Auther: Anryg<br> * @Date: 2023/9/3 14:54<br> */<br>public class FlinkDSFromKafka2Hudi {<br>    public static void main(String[] args) throws Exception {<br>        //获取流任务的环境变量<br>        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment()<br>                .enableCheckpointing(Long.parseLong(args[0]), CheckpointingMode.EXACTLY_ONCE); //打开checkpoint功能<br>        //env.setRuntimeMode(RuntimeExecutionMode.BATCH)<br>        env.getCheckpointConfig().setCheckpointStorage(&quot;hdfs://192.168.211.106:8020/tmp/flink_checkpoint/FlinkDSFromKafka2Hudi01&quot;); //设置checkpoint的hdfs目录<br>        env.getCheckpointConfig().setExternalizedCheckpointCleanup(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION); //设置checkpoint记录的保留策略<br><br>        KafkaSourceBuilder&lt;String&gt; kafkaSource = KafkaSource.&lt;String&gt;builder()  //获取kafka数据源<br>                                                    .setBootstrapServers(&quot;192.168.211.107:6667&quot;)<br>                                                    .setTopics(&quot;test&quot;)<br>                                                    .setGroupId(&quot;FlinkDSFromKafka2Hudi01&quot;)<br>                                                    .setStartingOffsets(OffsetsInitializer.timestamp(1703474520000L)) //确认消费模式为特定时间<br>                                                    .setValueOnlyDeserializer(new SimpleStringSchema());<br><br>        /**将数据源生成DataStream对象*/<br>        DataStreamSource&lt;String&gt; kafkaDS = env.fromSource(kafkaSource.build(), WatermarkStrategy.noWatermarks(), &quot;kafka-data&quot;);<br>        DataStream&lt;RowData&gt; targetDS = kafkaDS.map((MapFunction&lt;String, String[]&gt;) line -&gt; {<br>                                            JSONObject rawJson = JSON.parseObject(line);<br>                                            String message = rawJson.getString(&quot;message&quot;);  //获取业务数据部分<br>                                            String[] msgArray = message.split(&quot;,&quot;);  //指定分隔符进行字段切分<br>                                            return msgArray;<br>                                        }).filter((FilterFunction&lt;String[]&gt;) array -&gt; {<br>                                            if (array.length == 9) return true;<br>                                            else return false;<br>                                        }).map((MapFunction&lt;String[], RowData&gt;) array -&gt; {<br>                                            GenericRowData rowData = new GenericRowData(9);<br>                                            rowData.setField(0, StringData.fromString(array[0]));<br>                                            rowData.setField(1, StringData.fromString(array[1]));<br>                                            rowData.setField(2, StringData.fromString(array[2]));<br>                                            rowData.setField(3, StringData.fromString(array[3]));<br>                                            rowData.setField(4, StringData.fromString(array[4]));<br>                                            rowData.setField(5, StringData.fromString(array[5]));<br>                                            rowData.setField(6, StringData.fromString(array[6]));<br>                                            rowData.setField(7, StringData.fromString(array[7]));<br>                                            rowData.setField(8, StringData.fromString(array[8]));<br>                                            return rowData;<br>                                        });<br><br>        Map&lt;String, String&gt; options = new HashMap&lt;&gt;();<br>        options.put(FlinkOptions.PATH.key(), &quot;hdfs://192.168.211.106:8020/tmp/hudi/data_from_flink2hudi01&quot;);<br>        //options.put(FlinkOptions.TABLE_TYPE.key(), HoodieTableType.COPY_ON_WRITE.name());<br>        options.put(&quot;table.type&quot;, args[1]); //指定写入类型<br>        options.put(&quot;file.format&quot;, &quot;ORC&quot;); //默认为Parquet<br>        //options.put(FlinkOptions.PRECOMBINE_FIELD.key(), &quot;client_ip,domain,time,target_ip&quot;);<br>        HoodiePipeline.Builder builder = HoodiePipeline.builder(&quot;data_from_flink2hudi01&quot;)<br>                .column(&quot;client_ip string&quot;)<br>                .column(&quot;domain string&quot;)<br>                .column(&quot;`time` string&quot;)<br>                .column(&quot;target_ip string&quot;)<br>                .column(&quot;rcode string&quot;)<br>                .column(&quot;query_type string&quot;)<br>                .column(&quot;authority_record string&quot;)<br>                .column(&quot;add_msg string&quot;)<br>                .column(&quot;dns_ip string&quot;)<br>                .pk(&quot;client_ip&quot;,&quot;domain&quot;,&quot;`time`&quot;,&quot;target_ip&quot;) //主键字段<br>                .options(options);<br>        builder.sink(targetDS, false);<br>        env.execute();<br>    }<br>}</pre><p>I originally planned to write in Scala, but it turned out that as described in the previous article, <strong>there is still a problem that the types of the Scala API and the Java API cannot be interoperable (mutually converted) in certain places</strong> (I still miss the Spark API).</p><h3>3. First test comparison</h3><p>The test conditions are as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b17e8ea0997775f81b8f5eadd35b386a/href">https://medium.com/media/b17e8ea0997775f81b8f5eadd35b386a/href</a></iframe><p><em>Originally, I thought that taskmanager would directly use the default memory (1.7G), and then just use parallelism of 1, because considering that the amount of text data I poured into Kafka was only 3.1G, but after testing, I found that it would not work. Just gave me OOM</em> .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/0*KSk5OCsGvDZrda8m" /></figure><p>Therefore, I thought about re-adjusting the parameters (based on the principle of saving resources, I tried several times).</p><h4>3.1 Flink writes Hudi table</h4><p>Since the data is stored in Kafka in advance, after starting the program, there must be backpressure in the data source, and the writing end is very busy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/0*Y_zu9eEFVgVfSA05" /></figure><p>Since it is a streaming task, even if it consumes all the data I poured into Kafka, the task will not exit. In order to accurately observe the exact time when the program consumes the data, I can only stare at this page until the known amount of data is consumed, and then record the time spent by the program at this time.</p><p>So, I waited and waited and waited!</p><p>After more than an hour of long waiting, the number I was looking forward to, 24633164, finally appeared (all the data in Kafka has been consumed).</p><blockquote>A writing feature here is that the data is written very quickly in the early stage, but in the later stage, due to some reason of compacting, the data writing speed became slower.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*S7HEwiOUHYp45DFF" /></figure><p>Then, the status of the task instantly changed from “busy” to “idle”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/0*AMqMwCQS2479LRU9" /></figure><p>The entire process takes approximately: <strong>82 minutes</strong>.</p><p>A total of 260–2= <strong>258 data files</strong> are generated (excluding 2 metadata directories).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/0*bmIs28Q7fMj8P88M" /></figure><p>Note that I am using the COPY_ON_WRITE table here.</p><h4>3.2 Flink writes Paimon table</h4><p>You may not believe it, but when I use the same data source and the same degree of parallelism to write the Paimon table, after the task is submitted, it actually looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/0*-bcf11Bq0FIG6sU0" /></figure><p>The status kept spinning here, and when I came back from a 10-min break, it was still spinning.</p><p>I was puzzled, where is the problem? The key point is that I tried many times but it didn’t work (the cluster resources are sufficient).</p><p>So, I subsequently changed the parallelism to 7, 6, 5, 4, 3, 2, and 1. As a result, it worked fine from 6 onwards.</p><p>Finally, I used parallelism of 6 and finally got it running:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/0*wAo5fwXXoEZXWla6" /></figure><p>Although the parallelism is only 6, the efficiency of writing Paimon with Flink is obviously faster than writing Hudi.</p><p>Likewise, it took about half an hour to complete all data writing without me blinking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/0*zoYRlPZAv30UD10D" /></figure><p>The total time taken is about: <strong>29 minutes</strong>.</p><p>The total number of files generated is <strong>99.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/0*na0kvOXZcilCUGEO" /></figure><p><strong><em>Summary:</em></strong></p><p>From the actual measurement, for the current comparison, Paimon’s writing efficiency and writing effect (number of files), <strong>the writing speed is more than 2 times that of Hudi, while the number of files is less than half of Hudi’s</strong>.</p><p><strong>However, compared with the official test of Flink, the conclusion that writing efficiency is 12 times faster than Hudi COW table is not reflected here at all (of course, the amount of data tested is different )</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/0*OUpp-wUvteHEYd5B" /><figcaption><em>Comparison conclusion given by Flink official public account</em></figcaption></figure><p>But then, something strange happened. When I used the read API to read Paimon’s table and Hudi’s table data, only Hudi’s data was successfully read.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/0*B50Qkj7F5K15KB2R" /></figure><p>As for the Paimon table, it cannot be read no matter what (works only with small data volume, at the level of several millions).</p><h3>4. Second test comparison</h3><p>The test conditions are as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bade7d83108cc827c6ec7a6894a6be5e/href">https://medium.com/media/bade7d83108cc827c6ec7a6894a6be5e/href</a></iframe><h4>4.1 Flink writes Hudi table</h4><p>At this time, in addition to extending the checkpoint time to 2 minutes, Hudi’s table type was also changed to MERGE_ON_READ.</p><p>As for why the memory of tasksmanger should be changed to 6G, it is because when running on 4G, OOM occurs.</p><p>Let’s take a look at the results after running:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/0*lZjwC8Edwwu5z8gg" /></figure><p>Likewise, I watched it finish with my eyes wide open, so if I pinched it at this time, I was sure.</p><p>It can be clearly seen that after switching to the MERGE_ON_READ table, the efficiency is so much faster: From the previous more than an hour, it suddenly became: <strong>9 minutes and 36 seconds</strong>.</p><p>The number of files generated has also changed from the previous 258 to: <strong>41 (43 minus 2 metadata folder directories)</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/0*8QI3tPUukBlrt9rN" /></figure><h4>4.2 Flink writes Paimon table</h4><p>This time it is finally possible to use 8 degrees of parallelism. The other conditions are as shown in the table above. After writing 24633164 Kafka records, the conclusion is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/0*gPdBWpIGf1W75GHx" /></figure><p>The total time taken is about: <strong>13 minutes and 8 seconds</strong>.</p><p>The number of files generated is <strong>58</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/0*bz6HWFKGHS3hrspA" /></figure><p>Did you notice that Hudi has outperformed this time?</p><p><strong><em>summary:</em></strong></p><p>Compared with Paimon, Hudi performs better than Paimon in terms of writing speed and the number of generated files after changing the table type to MERGE_ON_READ.</p><p>This time, Hudi’s writing efficiency <strong>is more than 3 minutes faster than Paimon, and the number of files generated is 17 fewer</strong> than Paimon.</p><p>There is a big discrepancy with the conclusion given by Flink’s official website (of course, the amount of test data is different):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/0*YnBKdDh_8OJIZ_8T" /></figure><h3>5. Third test comparison</h3><p>The test conditions are as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f91ad8667f88852fc9a392143564e00/href">https://medium.com/media/3f91ad8667f88852fc9a392143564e00/href</a></iframe><h4>5.1 Flink writes Hudi table</h4><p>I first use the <strong>MERGE_ON_READ </strong>table type to test and see the conclusion directly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/0*lAXjri_VfkAnAsYg" /></figure><p>Compared with the last time, there is not much difference, the time taken is: <strong>11 minutes and 20 seconds</strong>.</p><p>The number of files generated also remains unchanged:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/0*YRp-7CdkwYFzQIKx" /></figure><p>Still <strong>41</strong>.</p><p>Then use the <strong>COPY_ON_WRITE</strong> table type to test and see the conclusion:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/0*kVImaKtih_ZSZFKi" /></figure><p>At this time, the time taken to write all the data is: <strong>24 minutes and 30 seconds</strong>.</p><p>The number of generated files is 90–2= <strong>88</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/0*kY0J_bSUgXUWzkua" /></figure><h4>5.2 Flink writes Paimon table</h4><p>Let’s go straight to the conclusion:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/0*dGDbTRQtp7plTYnc" /></figure><p>The time it takes to write all the data is: <strong>16 minutes and 27 seconds</strong> (watching the entire process).</p><p>The number of data files written is <strong>54</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/0*VFKGO5xsezrVEZfv" /></figure><p><strong><em>summary:</em></strong></p><p>Judging from actual measurements, <strong>Hudi’s MOR table is better than Paimon in terms of writing speed and the number of files generated</strong>.</p><p><strong>Hudi’s COW table is just the opposite</strong> . Its writing speed and number of files generated are worse than Paimon’s, but this gap seems to be gradually narrowing as the checkpoint time increases.</p><h3>At last</h3><p>Judging from the results of this actual measurement comparison, although the coverage is not complete, it can actually explain the problem and once again verify the sentence:</p><p><strong><em>Any conclusion about performance testing must be based on specific scenarios to be meaningful, otherwise it will be nonsense and misleading.</em></strong></p><p>Then, the test conclusions based on this test scenario are as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5dd5612dd651c102e245c4dde8db267e/href">https://medium.com/media/5dd5612dd651c102e245c4dde8db267e/href</a></iframe><p>Although there is no reverse conclusion as I posted in my WeChat circle, it is still very different from the official one.</p><p>Of course, this may be related to the closer integration between Hudi and Spark. Next time I have a chance, I will test it with Spark again (looking forward to a real reversal).</p><p>So what do you think of the conclusion of this test?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fccb1f745ab5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/apache-hudi-blogs/paimon-v-s-hudi-write-efficiency-fccb1f745ab5">Paimon v.s. Hudi write efficiency</a> was originally published in <a href="https://medium.com/apache-hudi-blogs">apache-hudi-blogs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hudi vs Delta vs Iceberg Lakehouse Feature Comparisons]]></title>
            <link>https://medium.com/apache-hudi-blogs/hudi-vs-delta-vs-iceberg-lakehouse-feature-comparisons-ef34345d8799?source=rss----464bbeff5499---4</link>
            <guid isPermaLink="false">https://medium.com/p/ef34345d8799</guid>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[apache-iceberg]]></category>
            <category><![CDATA[data-lakehouse]]></category>
            <category><![CDATA[apache-hudi]]></category>
            <category><![CDATA[delta-lake]]></category>
            <dc:creator><![CDATA[Kyle Weller]]></dc:creator>
            <pubDate>Wed, 24 Aug 2022 21:00:09 GMT</pubDate>
            <atom:updated>2022-08-24T21:10:22.312Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Delta vs Iceberg vs Hudi" src="https://cdn-images-1.medium.com/max/1024/1*bcWahI3Fy_OaCbasNzliZQ.png" /><figcaption>Apache Hudi vs Delta Lake vs Apache Iceberg</figcaption></figure><h3>Introduction</h3><p>With growing popularity of the lakehouse there has been a rising interest in the analysis and comparison of the open source projects which are at the core of this data architecture: Apache Hudi, Delta Lake, and Apache Iceberg.</p><p>Most comparison articles currently published seem to evaluate these projects merely as table/file formats for traditional append-only workloads, overlooking some qualities and features that are critical for modern data lake platforms that need to support update heavy workloads with continuous table management. This article will dive into greater depth to highlight technical differentiators of Apache Hudi and how it is a full fledged data lake platform steps ahead of the rest.</p><p><em>(This article is a repost from: </em><a href="https://www.onehouse.ai/blog/apache-hudi-vs-delta-lake-vs-apache-iceberg-lakehouse-feature-comparison"><em>https://www.onehouse.ai/blog/apache-hudi-vs-delta-lake-vs-apache-iceberg-lakehouse-feature-comparison</em></a></p><p><em>To see rich clickthroughs to all hyperlinks in the feature comparison table, see the original post.)</em></p><h3>Feature Comparisons</h3><p>First let’s look at an overall feature comparison. As you read, notice how the Hudi community has invested heavily into comprehensive platform services on top of the lake storage format. While formats are critical for standardization and interoperability, table/platform services give you a powerful toolkit to easily develop and manage your data lake deployments.</p><p><em>(*NOTE: Due to limitations on medium, I can’t embed a table here. To see the rich html table with all of these hyperlinks below, see this original article here: </em><a href="https://www.onehouse.ai/blog/apache-hudi-vs-delta-lake-vs-apache-iceberg-lakehouse-feature-comparison"><em>https://www.onehouse.ai/blog/apache-hudi-vs-delta-lake-vs-apache-iceberg-lakehouse-feature-comparison</em></a><em>)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*5LRhC2TTBDNrEJ4fBMFqTQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*uoc1AIweAP2wI_QK0ThZsA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*iRycP9Y1YEOiOzovDgQRxA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*znonFvdtzZ8hwJa7tZWBVg.png" /></figure><h3>Feature Highlights</h3><p>Of course, building a data lake platform is more than just checkboxes of feature availability. Let’s pick a few of the differentiating features above and dive into the use cases and real benefits in plain english.</p><h3>Incremental Pipelines</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uUZJaQuuqyD6TRZm.gif" /></figure><p>The majority of data engineers today feel like they have to choose between streaming and old-school batch ETL pipelines. Apache Hudi has pioneered a new paradigm called <a href="https://eng.uber.com/hoodie/">Incremental Pipelines</a>. Out of the box, Hudi tracks all changes (appends, updates, deletes) and exposes them as <a href="https://hudi.apache.org/docs/querying_data#spark-incr-query">change streams</a>. With record level indexes you can more efficiently leverage these change streams to avoid recomputing data and just process changes incrementally. While other data lake platforms may enable a way to consume changes incrementally, Hudi is designed from the ground up to enable incrementalization efficiently which results in cost efficient ETL pipelines at lower latencies.</p><p>Databricks recently developed a similar feature they call <a href="https://docs.databricks.com/delta/delta-change-data-feed.html">Change Data Feed</a> which they have held proprietary until it was finally released to open source in Delta Lake 2.0. Iceberg has an <a href="https://iceberg.apache.org/docs/latest/spark-queries/#incremental-read">incremental read</a>, but it only allows you to read incremental appends, no updates/deletes which are essential for true Change Data Capture and transactional data.</p><h3>Concurrency Control</h3><figure><img alt="Hudi Concurrency" src="https://cdn-images-1.medium.com/max/1024/0*Z2agoWl-pJCR_2Sm.gif" /></figure><p>ACID transactions and concurrency control are key characteristics of a Lakehouse, but how do current designs actually stack up compared to real world workloads? Hudi, Delta, and Iceberg all support <a href="https://en.wikipedia.org/wiki/Optimistic_concurrency_control">Optimistic Concurrency Control</a> (OCC). In optimistic concurrency control, writers check if they have overlapping files and if a conflict exists, they fail the operations and retry. For Delta Lake as an example this was just a JVM level lock held on a single Apache Spark driver node which means you have no OCC outside of a single cluster, until <a href="https://docs.delta.io/latest/delta-storage.html#multi-cluster-setup">recently</a>.</p><p>While this may work fine for append-only immutable datasets, optimistic concurrency control struggles with real world scenarios which introduces the need for frequent updates and deletes because of the data loading pattern or reorganizing the data for query performance. Oftentimes, it’s not practical to take writers offline for table management to ensure the table is healthy and performant. Apache Hudi concurrency control is more granular than other data lake platforms (File level) and with a design optimized for multiple small updates/deletes the conflict possibility can be largely reduced to negligible in most real world cases. You can read more details in <a href="https://hudi.apache.org/blog/2021/12/16/lakehouse-concurrency-control-are-we-too-optimistic/">this blog</a>, of how you can operate with asynchronous table services even in multi-writer scenarios, without the need to pause writers. This is very close to the level of concurrency supported by standard databases.</p><h3>Merge On Read</h3><p>Any good database system supports <a href="https://research.ibm.com/publications/designing-access-methods-the-rum-conjecture">different trade-offs</a> between write and query performance. The Hudi community has made some seminal contributions, in terms of defining these concepts for data lake storage across the industry. Hudi, Delta, and Iceberg all write and store data in parquet files. When updates occur, these parquet files are versioned and rewritten. This write mode pattern is what <a href="https://stackoverflow.com/questions/628938/what-is-copy-on-write">the industry</a> now calls Copy On Write (CoW). This model works well for optimizing query performance, but can be limiting for write performance and data freshness. In addition to CoW, Apache Hudi supports another table storage layout called <a href="https://hudi.apache.org/docs/table_types#merge-on-read-table">Merge On Read</a> (MoR). MoR stores data using a combination of columnar parquet files and row-based Avro log files. Updates can be batched up in log files that can later be compacted into new parquet files synchronously or asynchronously to balance maximum query performance and lower write amplification.</p><figure><img alt="Apache Hudi Merge On Read" src="https://cdn-images-1.medium.com/max/1024/0*_NFdQLaRGiqDuK3V.png" /></figure><p>Thus, for a near real time streaming workload, Hudi could use the more efficient row oriented formats and for batch workloads the hudi format uses vectorizable column oriented format with seamless merging of the two formats when required. Many users turn to Apache Hudi since it is the only project with this capability which allows them to achieve unmatched write performance and E2E data pipeline latencies.</p><h3>Partition Evolution</h3><p>One feature often highlighted for Apache Iceberg is hidden partitioning that unlocks what is called <a href="https://iceberg.apache.org/docs/latest/evolution/#partition-evolution">partition evolution</a>. The basic idea is when your data starts to evolve, or you just aren’t getting the performance value you need out of your current partitioning scheme, partition evolution allows you to update your partitions for new data without rewriting your data. When you evolve your partitions, old data is left in the old partitioning scheme and only new data is partitioned with your evolution. A table partitioned multiple ways pushes complexity to the user and cannot guarantee consistent performance if the user is unaware of the evolution history.</p><figure><img alt="Hudi Clustering" src="https://cdn-images-1.medium.com/max/884/0*SbCNrf64U6KiZZb5.png" /></figure><p>Apache Hudi takes a different approach to address the problem of adjusting data layout as your data evolves with <a href="https://hudi.apache.org/docs/clustering">Clustering</a>. You can choose a coarse-grained partition strategy or even leave it unpartitioned, and use a more fine-grained clustering strategy within each partition. Clustering can be run synchronously or asynchronously and can be evolved without rewriting any data. This approach is comparable to the micro-partitioning and clustering <a href="https://docs.snowflake.com/en/user-guide/tables-clustering-micropartitions.html#what-are-micro-partitions">strategy of Snowflake</a>.</p><h3>Multi-Modal Indexing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*A_B_h6QY3jyOU4Wb.png" /></figure><p>Indexing is an integral component for databases and data warehouses, yet is largely absent in data lakes. In recent releases, Apache Hudi created a first-of-its-kind high performance indexing subsystem for the Lakehouse that we call the <a href="https://www.onehouse.ai/blog/introducing-multi-modal-index-for-the-lakehouse-in-apache-hudi">Hudi Multi-Modal Index</a>. Apache Hudi offers an <a href="https://github.com/apache/hudi/blob/master/rfc/rfc-45/rfc-45.md">asynchronous indexing</a> mechanism that allows you to build and change indexes without impacting write latency. This indexing mechanism is extensible and scalable to support any popular index techniques such as Bloom, Hash, Bitmap, R-tree, etc.</p><p>These indexes are stored in the <a href="https://cwiki.apache.org/confluence/pages/viewpage.action?pageId=147427331">Hudi Metadata Table</a> which is stored in cloud storage next to your data. In this new release the metadata is written in optimized indexed file formats which results in 10–100x performance improvements for point lookups versus Delta or Iceberg generic file formats. When testing real world workloads, this new indexing subsystem results in 10–30x overall query performance.</p><h3>Ingestion Tools</h3><p>What sets a data platform apart from data formats are the operational services available. A differentiator for Apache Hudi is the powerful ingestion utility called <a href="https://hudi.apache.org/docs/hoodie_deltastreamer">DeltaStreamer</a>. DeltaStreamer is battle tested and used in production to build some of the largest data lakes on the planet today. DeltaStreamer is a standalone utility which allows you to incrementally ingest upstream changes from a wide variety of sources such as DFS, Kafka, database changelogs, S3 events, JDBC, and more.</p><p>Iceberg has no solution for a managed ingestion utility, and Delta Autoloader remains a Databricks proprietary feature that only supports cloud storage sources such as S3.</p><h3>Use Cases — Examples from the community</h3><p>Feature comparisons and <a href="https://www.onehouse.ai/blog/apache-hudi-vs-delta-lake-transparent-tpc-ds-lakehouse-performance-benchmarks">benchmarks</a> can help newcomers orient themselves on what technology choices are available, but more important is sizing up your personal use cases and workloads to find the right fit for your data architecture. All three of these technologies, Hudi, Delta, Iceberg have different origin stories and advantages for certain use cases. Iceberg was born at Netflix and was designed to overcome cloud storage scale problems like file listings. Delta was born at Databricks and it has deep integrations and accelerations when using the Databricks Spark runtime. Hudi was born at Uber to power petabyte scale data lakes in near real-time, with painless table management.</p><p>From years of engaging in real world comparison evaluations in the community, Apache Hudi routinely has a technical advantage when you have mature workloads that grow beyond simple append-only inserts. Once you start processing many updates, start adding real concurrency, or attempt to reduce the E2E latency of your pipelines, Apache Hudi stands out as the industry leader in performance and feature set.</p><p>Here are a couple examples and stories from <a href="https://hudi.apache.org/powered-by">the community</a> who independently evaluated and decided to use Apache Hudi:</p><h3><a href="https://hudi.apache.org/blog/2021/09/01/building-eb-level-data-lake-using-hudi-at-bytedance/">Amazon package delivery system</a> -</h3><p><em>“One of the biggest challenges ATS faced was handling data at petabyte scale with the need for constant inserts, updates, and deletes with minimal time delay, which reflects real business scenarios and package movement to downstream data consumers.”</em></p><p><em>“In this post, we show how we ingest data in real time in the order of hundreds of GBs per hour and run inserts, updates, and deletes on a petabyte-scale data lake using </em><strong><em>Apache Hudi</em></strong><em> tables loaded using AWS Glue Spark jobs and other AWS server-less services including AWS Lambda, Amazon Kinesis Data Firehose, and Amazon DynamoDB”</em></p><h3><a href="https://hudi.apache.org/blog/2021/09/01/building-eb-level-data-lake-using-hudi-at-bytedance/">ByteDance/Tiktok</a></h3><p><em>“In our scenario, the performance challenges are huge. The maximum data volume of a single table reaches 400PB+, the daily volume increase is PB level, and the total data volume reaches EB level.”</em></p><p><em>“The throughput is relatively large. The throughput of a single table exceeds 100 GB/s, and the single table needs PB-level storage. The data schema is complex. The data is highly dimensional and sparse. The number of table columns ranges from 1,000 to 10,000+. And there are a lot of complex data types.”</em></p><p><em>“When making the decision on the engine, we examine three of the most popular data lake engines, </em><strong><em>Hudi, Iceberg, and DeltaLake</em></strong><em>. These three have their own advantages and disadvantages in our scenarios. Finally, Hudi is selected as the storage engine based on Hudi’s openness to the upstream and downstream ecosystems, support for the global index, and customized development interfaces for certain storage logic.”</em></p><h3><a href="https://www.youtube.com/watch?v=ZamXiT9aqs8">Walmart</a></h3><figure><img alt="Walmart Hudi" src="https://cdn-images-1.medium.com/max/1024/0*d0RC6I8iKgl2VOJU.png" /></figure><p>From video transcription:</p><p><em>“Okay so what is it that enables us for us and why do we really like the </em><strong><em>Hudi</em></strong><em> features that have unlocked this in other use cases? We like the optimistic concurrency or mvcc controls that are available to us. We’ve done a lot of work around asynchronous compaction. We’re in the process of looking at doing asynchronous compaction rather than inline compaction on our merge on read tables.</em></p><p><em>We also want to reduce latency and so we leverage merge on read table significantly because that enables us to append data much faster. We also love native support for deletion. It’s something we had custom frameworks built for things like ccpa and gdpr where somebody would uh put in a service desk ticket and we’d have to build an automation flow to remove records from hdfs this comes out of the box for us.</em></p><p><em>Row versioning is really critical obviously a lot of our pipelines have out of order data and we need the latest records to show up and so we provide version keys as part of our framework for all upserts into the </em><strong><em>hudi tables</em></strong><em>.</em></p><p><em>The fact that customers can pick and choose how many versions of a row to keep be able to provide snapshot queries and get incremental updates like what’s been updated in the last five hours is really powerful for a lot of users”</em></p><h3><a href="https://robinhood.engineering/author-balaji-varadarajan-e3f496815ebf">Robinhood</a></h3><p><em>“Robinhood has a genuine need to keep data freshness low for the Data Lake. Many of the batch processing pipelines that used to run on daily cadence after or before market hours had to be run at hourly or higher frequency to support evolving use-cases. It was clear we needed a faster ingestion pipeline to replicate online databases to the data-lake.”</em></p><p><em>“We are using </em><strong><em>Apache Hudi</em></strong><em> to incrementally ingest changelogs from Kafka to create data-lake tables. Apache Hudi is a unified Data Lake platform for performing both batch and stream processing over Data Lakes. Apache Hudi comes with a full-featured out-of-box Spark based ingestion system called Deltastreamer with first-class Kafka integration, and exactly-once writes. Unlike immutable data, our CDC data have a fairly significant proportion of updates and deletes. Hudi Deltastreamer takes advantage of its pluggable, record-level indexes to perform fast and efficient upserts on the Data Lake table.”</em></p><h3><a href="https://aws.amazon.com/blogs/architecture/insights-for-ctos-part-3-growing-your-business-with-modern-data-capabilities/">Zendesk</a></h3><p><em>“The Data Lake pipelines consolidate the data from Zendesk’s highly distributed databases into a data lake for analysis.</em></p><p><em>Zendesk uses Amazon Database Migration Service (AWS DMS) for change data capture (CDC) from over 1,800 Amazon Aurora MySQL databases in eight AWS Regions. It detects transaction changes and applies them to the data lake using Amazon EMR and </em><strong><em>Hudi</em></strong><em>.</em></p><p><em>Zendesk ticket data consists of over 10 billion events and petabytes of data. The data lake files in Amazon S3 are transformed and stored in </em><strong><em>Apache Hudi</em></strong><em> format and registered on the AWS Glue catalog to be available as data lake tables for analytics querying and consumption via Amazon Athena.”</em></p><h3><a href="https://aws.amazon.com/blogs/big-data/how-ge-aviation-built-cloud-native-data-pipelines-at-enterprise-scale-using-the-aws-platform/">GE Aviation</a></h3><p><em>“The introduction of a more seamless </em><strong><em>Apache Hudi</em></strong><em> experience within AWS has been a big win for our team. We’ve been busy incorporating Hudi into our CDC transaction pipeline and are thrilled with the results. We’re able to spend less time writing code managing the storage of our data, and more time focusing on the reliability of our system. This has been critical in our ability to scale. Our development pipeline has grown beyond 10,000 tables and more than 150 source systems as we approach another major production cutover.”</em></p><h3>A Community that Innovates</h3><p>Finally, given how quickly lakehouse technologies are evolving, it’s important to consider where open source innovation in this space has come from. Below are a few foundational ideas and features that originated in Hudi and that are now being adopted into the other projects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*hWxdRcl6f5eQNcLlnAuZFw.png" /></figure><p>In fact, outside of the table metadata (file listings, column stats) support, the Hudi community has pioneered most of the other critical features that make up today’s lakehouses. The community has supported over 1500 user issues and 5500+ slack support threads over the last 4 years, and is rapidly growing stronger with an ambitious <a href="https://hudi.apache.org/blog/2021/07/21/streaming-data-lake-platform">vision</a> ahead. Users can consider this track record of innovation as a leading indicator for the future that lies ahead.</p><h3>Conclusion</h3><p>When choosing the technology for your Lakehouse it is important to perform an evaluation for your own personal use cases. Feature comparison spreadsheets and <a href="https://www.onehouse.ai/blog/apache-hudi-vs-delta-lake-transparent-tpc-ds-lakehouse-performance-benchmarks">benchmarks</a> should not be the end-all deciding factor, so we hope that this blog post simply provides a starting point and reference for you in your decision making process. Apache Hudi is innovative, battle hardened and here to stay. Join us on <a href="https://join.slack.com/t/apache-hudi/shared_invite/zt-1e94d3xro-JvlNO1kSeIHJBTVfLPlI5w">Hudi Slack</a> where you can ask questions and collaborate with the vibrant community from around the globe.</p><p>If you would like 1:1 consultation to dive deep into your use cases and architecture, feel free to reach out at <a href="/service/mailto:info@onehouse.ai?subject=Lakehouse%20comparisons">info@onehouse.ai</a>. At Onehouse we have decades of experience designing, building, and operating some of the largest distributed data systems in the world. We recognize these technologies are complex and rapidly evolving. It is likely we missed a feature or could have read the documentation wrong on some of the above comparisons. Please drop a note to <a href="/service/mailto:info@onehouse.ai?subject=Lakehouse%20comparisons">info@onehouse.ai</a> if you see any comparisons above that stand in need of correction so we can keep the facts accurate in this article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef34345d8799" width="1" height="1" alt=""><hr><p><a href="https://medium.com/apache-hudi-blogs/hudi-vs-delta-vs-iceberg-lakehouse-feature-comparisons-ef34345d8799">Hudi vs Delta vs Iceberg Lakehouse Feature Comparisons</a> was originally published in <a href="https://medium.com/apache-hudi-blogs">apache-hudi-blogs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apache Hudi vs Delta Lake — Transparent TPC-DS Lakehouse Performance Benchmarks]]></title>
            <link>https://medium.com/apache-hudi-blogs/apache-hudi-vs-delta-lake-transparent-tpc-ds-lakehouse-performance-benchmarks-9a187eb88147?source=rss----464bbeff5499---4</link>
            <guid isPermaLink="false">https://medium.com/p/9a187eb88147</guid>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[delta-lake]]></category>
            <category><![CDATA[apache-hudi]]></category>
            <category><![CDATA[data-lakehouse]]></category>
            <dc:creator><![CDATA[Kyle Weller]]></dc:creator>
            <pubDate>Wed, 29 Jun 2022 21:18:55 GMT</pubDate>
            <atom:updated>2022-06-29T21:18:55.097Z</atom:updated>
            <content:encoded><![CDATA[<h3>Apache Hudi vs Delta Lake — Transparent TPC-DS Lakehouse Performance Benchmarks</h3><p><em>Repost from: </em><a href="https://www.onehouse.ai/blog/apache-hudi-vs-delta-lake-transparent-tpc-ds-lakehouse-performance-benchmarks"><em>https://www.onehouse.ai/blog/apache-hudi-vs-delta-lake-transparent-tpc-ds-lakehouse-performance-benchmarks</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7nhI5CPfAovqdVNMv5HRvA.png" /></figure><h3>Intro</h3><p>In recent weeks, there has been a <a href="https://bytearray.io/corrections-in-data-lakehouse-table-format-comparisons-b72eb63ece32">growing interest</a> in comparing the performance of Hudi vs. Delta vs. Iceberg. We felt the community deserves more transparent and reproducible analysis. We want to add our perspective on how these benchmarks should be executed and presented, what value they bring, and how we should interpret them.</p><h3>What are the issues with existing approaches?</h3><p>Recently <a href="https://databeans-blogs.medium.com/delta-vs-iceberg-vs-hudi-reassessing-performance-cb8157005eb0">Databeans published a blog</a> where the performance of Hudi/Delta/Iceberg is compared head-to-head using a TPC-DS benchmark. While it’s fantastic to see the community coming forward and taking action to improve awareness of the current state of the art in the industry, we identified a few issues with the way the experiments were conducted and the results were reported, which we want to share and discuss more broadly today.</p><p>As a community, we should strive to add more rigor when publishing benchmarks. We believe these are crucial tenets of any benchmarking efforts:</p><ol><li><strong>Reproducible</strong>: If results are not reproducible, the reader has no choice but to blindly trust the results at face value. Instead, the benchmark should be documented such that <em>anyone </em>can achieve the same results using the <em>same instruments</em>.</li><li><strong>Open</strong>: To achieve the same results, it’s vital to make sure that the tooling used for benchmarking is accessible to review correctness.</li><li><strong>Fair</strong>: With the complexity of the technologies being tested growing constantly, the benchmark setup needs to ensure all contenders use documented configurations for the workloads under test.</li></ol><p>With respect to these fundamental issues, we believe that the Databeans blog, unfortunately, came short of sharing the complete picture of what and how the results were achieved. For example:</p><ul><li>Benchmarked EMR Runtime configuration was not fully disclosed: it’s unclear, e.g., whether or not Spark’s <a href="https://docs.aws.amazon.com/emr/latest/ReleaseGuide/emr-spark-configure.html">dynamic allocation feature</a> was disabled, as it has the potential to affect the measurements unpredictably.</li><li>Code used for Benchmarking is an extension of <a href="https://github.com/delta-io/delta/tree/master/benchmarks">Delta’s benchmarking framework</a>, which is also, unfortunately, not shared publicly, making it impossible to review or replay the same experiment.</li><li>Not having access to the code also affects the ability to analyze configurations applied to Hudi/Delta/Iceberg, which makes it challenging to assess fairness</li></ul><h3>How we suggest running benchmarks</h3><p>We routinely run performance benchmarks to make sure that Hudi’s rich feature-set is provided along with the best performance possible for the exabytes of Hudi-powered data lakes out there. Our team has extensive <a href="https://www.confluent.io/blog/kafka-fastest-messaging-system/">experience</a> in benchmarking complex distributed systems like Apache Kafka or Pulsar, true to the principles outlined above.</p><p>To make sure the published benchmarks comply with these principles:</p><ol><li>We switch off Spark’s <a href="https://docs.aws.amazon.com/emr/latest/ReleaseGuide/emr-spark-configure.html">dynamic-allocation</a> feature to make sure we run the benchmark in a stable environment and eliminate any jitter in the results entailed by Spark’s cluster deciding to scale up or down. We use EMR 6.6.0 release, with Spark 3.2.0 and Hive 3.1.2 (for HMS), with the following configuration (which is specified in Spark EMR UI upon creation) For more details on how HMS should be setup please follow <a href="https://github.com/delta-io/delta/tree/56fa242bdbd4b1c2480ade820728843edc2d76fc/benchmarks#create-external-hive-metastore-using-amazon-rds">instructions in the README</a></li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b1451a7894eea916f5c0c61b794ad7a/href">https://medium.com/media/7b1451a7894eea916f5c0c61b794ad7a/href</a></iframe><p>2. We have publicly shared our <a href="https://github.com/delta-io/delta/compare/master...alexeykudinkin:delta:ak/dlt-bcnh-fix">modifications to Delta’s benchmarking framework</a> to support creating Hudi tables through either Spark Datasource or Spark SQL. This could be dynamically switched over within the benchmark definition.</p><p>3. TPC-DS loads do not involve updates. The databeans configuration of Hudi loads used an inappropriate write operation `upsert`, while it is <a href="https://hudi.apache.org/learn/faq/#what-performanceingest-latency-can-i-expect-for-hudi-writing">clearly documented</a> that Hudi `<a href="https://hudi.apache.org/docs/next/write_operations/#bulk_insert">bulk-insert</a>` is the recommended write operation for this use case. Additionally, we adjusted the Hudi parquet file size settings to match Delta Lake defaults.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0a114a77d9dea2a875bd4e59554d41b/href">https://medium.com/media/c0a114a77d9dea2a875bd4e59554d41b/href</a></iframe><p>Hudi’s <a href="https://eng.uber.com/hoodie/">origins</a> take root in incremental data processing to turn all old school batch jobs <a href="https://www.youtube.com/watch?v=5h4i63aB1-I&amp;t=860s">incremental</a>. Thus, Hudi’s default configs are geared towards incremental upserts and generating change streams for incremental ETL pipelines, treating the initial load as a rare, one-time activity. Thus, closer attention needs to be paid for the load times to be comparable with Delta.</p><h3>Running the benchmarks</h3><h4>Loading</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OocmICb4VJ6S9iq7" /><figcaption><a href="https://docs.google.com/spreadsheets/d/13mtvxhzewmuw0WiickqO3oyCPPIVnTHPU1mLzXibvvA/edit?usp=sharing"><em>Reference</em></a></figcaption></figure><p>As could be seen clearly, Delta and Hudi are within 6% for the 0.11.1 release and 5% for the current Hudi’s master* (we’ve additionally benchmarked against Hudi’s master branch since we’ve recently discovered a <a href="https://issues.apache.org/jira/projects/HUDI/issues/HUDI-4319">bug in Parquet encoding configuration</a> that has promptly been resolved).</p><p>To power the rich feature-set that Hudi provides on top of raw Parquet tables, such as:</p><ul><li><a href="https://www.linkedin.com/feed/update/urn:li:activity:6945762629101486080/"><em>Incremental Processing</em></a> (since commit at timestamp t)</li><li><a href="https://hudi.apache.org/blog/2020/11/11/hudi-indexing-mechanisms/"><em>Record-level Indexing</em></a> (powering record-level lookups, updates and deletes),</li><li>and many more, Hudi internally stores a set of additional <em>metadata</em> along with every record called <a href="https://github.com/apache/hudi/blob/master/hudi-common/src/main/java/org/apache/hudi/common/model/HoodieRecord.java#L37">meta-fields</a>. Since <em>tpc-ds</em> is primarily concerned with snapshot queries, in this particular experiment, such fields have been disabled (and not computed), Hudi still does persist them as nulls, enabling turning them on in the future w/o the need to evolve the schema. Adding five such fields as nulls has, while low, still non-negligible overhead.</li></ul><h4>Queries</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rhdAMnhsXDbCI1rL" /><figcaption><a href="https://docs.google.com/spreadsheets/d/13mtvxhzewmuw0WiickqO3oyCPPIVnTHPU1mLzXibvvA/edit#gid=0"><em>Reference</em></a></figcaption></figure><p>As we can see, there’s practically no difference between Hudi 0.11.1 and Delta 1.2.0 performance, and Hudi’s current master is very slightly faster (~5%).</p><p>You can find raw logs in this directory on Google Drive:</p><ul><li>Hudi 0.11: <a href="https://drive.google.com/file/d/1k_zK2jv5c5JxGRPwRknPo9R-KiPcY6lW/view?usp=sharing">Loading</a> / <a href="https://drive.google.com/file/d/1KFcj2WY4tiYQPIJNgJPfmEBail6rAV9c/view?usp=sharing">Querying</a></li><li>Hudi master: <a href="https://drive.google.com/file/d/1M5lyxxa0AEdSk12B9i3c4n9r492ZfCd5/view?usp=sharing">Loading</a> / <a href="https://drive.google.com/file/d/1luTS8d91MjtdlzY_7EQN2wT3QktwVNGd/view?usp=sharing">Querying</a></li><li>Delta 1.2.0: <a href="https://drive.google.com/file/d/1EEnX2jhddZyzlpN6s-SXHJZp-9LTzTYe/view?usp=sharing">Loading</a> / <a href="https://drive.google.com/file/d/17cVgnPcvYHRG1K6hUf9ODS7d5dCFVmdX/view?usp=sharing">Querying</a></li><li>Delta 2.0.0rc1: <a href="https://drive.google.com/file/d/1_Z8OrEkSfraz9Re6AGupNIXULvQYljTl/view?usp=sharing">Loading</a> / <a href="https://drive.google.com/file/d/1buEvptPuz3O-knGZARoGaOewnU1RlegU/view?usp=sharing">Querying</a></li></ul><p>To reproduce the results above, please use <a href="https://github.com/delta-io/delta/compare/master...alexeykudinkin:delta:ak/dlt-bcnh-fix">our branch in Delta’s benchmark</a> repo and follow the steps in the README.</p><h3>Conclusion</h3><p>Summing up, we’ve wanted to underscore the importance of openness and reproducibility in such a sensitive and sophisticated area as performance benchmarking. As we repeatedly saw, obtaining reliable and trustworthy benchmarking results is tedious and challenging, requiring dedication, diligence, and rigor to back it up.</p><p>Going forward, we’re planning to release more internal benchmarks that highlight how Hudi’s rich feature-set reaches unmatched performance levels in other common industry workloads. Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a187eb88147" width="1" height="1" alt=""><hr><p><a href="https://medium.com/apache-hudi-blogs/apache-hudi-vs-delta-lake-transparent-tpc-ds-lakehouse-performance-benchmarks-9a187eb88147">Apache Hudi vs Delta Lake — Transparent TPC-DS Lakehouse Performance Benchmarks</a> was originally published in <a href="https://medium.com/apache-hudi-blogs">apache-hudi-blogs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Change Data Capture with Debezium and Apache Hudi]]></title>
            <link>https://medium.com/apache-hudi-blogs/change-data-capture-with-debezium-and-apache-hudi-2a6ec053aabe?source=rss----464bbeff5499---4</link>
            <guid isPermaLink="false">https://medium.com/p/2a6ec053aabe</guid>
            <dc:creator><![CDATA[Tiffany Jordan]]></dc:creator>
            <pubDate>Thu, 20 Jan 2022 22:58:23 GMT</pubDate>
            <atom:updated>2022-01-20T22:58:23.079Z</atom:updated>
            <content:encoded><![CDATA[<p>Author: Rajesh Mahindra</p><p>As of Hudi v0.10.0, we are excited to announce the availability of <a href="https://debezium.io/">Debezium</a> sources for <a href="https://hudi.apache.org/docs/hoodie_deltastreamer">Deltastreamer</a> that provide the ingestion of change capture data (CDC) from Postgres and Mysql databases to your data lake. For more details, please refer to the original <a href="https://github.com/apache/hudi/blob/master/rfc/rfc-39/rfc-39.md">RFC</a>.</p><h3>Background<a href="https://hudi.apache.org/blog/2022/01/14/change-data-capture-with-debezium-and-apache-hudi/#background">​</a></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*z8tF47WwGBAn6wkc.png" /></figure><p>When you want to perform analytics on data from transactional databases like Postgres or Mysql you typically need to bring this data into an OLAP system such as a data warehouse or a data lake through a process called <a href="https://debezium.io/documentation/faq/#what_is_change_data_capture">Change Data Capture</a> (CDC). Debezium is a popular tool that makes CDC easy. It provides a way to capture row-level changes in your databases by <a href="https://debezium.io/blog/2018/07/19/advantages-of-log-based-change-data-capture/">reading changelogs</a>. By doing so, Debezium avoids increased CPU load on your database and ensures you capture all changes including deletes.</p><p>Now that <a href="https://hudi.apache.org/docs/overview/">Apache Hudi</a> offers a Debezium source connector, CDC ingestion into a data lake is easier than ever with some <a href="https://hudi.apache.org/docs/use_cases">unique differentiated capabilities</a>. Hudi enables efficient update, merge, and delete transactions on a data lake. Hudi uniquely provides <a href="https://hudi.apache.org/docs/table_types#merge-on-read-table">Merge-On-Read</a> writers which unlock <a href="https://aws.amazon.com/blogs/big-data/how-amazon-transportation-service-enabled-near-real-time-event-analytics-at-petabyte-scale-using-aws-glue-with-apache-hudi/">significantly lower latency</a> ingestion than typical data lake writers with Spark or Flink. Last but not least, Apache Hudi offers <a href="https://hudi.apache.org/docs/querying_data#spark-incr-query">incremental queries</a> so after capturing changes from your database, you can incrementally process these changes downstream throughout all of your subsequent ETL pipelines.</p><h3>Design Overview<a href="https://hudi.apache.org/blog/2022/01/14/change-data-capture-with-debezium-and-apache-hudi/#design-overview">​</a></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UxrOJi0uRgpqrx3_.png" /></figure><p>The architecture for an end-to-end CDC ingestion flow with Apache Hudi is shown above. The first component is the Debezium deployment, which consists of a Kafka cluster, schema registry (Confluent or Apicurio), and the Debezium connector. The Debezium connector continuously polls the changelogs from the database and writes an AVRO message with the changes for each database row to a dedicated Kafka topic per table.</p><p>The second component is <a href="https://hudi.apache.org/docs/hoodie_deltastreamer">Hudi Deltastreamer</a> that reads and processes the incoming Debezium records from Kafka for each table and writes (updates) the corresponding rows in a Hudi table on your cloud storage.</p><p>To ingest the data from the database table into a Hudi table in near real-time, we implement two classes that can be plugged into the Deltastreamer. Firstly, we implemented a <a href="https://github.com/apache/hudi/blob/83f8ed2ae3ba7fb20813cbb8768deae6244b020c/hudi-utilities/src/main/java/org/apache/hudi/utilities/sources/debezium/DebeziumSource.java">Debezium source</a>. With Deltastreamer running in continuous mode, the source continuously reads and processes the Debezium change records in Avro format from the Kafka topic for a given table, and writes the updated record to the destination Hudi table. In addition to the columns from the database table, we also ingest some meta fields that are added by Debezium in the target Hudi table. The meta fields help us correctly merge updates and delete records. The records are read using the latest schema from the <a href="https://hudi.apache.org/docs/hoodie_deltastreamer#schema-providers">Schema Registry</a>.</p><p>Secondly, we implement a custom <a href="https://github.com/apache/hudi/blob/83f8ed2ae3ba7fb20813cbb8768deae6244b020c/hudi-common/src/main/java/org/apache/hudi/common/model/debezium/AbstractDebeziumAvroPayload.java">Debezium Payload</a> that essentially governs how Hudi records are merged when the same row is updated or deleted. When a new Hudi record is received for an existing row, the payload picks the latest record using the higher value of the appropriate column (FILEID and POS fields in MySql and LSN fields in Postgres). In the case that the latter event is a delete record, the payload implementation ensures that the record is hard deleted from the storage. Delete records are identified using the op field, which has a value of d for deletes.</p><h3>Apache Hudi Configurations<a href="https://hudi.apache.org/blog/2022/01/14/change-data-capture-with-debezium-and-apache-hudi/#apache-hudi-configurations">​</a></h3><p>It is important to consider the following configurations of your Hudi deployments when using the Debezium source connector for CDC ingestion.</p><ol><li>Record Keys — The Hudi <a href="https://hudi.apache.org/docs/next/indexing">record key(s)</a> for a table should be set as the Primary keys of the table in the upstream database. This ensures that updates are applied correctly as record key(s) uniquely identify a row in the Hudi table.</li><li>Source Ordering Fields — For de-duplication of changelog records the source ordering field should be set to the actual position of the change event as it happened on the database. For instance, we use the FILEID and POS fields in MySql and LSN fields in Postgres databases respectively to ensure records are processed in the correct order of occurrence in the original database.</li><li>Partition Fields — Don’t feel restricted to matching the partitioning of your Hudi tables with the same partition fields as the upstream database. You can set partition fields independently for the Hudi table as needed.</li></ol><h3>Bootstrapping Existing tables<a href="https://hudi.apache.org/blog/2022/01/14/change-data-capture-with-debezium-and-apache-hudi/#bootstrapping-existing-tables">​</a></h3><p>One important use case might be when CDC ingestion has to be done for existing database tables. There are two ways we can ingest existing database data prior to streaming the changes:</p><ol><li>By default on initialization, Debezium performs an initial consistent snapshot of the database (controlled by config snapshot.mode). After the initial snapshot, it continues streaming updates from the correct position to avoid loss of data.</li><li>While the first approach is simple, for large tables it may take a long time for Debezium to bootstrap the initial snapshot. Alternatively, we could run a Deltastreamer job to bootstrap the table directly from the database using the <a href="https://github.com/apache/hudi/blob/master/hudi-utilities/src/main/java/org/apache/hudi/utilities/sources/JdbcSource.java">JDBC source</a>. This provides more flexibility to the users in defining and executing more optimized SQL queries required to bootstrap the database table. Once the bootstrap job finishes successfully, another Deltastreamer job is executed that processes the database changelogs from Debezium. Users will have to use <a href="https://hudi.apache.org/docs/hoodie_deltastreamer/#checkpointing">checkpointing</a> in Deltastreamer to ensure the second job starts processing the changelogs from the correct position to avoid data loss.</li></ol><h3>Example Implementation<a href="https://hudi.apache.org/blog/2022/01/14/change-data-capture-with-debezium-and-apache-hudi/#example-implementation">​</a></h3><p>The following describes steps to implement an end-to-end CDC pipeline using an AWS RDS instance of Postgres, Kubernetes-based Debezium deployment, and Hudi Deltastreamer running on a spark cluster.</p><h3>Database<a href="https://hudi.apache.org/blog/2022/01/14/change-data-capture-with-debezium-and-apache-hudi/#database">​</a></h3><p>A few configuration changes are required for the RDS instance to enable logical replication.</p><pre>SET rds.logical_replication to 1 (instead of 0)</pre><pre>psql --host=&lt;aws_rds_instance&gt; --port=5432 --username=postgres --password -d &lt;database_name&gt;;</pre><pre>CREATE PUBLICATION &lt;publication_name&gt; FOR TABLE schema1.table1, schema1.table2;</pre><pre>ALTER TABLE schema1.table1 REPLICA IDENTITY FULL;</pre><h3>Debezium Connector<a href="https://hudi.apache.org/blog/2022/01/14/change-data-capture-with-debezium-and-apache-hudi/#debezium-connector">​</a></h3><p><a href="https://strimzi.io/blog/2020/01/27/deploying-debezium-with-kafkaconnector-resource/">Strimzi</a> is the recommended option to deploy and manage Kafka connectors on Kubernetes clusters. Alternatively, you have the option to use the Confluent managed <a href="https://docs.confluent.io/debezium-connect-postgres-source/current/overview.html">Debezium connector</a>.</p><pre>kubectl create namespace kafka<br>kubectl create -f https://strimzi.io/install/latest?namespace=kafka -n kafka<br>kubectl -n kafka apply -f kafka-connector.yaml</pre><p>An example for kafka-connector.yaml is shown below:</p><pre>apiVersion: kafka.strimzi.io/v1beta2<br>kind: KafkaConnect<br>metadata:<br>name: debezium-kafka-connect<br>annotations:<br>strimzi.io/use-connector-resources: &quot;false&quot;<br>spec:<br>image: debezium-kafka-connect:latest<br>replicas: 1<br>bootstrapServers: localhost:9092<br>config:<br>config.storage.replication.factor: 1<br>offset.storage.replication.factor: 1<br>status.storage.replication.factor: 1</pre><p>The docker image debezium-kafka-connect can be built using the following Dockerfile that includes the Postgres Debezium Connector.</p><pre>FROM confluentinc/cp-kafka-connect:6.2.0 as cp<br>RUN confluent-hub install --no-prompt confluentinc/kafka-connect-avro-converter:6.2.0<br>FROM strimzi/kafka:0.18.0-kafka-2.5.0<br>USER root:root<br>RUN yum -y update<br>RUN yum -y install git<br>RUN yum -y install wget</pre><pre>RUN wget https://repo1.maven.org/maven2/io/debezium/debezium-connector-postgres/1.6.1.Final/debezium-connector-postgres-1.6.1.Final-plugin.tar.gz<br>RUN tar xzf debezium-connector-postgres-1.6.1.Final-plugin.tar.gz</pre><pre>RUN mkdir -p /opt/kafka/plugins/debezium &amp;&amp; mkdir -p /opt/kafka/plugins/avro/<br>RUN mv debezium-connector-postgres /opt/kafka/plugins/debezium/<br>COPY --from=cp /usr/share/confluent-hub-components/confluentinc-kafka-connect-avro-converter/lib /opt/kafka/plugins/avro/<br>USER 1001</pre><p>Once the Strimzi operator and the Kafka connect are deployed, we can start the Debezium connector.</p><pre>curl -X POST -H &quot;Content-Type:application/json&quot; -d @connect-source.json <a href="http://localhost:8083/connectors/">http://localhost:8083/connectors/</a></pre><p>The following is an example of a configuration to setup Debezium connector for generating the changelogs for two tables, table1, and table2.</p><p>Contents of connect-source.json:</p><pre>{<br>  &quot;name&quot;: &quot;postgres-debezium-connector&quot;,<br>  &quot;config&quot;: {<br>    &quot;connector.class&quot;: &quot;io.debezium.connector.postgresql.PostgresConnector&quot;,<br>    &quot;database.hostname&quot;: &quot;localhost&quot;,<br>    &quot;database.port&quot;: &quot;5432&quot;,<br>    &quot;database.user&quot;: &quot;postgres&quot;,<br>    &quot;database.password&quot;: &quot;postgres&quot;,<br>    &quot;database.dbname&quot;: &quot;database&quot;,<br>    &quot;plugin.name&quot;: &quot;pgoutput&quot;,<br>    &quot;database.server.name&quot;: &quot;postgres&quot;,<br>    &quot;table.include.list&quot;: &quot;schema1.table1,schema1.table2&quot;,<br>    &quot;publication.autocreate.mode&quot;: &quot;filtered&quot;,<br>    &quot;tombstones.on.delete&quot;:&quot;false&quot;,<br>    &quot;key.converter&quot;: &quot;io.confluent.connect.avro.AvroConverter&quot;,<br>    &quot;key.converter.schema.registry.url&quot;: &quot;&lt;schema_registry_host&gt;&quot;,<br>    &quot;value.converter&quot;: &quot;io.confluent.connect.avro.AvroConverter&quot;,<br>    &quot;value.converter.schema.registry.url&quot;: &quot;&lt;schema_registry_host&gt;&quot;,<br>    &quot;slot.name&quot;: &quot;pgslot&quot;<br>  }<br>}</pre><h3>Hudi Deltastreamer<a href="https://hudi.apache.org/blog/2022/01/14/change-data-capture-with-debezium-and-apache-hudi/#hudi-deltastreamer">​</a></h3><p>Next, we run the Hudi Deltastreamer using spark that will ingest the Debezium changelogs from kafka and write them as a Hudi table. One such instance of the command is shown below that works for Postgres database. A few key configurations are as follows:</p><ol><li>Set the source class to PostgresDebeziumSource.</li><li>Set the payload class to PostgresDebeziumAvroPayload.</li><li>Configure the schema registry URLs for Debezium Source and Kafka Source.</li><li>Set the record key(s) as the primary key(s) of the database table.</li><li>Set the source ordering field (dedup) to _event_lsn</li></ol><pre>spark-submit \\<br>  --jars &quot;/home/hadoop/hudi-utilities-bundle_2.12-0.10.0.jar,/usr/lib/spark/external/lib/spark-avro.jar&quot; \\<br>  --master yarn --deploy-mode client \\<br>  --<em>class</em> org.apache.hudi.utilities.deltastreamer.HoodieDeltaStreamer /home/hadoop/hudi-packages/hudi-utilities-bundle_2.12-0.10.0-SNAPSHOT.jar \\<br>  --table-<em>type</em> COPY_ON_WRITE --op UPSERT \\<br>  --target-base-path s3://bucket_name/path/<em>for</em>/hudi_table1 \\<br>  --target-table hudi_table1  --continuous \\<br>  --min-sync-interval-seconds 60 \\<br>  --source-<em>class</em> org.apache.hudi.utilities.sources.debezium.PostgresDebeziumSource \\<br>  --source-ordering-field _event_lsn \\<br>  --payload-<em>class</em> org.apache.hudi.common.model.debezium.PostgresDebeziumAvroPayload \\<br>  --hoodie-conf schema.registry.url=https://localhost:8081 \\<br>  --hoodie-conf hoodie.deltastreamer.schemaprovider.registry.url=https://localhost:8081/subjects/postgres.schema1.table1-value/versions/latest \\<br>  --hoodie-conf hoodie.deltastreamer.source.kafka.value.deserializer.<em>class</em>=io.confluent.kafka.serializers.KafkaAvroDeserializer \\<br>  --hoodie-conf hoodie.deltastreamer.source.kafka.topic=postgres.schema1.table1 \\<br>  --hoodie-conf auto.offset.reset=earliest \\<br>  --hoodie-conf hoodie.datasource.write.recordkey.field=”database_primary_key” \\<br>  --hoodie-conf hoodie.datasource.write.partitionpath.field=partition_key \\<br>  --enable-hive-sync \\<br>  --hoodie-conf hoodie.datasource.hive_sync.partition_extractor_class=org.apache.hudi.hive.MultiPartKeysValueExtractor \\<br>  --hoodie-conf hoodie.datasource.write.hive_style_partitioning=true \\<br>  --hoodie-conf hoodie.datasource.hive_sync.database=default \\<br>  --hoodie-conf hoodie.datasource.hive_sync.table=hudi_table1 \\<br>  --hoodie-conf hoodie.datasource.hive_sync.partition_fields=partition_key</pre><h3>Conclusion<a href="https://hudi.apache.org/blog/2022/01/14/change-data-capture-with-debezium-and-apache-hudi/#conclusion">​</a></h3><p>This post introduced the Debezium Source for Hudi Deltastreamer to ingest Debezium changelogs into Hudi tables. Database data can now be ingested into data lakes to provide a cost-effective way to store and analyze database data.</p><p>Please follow this <a href="https://issues.apache.org/jira/browse/HUDI-1290">JIRA</a> to learn more about active development on this new feature. I look forward to more contributions and feedback from the community. Come join our <a href="https://join.slack.com/t/apache-hudi/shared_invite/enQtODYyNDAxNzc5MTg2LTE5OTBlYmVhYjM0N2ZhOTJjOWM4YzBmMWU2MjZjMGE4NDc5ZDFiOGQ2N2VkYTVkNzU3ZDQ4OTI1NmFmYWQ0NzE">Hudi Slack</a> channel or attend one of our <a href="https://hudi.apache.org/community/syncs">community events</a> to learn more.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a6ec053aabe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/apache-hudi-blogs/change-data-capture-with-debezium-and-apache-hudi-2a6ec053aabe">Change Data Capture with Debezium and Apache Hudi</a> was originally published in <a href="https://medium.com/apache-hudi-blogs">apache-hudi-blogs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hudi Z-Order and Hilbert Space-filling Curves]]></title>
            <link>https://medium.com/apache-hudi-blogs/hudi-z-order-and-hilbert-space-filling-curves-68fa28bffaf0?source=rss----464bbeff5499---4</link>
            <guid isPermaLink="false">https://medium.com/p/68fa28bffaf0</guid>
            <dc:creator><![CDATA[Tiffany Jordan]]></dc:creator>
            <pubDate>Fri, 31 Dec 2021 01:04:56 GMT</pubDate>
            <atom:updated>2021-12-31T01:04:56.653Z</atom:updated>
            <content:encoded><![CDATA[<p>Authors: Tao Meng, <a href="https://medium.com/u/b7a454e0797c">Alexey Kudinkin</a></p><p>As of Hudi v0.10.0, we are excited to introduce support for an advanced Data Layout Optimization technique known in the database realm as <a href="https://en.wikipedia.org/wiki/Z-order_curve">Z-order</a> and <a href="https://en.wikipedia.org/wiki/Hilbert_curve">Hilbert</a> space-filling curves.</p><h3>Background</h3><p>Amazon EMR team recently published a <a href="https://aws.amazon.com/blogs/big-data/new-features-from-apache-hudi-0-7-0-and-0-8-0-available-on-amazon-emr/">great article</a> show-casing how <a href="https://hudi.apache.org/docs/clustering">clustering</a> your data can improve your <em>query performance</em>.</p><p>To better understand what’s going on and how it’s related to space-filling curves, let’s zoom in to the setup in that article:</p><p>In the article, 2 <a href="https://hudi.apache.org/docs/overview">Apache Hudi</a> tables are compared (both ingested from the well-known <a href="https://s3.amazonaws.com/amazon-reviews-pds/tsv/index.txt">Amazon Reviews</a> dataset):</p><ul><li>amazon_reviews table which is not clustered (ie the data has not been re-ordered by any particular key)</li><li>amazon_reviews_clustered table which is clustered. When data is clustered by Apache Hudi the data is <a href="https://en.wikipedia.org/wiki/Lexicographic_order"><strong>lexicographically ordered</strong></a><strong> </strong>(hereon we will be referring to this kind of ordering as <strong><em>linear ordering</em></strong>) by 2 columns: star_rating, total_votes (see screenshot below)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VfJZ6r5ShC_TABXC.png" /></figure><p><em>Screenshot of the Hudi configuration (from Amazon EMR team article)</em></p><p>To showcase the improvement in querying performance, the following queries are executed against both of these tables:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5IqzAI17sqI-XcqO.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TiLcyZI5vS03IyDO.png" /></figure><p><em>Screenshots of the queries run against the previously setup tables (from Amazon EMR team article)</em></p><p>The important consideration to point out here is that the queries were specifying <strong>both of the columns</strong> latter table is ordered by (both star_rating and total_votes).</p><p>And this is unfortunately a crucial limitation of the linear/lexicographic ordering, the value of the ordering diminishes very quickly as you add more columns. It’s not hard to see why:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/0*AkbK_fnReyf4Z8Mr.png" /></figure><p><em>Courtesy of Wikipedia, </em><a href="https://en.wikipedia.org/wiki/Lexicographic_order"><em>Lexicographic Order article</em></a></p><p>From this image you can see that with lexicographically ordered 3-tuples of integers, only the first column is able to feature crucial property of <strong>locality</strong> for all of the records having the same value: for ex, all of the records wit values starting with “1”, “2”, “3” (in the first columns) are nicely clumped together. However if you try to find all the values that have “5” as the value in their third<em> </em>column you’d see that those are now dispersed all over the place, not being localized at all.</p><p>The crucial property that improves query performance is locality: it enables queries to substantially reduce the search space and the number of files that need to be scanned, parsed, etc.</p><p>But… does this mean that our queries are doomed to do a full-scan if we’re filtering by anything other than the first (or more accurate would be to say prefix) of the list of columns the table is ordered by?</p><p>Not exactly: luckily, locality is also a property that space-filling curves enable while enumerating multi-dimensional spaces (records in our table could be represented as points in N-dimensional space, where N is the number of columns in our table)</p><p>How does it work?</p><p>Let’s take Z-curve as an example: Z-order curves fitting a 2-dimensional plane would look like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IOK6vHWBAjfKllCG.png" /></figure><p><em>Courtesy of Wikipedia, </em><a href="https://en.wikipedia.org/wiki/Z-order_curve"><em>Z-order curve article</em></a></p><p>As you can see following its path, instead of simply ordering by one coordinate (“x”) first, following with the other, it’s actually ordering them as if the bits of those coordinates have been <em>interwoven</em> into a single value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TEAnme0p2civ8RDTalOCiQ.png" /></figure><p>This allows for that crucial property of locality (even though a slightly “stretched” one) to be carried over to all columns as compared to just the first one in case of linear ordering.</p><p>In a similar fashion, Hilbert curves also allow you to map points in a N-dimensional space (rows in our table) onto 1-dimensional curve, essentially <em>ordering </em>them, while still preserving the crucial property of locality. Read more details about Hilbert Curves <a href="https://drum.lib.umd.edu/handle/1903/804">here</a>. Our personal experiments so far show that ordering data along a Hilbert curve leads to better clustering and performance outcomes.</p><p>Now, let’s check it out in action!</p><h3>Setup</h3><p>We will use the <a href="https://s3.amazonaws.com/amazon-reviews-pds/readme.html">Amazon Reviews</a> dataset again, but this time we will use Hudi to Z-Order by product_id, customer_idcolumns tuple instead of Clustering or <em>linear ordering</em>.</p><p>No special preparations are required for the dataset, you can simply download it from <a href="https://s3.amazonaws.com/amazon-reviews-pds/readme.html">S3</a> in Parquet format and use it directly as an input for Spark ingesting it into Hudi table.</p><p>Launch Spark Shell</p><pre>./bin/spark-shell --master &#39;local[4]&#39; --driver-memory 8G --executor-memory 8G \<br>  --jars ../../packaging/hudi-spark-bundle/target/hudi-spark3-bundle_2.12-0.10.0.jar \<br>  --packages org.apache.spark:spark-avro_2.12:2.4.4 \<br>  --conf &#39;spark.serializer=org.apache.spark.serializer.KryoSerializer&#39;</pre><p>Paste</p><pre>import org.apache.hadoop.fs.{FileStatus, Path}<br>import scala.collection.JavaConversions._<br>import org.apache.spark.sql.SaveMode._<br>import org.apache.hudi.{DataSourceReadOptions, DataSourceWriteOptions}<br>import org.apache.hudi.DataSourceWriteOptions._<br>import org.apache.hudi.common.fs.FSUtils<br>import org.apache.hudi.common.table.HoodieTableMetaClient<br>import org.apache.hudi.common.util.ClusteringUtils<br>import org.apache.hudi.config.HoodieClusteringConfig<br>import org.apache.hudi.config.HoodieWriteConfig._<br>import org.apache.spark.sql.DataFrame<br></pre><pre>import java.util.stream.Collectors<br></pre><pre>val layoutOptStrategy = &quot;z-order&quot;; // OR &quot;hilbert&quot;<br></pre><pre>val inputPath = s&quot;file:///${System.getProperty(&quot;user.home&quot;)}/datasets/amazon_reviews_parquet&quot;<br>val tableName = s&quot;amazon_reviews_${layoutOptStrategy}&quot;<br>val outputPath = s&quot;file:///tmp/hudi/$tableName&quot;<br></pre><pre>def safeTableName(s: String) = s.replace(&#39;-&#39;, &#39;_&#39;)<br></pre><pre>val commonOpts =<br>  Map(<br>    &quot;hoodie.compact.inline&quot; -&gt; &quot;false&quot;,<br>    &quot;hoodie.bulk_insert.shuffle.parallelism&quot; -&gt; &quot;10&quot;<br>  )<br></pre><pre>////////////////////////////////////////////////////////////////<br>// Writing to Hudi<br>////////////////////////////////////////////////////////////////<br></pre><pre>val df = spark.read.parquet(inputPath)<br></pre><pre>df.write.format(&quot;hudi&quot;)<br>  .option(DataSourceWriteOptions.TABLE_TYPE.key(), COW_TABLE_TYPE_OPT_VAL)<br>  .option(&quot;hoodie.table.name&quot;, tableName)<br>  .option(PRECOMBINE_FIELD.key(), &quot;review_id&quot;)<br>  .option(RECORDKEY_FIELD.key(), &quot;review_id&quot;)<br>  .option(DataSourceWriteOptions.PARTITIONPATH_FIELD.key(), &quot;product_category&quot;)<br>  .option(&quot;hoodie.clustering.inline&quot;, &quot;true&quot;)<br>  .option(&quot;hoodie.clustering.inline.max.commits&quot;, &quot;1&quot;)<br>  // NOTE: Small file limit is intentionally kept _ABOVE_ target file-size max threshold for Clustering,<br>  // to force re-clustering<br>  .option(&quot;hoodie.clustering.plan.strategy.small.file.limit&quot;, String.valueOf(1024 * 1024 * 1024)) // 1Gb<br>  .option(&quot;hoodie.clustering.plan.strategy.target.file.max.bytes&quot;, String.valueOf(128 * 1024 * 1024)) // 128Mb<br>  // NOTE: We&#39;re increasing cap on number of file-groups produced as part of the Clustering run to be able to accommodate for the <br>  // whole dataset (~33Gb)<br>  .option(&quot;hoodie.clustering.plan.strategy.max.num.groups&quot;, String.valueOf(4096))<br>  .option(HoodieClusteringConfig.LAYOUT_OPTIMIZE_ENABLE.key, &quot;true&quot;)<br>  .option(HoodieClusteringConfig.LAYOUT_OPTIMIZE_STRATEGY.key, layoutOptStrategy)<br>  .option(HoodieClusteringConfig.PLAN_STRATEGY_SORT_COLUMNS.key, &quot;product_id,customer_id&quot;)<br>  .option(DataSourceWriteOptions.OPERATION.key(), DataSourceWriteOptions.BULK_INSERT_OPERATION_OPT_VAL)<br>  .option(BULK_INSERT_SORT_MODE.key(), &quot;NONE&quot;)<br>  .options(commonOpts)<br>  .mode(ErrorIfE</pre><h3>Testing</h3><p>Please keep in mind, that each individual test is run in a separate spark-shell to avoid caching getting in the way of our measurements.</p><pre>////////////////////////////////////////////////////////////////<br>// Reading<br>///////////////////////////////////////////////////////////////<br></pre><pre>// Temp Table w/ Data Skipping DISABLED<br>val readDf: DataFrame =<br>  spark.read.option(DataSourceReadOptions.ENABLE_DATA_SKIPPING.key(), &quot;false&quot;).format(&quot;hudi&quot;).load(outputPath)<br></pre><pre>val rawSnapshotTableName = safeTableName(s&quot;${tableName}_sql_snapshot&quot;)<br></pre><pre>readDf.createOrReplaceTempView(rawSnapshotTableName)<br></pre><pre>// Temp Table w/ Data Skipping ENABLED<br>val readDfSkip: DataFrame =<br>  spark.read.option(DataSourceReadOptions.ENABLE_DATA_SKIPPING.key(), &quot;true&quot;).format(&quot;hudi&quot;).load(outputPath)<br></pre><pre>val dataSkippingSnapshotTableName = safeTableName(s&quot;${tableName}_sql_snapshot_skipping&quot;)<br></pre><pre>readDfSkip.createOrReplaceTempView(dataSkippingSnapshotTableName)<br></pre><pre>// Query 1: Total votes by product_category, for 6 months<br>def runQuery1(tableName: String) = {<br>  // Query 1: Total votes by product_category, for 6 months<br>  spark.sql(s&quot;SELECT sum(total_votes), product_category FROM $tableName WHERE review_date &gt; &#39;2013-12-15&#39; AND review_date &lt; &#39;2014-06-01&#39; GROUP BY product_category&quot;).show()<br>}<br></pre><pre>// Query 2: Average star rating by product_id, for some product<br>def runQuery2(tableName: String) = {<br>  spark.sql(s&quot;SELECT avg(star_rating), product_id FROM $tableName WHERE product_id in (&#39;B0184XC75U&#39;) GROUP BY product_id&quot;).show()<br>}<br></pre><pre>// Query 3: Count number of reviews by customer_id for some 5 customers<br>def runQuery3(tableName: String) = {<br>  spark.sql(s&quot;SELECT count(*) as num_reviews, customer_id FROM $tableName WHERE customer_id in (&#39;53096570&#39;,&#39;10046284&#39;,&#39;53096576&#39;,&#39;10000196&#39;,&#39;21700145&#39;) GROUP BY customer_id&quot;).show()<br>}<br></pre><pre>//<br>// Query 1: Is a &quot;wide&quot; query and hence it&#39;s expected to touch a lot of files<br>//<br>scala&gt; runQuery1(rawSnapshotTableName)<br>+----------------+--------------------+<br>|sum(total_votes)|    product_category|<br>+----------------+--------------------+<br>|         1050944|                  PC|<br>|          867794|             Kitchen|<br>|         1167489|                Home|<br>|          927531|            Wireless|<br>|            6861|               Video|<br>|           39602| Digital_Video_Games|<br>|          954924|Digital_Video_Dow...|<br>|           81876|             Luggage|<br>|          320536|         Video_Games|<br>|          817679|              Sports|<br>|           11451|  Mobile_Electronics|<br>|          228739|  Home_Entertainment|<br>|         3769269|Digital_Ebook_Pur...|<br>|          252273|                Baby|<br>|          735042|             Apparel|<br>|           49101|    Major_Appliances|<br>|          484732|             Grocery|<br>|          285682|               Tools|<br>|          459980|         Electronics|<br>|          454258|            Outdoors|<br>+----------------+--------------------+<br>only showing top 20 rows<br></pre><pre>scala&gt; runQuery1(dataSkippingSnapshotTableName)<br>+----------------+--------------------+<br>|sum(total_votes)|    product_category|<br>+----------------+--------------------+<br>|         1050944|                  PC|<br>|          867794|             Kitchen|<br>|         1167489|                Home|<br>|          927531|            Wireless|<br>|            6861|               Video|<br>|           39602| Digital_Video_Games|<br>|          954924|Digital_Video_Dow...|<br>|           81876|             Luggage|<br>|          320536|         Video_Games|<br>|          817679|              Sports|<br>|           11451|  Mobile_Electronics|<br>|          228739|  Home_Entertainment|<br>|         3769269|Digital_Ebook_Pur...|<br>|          252273|                Baby|<br>|          735042|             Apparel|<br>|           49101|    Major_Appliances|<br>|          484732|             Grocery|<br>|          285682|               Tools|<br>|          459980|         Electronics|<br>|          454258|            Outdoors|<br>+----------------+--------------------+<br>only showing top 20 rows<br></pre><pre>//<br>// Query 2: Is a &quot;pointwise&quot; query and hence it&#39;s expected that data-skipping should substantially reduce number <br>// of files scanned (as compared to Baseline)<br>//<br>// NOTE: That Linear Ordering (as compared to Space-curve based on) will have similar effect on performance reducing<br>// total # of Parquet files scanned, since we&#39;re querying on the prefix of the ordering key<br>//<br>scala&gt; runQuery2(rawSnapshotTableName)<br>+----------------+----------+<br>|avg(star_rating)|product_id|<br>+----------------+----------+<br>|             1.0|B0184XC75U|<br>+----------------+----------+<br></pre><pre>scala&gt; runQuery2(dataSkippingSnapshotTableName)<br>+----------------+----------+<br>|avg(star_rating)|product_id|<br>+----------------+----------+<br>|             1.0|B0184XC75U|<br>+----------------+----------+<br></pre><pre>//<br>// Query 3: Similar to Q2, is a &quot;pointwise&quot; query, but querying other part of the ordering-key (product_id, customer_id)<br>// and hence it&#39;s expected that data-skipping should substantially reduce number of files scanned (as compared to Baseline, Linear Ordering).<br>//<br>// NOTE: That Linear Ordering (as compared to Space-curve based on) will _NOT_ have similar effect on performance reducing<br>// total # of Parquet files scanned, since we&#39;re NOT querying on the prefix of the ordering key<br>//<br>scala&gt; runQuery3(rawSnapshotTableName)<br>+-----------+-----------+<br>|num_reviews|customer_id|<br>+-----------+-----------+<br>|         50|   53096570|<br>|          3|   53096576|<br>|         25|   10046284|<br>|          1|   10000196|<br>|         14|   21700145|<br>+-----------+-----------+<br></pre><pre>scala&gt; runQuery3(dataSkippingSnapshotTableName)<br>+-----------+-----------+<br>|num_reviews|customer_id|<br>+-----------+-----------+<br>|         50|   53096570|<br>|          3|   53096576|<br>|         25|   10046284|<br>|          1|   10000196|<br>|         14|   21700145|<br>+---</pre><h3>Results</h3><p>We’ve summarized the measured performance metrics below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VR3rUfmKf-WzJOdNlztUdA.png" /></figure><p>As you can see multi-column linear ordering is not very effective for the queries that do filtering by columns other than the first one (Q2, Q3).</p><p>Which is a very clear contrast with space-filling curves (both Z-order and Hilbert) that allow to speed up query time by up to <strong>3x!</strong></p><p>It’s worth noting that the performance gains are heavily dependent on your underlying data and queries. In benchmarks on our internal data we were able to achieve queries performance improvements of more than <strong>11x!</strong></p><h3>Epilogue</h3><p>Apache Hudi v0.10 brings new layout optimization capabilities Z-order and Hilbert to open source. Using these industry leading layout optimization techniques can bring substantial performance improvement and cost savings to your queries!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68fa28bffaf0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/apache-hudi-blogs/hudi-z-order-and-hilbert-space-filling-curves-68fa28bffaf0">Hudi Z-Order and Hilbert Space-filling Curves</a> was originally published in <a href="https://medium.com/apache-hudi-blogs">apache-hudi-blogs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lakehouse Concurrency Control: Are we too optimistic?]]></title>
            <link>https://medium.com/apache-hudi-blogs/lakehouse-concurrency-control-are-we-too-optimistic-1b1f6654feab?source=rss----464bbeff5499---4</link>
            <guid isPermaLink="false">https://medium.com/p/1b1f6654feab</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[data-lakehouse]]></category>
            <category><![CDATA[data-warehousing]]></category>
            <dc:creator><![CDATA[Kyle Weller]]></dc:creator>
            <pubDate>Fri, 17 Dec 2021 01:46:32 GMT</pubDate>
            <atom:updated>2021-12-17T16:55:28.271Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This is a repost of a blog from Apache Hudi </em><a href="https://hudi.apache.org/blog/2021/12/16/lakehouse-concurrency-control-are-we-too-optimistic"><em>linked here</em></a><em>. <br></em><strong><em>Author:</em></strong><em> Vinoth Chandar</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*yYJhU03XtzE3WRECqT4o-g.jpeg" /></figure><p>Transactions on data lakes are now considered a key characteristic of a Lakehouse these days. But what has actually been accomplished so far? What are the current approaches? How do they fare in real-world scenarios? These questions are the focus of this blog.</p><p>Having had the good fortune of working on diverse database projects — an RDBMS (<a href="https://www.oracle.com/database/">Oracle</a>), a NoSQL key-value store (<a href="https://www.slideshare.net/vinothchandar/voldemort-prototype-to-production-nectar-edits">Voldemort</a>), a streaming database (<a href="https://www.confluent.io/blog/ksqldb-pull-queries-high-availability/">ksqlDB</a>), a closed-source real-time datastore and of course, Apache Hudi, I can safely say that the nature of workloads deeply influence the concurrency control mechanisms adopted in different databases. This blog will also describe how we rethought concurrency control for the data lake in Apache Hudi.</p><p>First, let’s set the record straight. RDBMS databases offer the richest set of transactional capabilities and the widest array of concurrency control <a href="https://dev.mysql.com/doc/refman/5.7/en/innodb-locking-transaction-model.html">mechanisms</a>. Different isolation levels, fine grained locking, deadlock detection/avoidance, and more are possible because they have to support row-level mutations and reads across many tables while enforcing <a href="https://dev.mysql.com/doc/refman/8.0/en/create-table-foreign-keys.html">key constraints</a> and maintaining <a href="https://dev.mysql.com/doc/refman/8.0/en/create-table-secondary-indexes.html">indexes</a>. NoSQL stores offer dramatically weaker guarantees like eventual-consistency and simple row level atomicity in exchange for greater scalability for simpler workloads. Drawing a similar parallel, traditional data warehouses offer more or less the full set of capabilities that you would find in an RDBMS, over columnar data, with locking and key constraints <a href="https://docs.teradata.com/r/a8IdS6iVHR77Z9RrIkmMGg/wFPZS4jwZgSG21GnOIpEsw">enforced</a> whereas cloud data warehouses seem to have focused a lot more on separating the data and compute in architecture, while offering fewer isolation levels. As a surprising example, <a href="https://docs.snowflake.com/en/sql-reference/constraints-overview.html#supported-constraint-types">no enforcement</a> of key constraints!</p><h3>Pitfalls and Lake Concurrency Control</h3><p>Historically, data lakes have been viewed as batch jobs reading/writing files on cloud storage and it’s interesting to see how most new work extends this view and implements glorified file version control using some form of “<a href="https://en.wikipedia.org/wiki/Optimistic_concurrency_control"><strong>Optimistic concurrency control</strong></a>” (OCC). With OCC jobs take a table level lock to check if they have impacted overlapping files and if a conflict exists, they abort their operations completely. Without naming names, the lock is sometimes even just a JVM level lock held on a single Apache Spark driver node. Once again, this may be okay for lightweight coordination of old school batch jobs that mostly append files to tables, but cannot be applied broadly to modern data lake workloads. Such approaches are built with immutable/append-only data models in mind, which are inadequate for incremental data processing or keyed updates/deletes. OCC is very optimistic that real contention never happens. Developer evangelism comparing OCC to the full fledged transactional capabilities of an RDBMS or a traditional data warehouse is rather misinformed. Quoting Wikipedia directly — “ <em>if contention for data resources is frequent, the cost of repeatedly restarting transactions hurts performance significantly, in which case other</em> <a href="https://en.wikipedia.org/wiki/Concurrency_control"><em>concurrency control</em></a> <em>methods may be better suited.</em> “ When conflicts do occur, they can cause massive resource wastage since you have a batch job that fails after it ran for a few hours, during every attempt!</p><p>Imagine a real-life scenario of two writer processes : an ingest writer job producing new data every 30 minutes and a deletion writer job that is enforcing GDPR, taking 2 hours to issue deletes. It’s very likely for these to overlap files with random deletes, and the deletion job is almost guaranteed to starve and fail to commit each time. In database speak, mixing long running transactions with optimism leads to disappointment, since the longer the transactions the higher the probability they will overlap.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2JIkmPiMrBAhkKMjex2h8A.png" /></figure><p>So, what’s the alternative? Locking? Wikipedia also says — “ <em>However, locking-based (“pessimistic”) methods also can deliver poor performance because locking can drastically limit effective concurrency even when deadlocks are avoided.”.</em> Here is where Hudi takes a different approach, that we believe is more apt for modern lake transactions which are typically long-running and even continuous. Data lake workloads share more characteristics with high throughput stream processing jobs, than they do to standard reads/writes from a database and this is where we build strength. In stream processing events are serialized into a single ordered log, avoiding any locks/concurrency bottlenecks and you can continuously process millions of events/sec. Hudi implements a file level, log based concurrency control protocol on the Hudi <a href="https://hudi.apache.org/docs/timeline">timeline</a>, which in-turn relies on bare minimum atomic puts to cloud storage. By building on an event log as the central piece for inter process coordination, Hudi is able to offer a few flexible deployment models that offer greater concurrency over pure OCC approaches.</p><h3>Model 1: Single Writer, Inline Table Services</h3><p>The simplest form of concurrency control is just no concurrency at all. A data lake table often has common services operating on it to ensure efficiency. Reclaiming storage space from older versions and logs, coalescing files (clustering in Hudi), merging deltas (compactions in Hudi), and more. Hudi can simply eliminate the need for concurrency control and maximizes throughput by supporting these table services out-of-box and running inline after every write to the table.</p><p>Execution plans are idempotent, persisted to the timeline and auto-recover from failures. For most simple use-cases, this means just writing is sufficient to get a well-managed table that needs no concurrency control.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wRhy6e-30-TYCxfsl7E6xA.gif" /></figure><h3>Model 2: Single Writer, Async Table Services</h3><p>Our delete/ingest example above is n’t really that simple. While ingest/writer may just be updating the last N partitions on the table, delete may span across the entire table even. Mixing them in the same job, could slow down ingest latency by a lot. But, Hudi provides the option of running the table services in an async fashion, where most of the heavy lifting (e.g actually rewriting the columnar data by compaction service) is done asynchronously, eliminating any repeated wasteful retries whatsoever, while also optimizing the table using clustering techniques. Thus a single writer could consumes both regular updates and GDPR deletes and serialize them into a log. Given Hudi has record level indexing and avro log writes are much cheaper (as opposed to writing parquet, which can be 10x or more expensive), ingest latency can be sustained while enjoying great replayability. In fact, we were able to scale this model at <a href="https://eng.uber.com/uber-big-data-platform/">Uber</a>, across 100s of petabytes, by sequencing all deletes &amp; updates into the same source Apache Kafka topic. There’s more to concurrency control than locking and Hudi accomplishes all this without needing any external locking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jaOM-9PcP8thdAyFVjFI-Q.gif" /></figure><h3>Model 3: Multiple Writers</h3><p>But it’s not always possible to serialize the deletes into the same write stream or sql based deletes are required. With multiple distributed processes, some form of locking is inevitable, but like real databases Hudi’s concurrency model is intelligent enough to differentiate actual writing to the table, from table services that manage or optimize the table. Hudi offers similar optimistic concurrency control across multiple writers, but table services can still execute completely lock-free and async. This means the delete job can merely encode deletes and the ingest job can log updates, while the compaction service again applies the updates/deletes to base files. Even though the delete job and ingest job can contend and starve each other like like we mentioned above, their run-times are much lower and the wastage is drastically lower, since the compaction does the heavy-lifting of parquet/columnar data writing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8LcUaTgEhW9aN9-xi5w1lQ.gif" /></figure><p>All this said, there are still many ways we can improve upon this foundation.</p><ul><li>For starters, Hudi has already implemented a <a href="https://hudi.apache.org/blog/2021/08/18/improving-marker-mechanism/">marker mechanism</a> that tracks all the files that are part of an active write transaction and a heartbeat mechanism that can track active writers to a table. This can be directly used by other active transactions/writers to detect what other writers are doing and <a href="https://issues.apache.org/jira/browse/HUDI-1575">abort early</a> if conflicts are detected, yielding the cluster resources back to other jobs sooner.</li><li>While optimistic concurrency control is attractive when serializable snapshot isolation is desired, it’s neither optimal nor the only method for dealing with concurrency between writers. We plan to implement a fully lock-free concurrency control using CRDTs and widely adopted stream processing concepts, over our log <a href="https://github.com/apache/hudi/blob/bc8bf043d5512f7afbb9d94882c4e43ee61d6f06/hudi-common/src/main/java/org/apache/hudi/common/model/HoodieRecordPayload.java#L38">merge API</a>, that has already been <a href="https://hudi.apache.org/blog/2021/09/01/building-eb-level-data-lake-using-hudi-at-bytedance/#functionality-support">proven</a> to sustain enormous continuous write volumes for the data lake.</li><li>Touching upon key constraints, Hudi is the only lake transactional layer that ensures unique <a href="https://hudi.apache.org/docs/key_generation">key</a> constraints today, but limited to the record key of the table. We will be looking to expand this capability in a more general form to non-primary key fields, with the said newer concurrency models.</li></ul><p>Finally, for data lakes to transform successfully into lakehouses, we must learn from the failing of the “hadoop warehouse” vision, which shared similar goals with the new “lakehouse” vision. Designers did not pay closer attention to the missing technology gaps against warehouses and created unrealistic expectations from the actual software. As transactions and database functionality finally goes mainstream on data lakes, we must apply these lessons and remain candid about the current shortcomings. If you are building a lakehouse, I hope this post encourages you to closely consider various operational and efficiency aspects around concurrency control. Join our fast growing community by trying out <a href="https://hudi.apache.org/docs/overview">Apache Hudi</a> or join us in conversations on <a href="https://join.slack.com/t/apache-hudi/shared_invite/enQtODYyNDAxNzc5MTg2LTE5OTBlYmVhYjM0N2ZhOTJjOWM4YzBmMWU2MjZjMGE4NDc5ZDFiOGQ2N2VkYTVkNzU3ZDQ4OTI1NmFmYWQ0NzE">Slack</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b1f6654feab" width="1" height="1" alt=""><hr><p><a href="https://medium.com/apache-hudi-blogs/lakehouse-concurrency-control-are-we-too-optimistic-1b1f6654feab">Lakehouse Concurrency Control: Are we too optimistic?</a> was originally published in <a href="https://medium.com/apache-hudi-blogs">apache-hudi-blogs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reliable ingestion from AWS S3 using Hudi]]></title>
            <link>https://medium.com/apache-hudi-blogs/reliable-ingestion-from-aws-s3-using-hudi-b7d5590c78a9?source=rss----464bbeff5499---4</link>
            <guid isPermaLink="false">https://medium.com/p/b7d5590c78a9</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[apache-hudi]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[analytics]]></category>
            <dc:creator><![CDATA[Vinoth Chandar]]></dc:creator>
            <pubDate>Thu, 02 Sep 2021 15:10:08 GMT</pubDate>
            <atom:updated>2021-09-02T15:10:08.783Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post we will talk about a new deltastreamer source which reliably and efficiently processes new data files as they arrive in AWS S3</p><blockquote>This is a repost of the original Hudi blog <a href="https://hudi.apache.org/blog/2021/08/23/s3-events-source/">here</a>.</blockquote><p>As of today, to ingest data from S3 into Hudi, users leverage DFS source whose <a href="https://github.com/apache/hudi/blob/178767948e906f673d6d4a357c65c11bc574f619/hudi-utilities/src/main/java/org/apache/hudi/utilities/sources/helpers/DFSPathSelector.java">path selector</a> would identify the source files modified since the last checkpoint based on max modification time. The problem with this approach is that modification time precision is upto seconds in S3. It maybe possible that there were many files (beyond what the configurable source limit allows) modifed in that second and some files might be skipped. For more details, please refer to <a href="https://issues.apache.org/jira/browse/HUDI-1723">HUDI-1723</a>. While the workaround is to ignore the source limit and keep reading, the problem motivated us to redesign so that users can reliably ingest from S3.</p><h3>Design</h3><p>For use-cases where seconds granularity does not suffice, we have a new source in deltastreamer using log-based approach. The new <a href="https://github.com/apache/hudi/blob/178767948e906f673d6d4a357c65c11bc574f619/hudi-utilities/src/main/java/org/apache/hudi/utilities/sources/S3EventsSource.java">S3 events source</a> relies on change notification and incremental processing to ingest from S3. The architecture is as shown in the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/0*kEYB2o6CuKx2tcWj.png" /></figure><p>In this approach, users need to <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/NotificationHowTo.html">enable S3 event notifications</a>. There will be two types of deltastreamers as detailed below.</p><ol><li><a href="https://github.com/apache/hudi/blob/178767948e906f673d6d4a357c65c11bc574f619/hudi-utilities/src/main/java/org/apache/hudi/utilities/sources/S3EventsSource.java">S3EventsSource</a>: Create Hudi S3 metadata table. This source leverages AWS <a href="https://aws.amazon.com/sns">SNS</a> and <a href="https://aws.amazon.com/sqs/">SQS</a> services that subscribe to file events from the source bucket.</li></ol><ul><li>Events from SQS will be written to this table, which serves as a changelog for the subsequent incremental puller.</li><li>When the events are committed to the S3 metadata table they will be deleted from SQS.</li></ul><p><a href="https://github.com/apache/hudi/blob/178767948e906f673d6d4a357c65c11bc574f619/hudi-utilities/src/main/java/org/apache/hudi/utilities/sources/S3EventsHoodieIncrSource.java">2. S3EventsHoodieIncrSource</a> and uses the metadata table written by S3EventsSource.</p><ul><li>Read the S3 metadata table and get the objects that were added or modified. These objects contain the S3 path for the source files that were added or modified.</li><li>Write to Hudi table with source data corresponding to the source files in the S3 bucket.</li></ul><h3>Advantages</h3><ul><li><strong>Decoupling</strong>: Every step in the pipeline is decoupled. The two sources can be started independent of each other. We imagine most users run a single deltastreamer to get all changes for a given bucket and can fan-out multiple tables off that.</li><li><strong>Performance and Scale</strong>: The previous approach used to list all files, sort by modification time and then filter based on checkpoint. While it did prune partition paths, the directory listing could still become a bottleneck. By relying on change notification and native cloud APIs, the new approach avoids directory listing and scales with the number of files being ingested.</li><li><strong>Reliability</strong>: Since there is no longer any dependency on the max modification time and the fact that S3 events are being recorded in the metadata table, users can rest assured that all the events will be processed eventually.</li><li><strong>Fault Tolerance:</strong> There are two levels of fault toerance in this design. Firstly, if some of the messages are not committed to the S3 metadata table, then those messages will remain in the queue so that they can be reprocessed in the next round. Secondly, if the incremental puller fails, then users can query the S3 metadata table for the last commit point and resume the incremental puller from that point onwards (kinda like how Kafka consumers can reset offset).</li><li><strong>Asynchronous backfills:</strong> With the log-based approach, it becomes much easier to trigger backfills. See the “Conclusion and Future Work” section for more details.</li></ul><h3>Configuration and Setup</h3><p>Users only need to specify the SQS queue url and region name to start the S3EventsSource (metadata source).</p><pre>hoodie.deltastreamer.s3.source.queue.url=https://sqs.us-west-2.amazonaws.com/queue/url<br>hoodie.deltastreamer.s3.source.queue.region=us-west-2</pre><p>There are a few other configurations for the metadata source which can be tuned to suit specific requirements:</p><ul><li><em>hoodie.deltastreamer.s3.source.queue.long.poll.wait</em>: Value can range in [0, 20] seconds. If set to 0 then metadata source will consume messages from SQS using short polling. It is recommended to use long polling because it will reduce false empty responses and reduce the cost of using SQS. By default, this value is set to 20 seconds.</li><li><em>hoodie.deltastreamer.s3.source.queue.visibility.timeout</em>: Value can range in [0, 43200] seconds (i.e. max 12 hours). SQS does not automatically delete the messages once consumed. It is the responsibility of metadata source to delete the message after committing. SQS will move the consumed message to in-flight state during which it becomes invisible for the configured timeout period. By default, this value is set to 30 seconds.</li><li><em>hoodie.deltastreamer.s3.source.queue.max.messages.per.batch</em>: Maximum number of messages in a batch of one round of metadata source run. By default, this value is set to 5.</li></ul><p>To setup the pipeline, first <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/NotificationHowTo.html">enable S3 event notifications</a>. Download the <a href="https://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk-sqs">aws-java-sdk-sqs</a> jar. Then start the S3EventsSource and S3EventsHoodieIncrSource using the HoodieDeltaStreamer utility as shown in sample commands below.</p><pre># To start S3EventsSource<br>spark-submit \<br>--jars &quot;/home/hadoop/hudi-utilities-bundle_2.11-0.9.0.jar,/usr/lib/spark/external/lib/spark-avro.jar,/home/hadoop/aws-java-sdk-sqs-1.12.22.jar&quot; \<br>--master yarn --deploy-mode client \<br>--class org.apache.hudi.utilities.deltastreamer.HoodieDeltaStreamer /home/hadoop/hudi-packages/hudi-utilities-bundle_2.11-0.9.0-SNAPSHOT.jar \<br>--table-type COPY_ON_WRITE --source-ordering-field eventTime \<br>--target-base-path s3://bucket_name/path/for/s3_meta_table \<br>--target-table s3_meta_table  --continuous \<br>--min-sync-interval-seconds 10 \<br>--hoodie-conf hoodie.datasource.write.recordkey.field=&quot;s3.object.key,eventName&quot; \<br>--hoodie-conf hoodie.datasource.write.keygenerator.class=org.apache.hudi.keygen.ComplexKeyGenerator \<br>--hoodie-conf hoodie.datasource.write.partitionpath.field=s3.bucket.name --enable-hive-sync \<br>--hoodie-conf hoodie.datasource.hive_sync.partition_extractor_class=org.apache.hudi.hive.MultiPartKeysValueExtractor \<br>--hoodie-conf hoodie.datasource.write.hive_style_partitioning=true \<br>--hoodie-conf hoodie.datasource.hive_sync.database=default \<br>--hoodie-conf hoodie.datasource.hive_sync.table=s3_meta_table \<br>--hoodie-conf hoodie.datasource.hive_sync.partition_fields=bucket \<br>--source-class org.apache.hudi.utilities.sources.S3EventsSource \<br>--hoodie-conf hoodie.deltastreamer.source.queue.url=<a href="https://sqs.us-west-2.amazonaws.com/queue/url">https://sqs.us-west-2.amazonaws.com/queue/url</a><br>--hoodie-conf hoodie.deltastreamer.s3.source.queue.region=us-west-2</pre><pre># To start S3EventsHoodieIncrSource<br>spark-submit \<br>--jars &quot;/home/hadoop/hudi-utilities-bundle_2.11-0.9.0.jar,/usr/lib/spark/external/lib/spark-avro.jar,/home/hadoop/aws-java-sdk-sqs-1.12.22.jar&quot; \<br>--master yarn --deploy-mode client \<br>--class org.apache.hudi.utilities.deltastreamer.HoodieDeltaStreamer /home/hadoop/hudi-packages/hudi-utilities-bundle_2.11-0.9.0-SNAPSHOT.jar \<br>--table-type COPY_ON_WRITE \<br>--source-ordering-field eventTime --target-base-path s3://bucket_name/path/for/s3_hudi_table \<br>--target-table s3_hudi_table  --continuous --min-sync-interval-seconds 10 \<br>--hoodie-conf hoodie.datasource.write.recordkey.field=&quot;pull_request_id&quot; \<br>--hoodie-conf hoodie.datasource.write.keygenerator.class=org.apache.hudi.keygen.SimpleKeyGenerator \<br>--hoodie-conf hoodie.datasource.write.partitionpath.field=s3.bucket.name --enable-hive-sync \<br>--hoodie-conf hoodie.datasource.hive_sync.partition_extractor_class=org.apache.hudi.hive.MultiPartKeysValueExtractor \<br>--hoodie-conf hoodie.datasource.write.hive_style_partitioning=true \<br>--hoodie-conf hoodie.datasource.hive_sync.database=default \<br>--hoodie-conf hoodie.datasource.hive_sync.table=s3_hudi_v6 \<br>--hoodie-conf hoodie.datasource.hive_sync.partition_fields=bucket \<br>--source-class org.apache.hudi.utilities.sources.S3EventsHoodieIncrSource \<br>--hoodie-conf hoodie.deltastreamer.source.hoodieincr.path=s3://bucket_name/path/for/s3_meta_table \<br>--hoodie-conf hoodie.deltastreamer.source.hoodieincr.read_latest_on_missing_ckpt=true</pre><h3>Conclusion and Future Work</h3><ul><li>One stream of work is to add support for other cloud-based object storage like Google Cloud Storage, Azure Blob Storage, etc. with this revamped design.</li><li>Another stream of work is to add resource manager that allows users to setup notifications and delete resources when no longer needed.</li><li>Another interesting piece of work is to support asynchronous backfills. Notification systems are evntually consistent and typically do not guarantee perfect delivery of all files right away. The log-based approach provides enough flexibility to trigger automatic backfills at a configurable interval e.g. once a day or once a week.</li></ul><p>Please follow this <a href="https://issues.apache.org/jira/browse/HUDI-1896">JIRA</a> to learn more about active development on this issue. We look forward to contributions from the community. Hope you enjoyed this post.</p><p>Put your Hudi on and keep streaming!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7d5590c78a9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/apache-hudi-blogs/reliable-ingestion-from-aws-s3-using-hudi-b7d5590c78a9">Reliable ingestion from AWS S3 using Hudi</a> was originally published in <a href="https://medium.com/apache-hudi-blogs">apache-hudi-blogs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apache Hudi — The Streaming Data Lake Platform]]></title>
            <link>https://medium.com/apache-hudi-blogs/apache-hudi-the-streaming-data-lake-platform-5964468678a4?source=rss----464bbeff5499---4</link>
            <guid isPermaLink="false">https://medium.com/p/5964468678a4</guid>
            <category><![CDATA[apache-hudi]]></category>
            <category><![CDATA[stream-processing]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Vinoth Chandar]]></dc:creator>
            <pubDate>Tue, 27 Jul 2021 15:41:17 GMT</pubDate>
            <atom:updated>2021-08-06T14:38:18.560Z</atom:updated>
            <content:encoded><![CDATA[<h3>Apache Hudi — The Streaming Data Lake Platform</h3><blockquote>This blog is a repost of the original blog <a href="https://hudi.apache.org/blog/2021/07/21/streaming-data-lake-platform">here</a></blockquote><p>As early as 2016, we set out a <a href="https://www.oreilly.com/content/ubers-case-for-incremental-processing-on-hadoop/">bold, new vision</a> reimagining batch data processing through a new “<strong>incremental</strong>” data processing stack — alongside the existing batch and streaming stacks. While a stream processing pipeline does row-oriented processing, delivering a few seconds of processing latency, an incremental pipeline would apply the same principles to <em>columnar</em> data in the data lake, delivering orders of magnitude improvements in processing efficiency within few minutes, on extremely scalable batch storage/compute infrastructure. This new stack would be able to effortlessly support regular batch processing for bulk reprocessing/backfilling as well. Hudi was built as the manifestation of this vision, rooted in real, hard problems faced at <a href="https://eng.uber.com/uber-big-data-platform/">Uber</a> and later took a life of its own in the open source community. Together, we have been able to usher in fully incremental data ingestion and moderately complex ETLs on data lakes already.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jhooS2MCbjBZ09H7.png" /></figure><p>Today, this grand vision of being able to express almost any batch pipeline incrementally is more attainable than it ever was. Stream processing is <a href="https://flink.apache.org/blog/">maturing rapidly</a> and gaining <a href="https://www.confluent.io/blog/every-company-is-becoming-software/">tremendous momentum</a>, with <a href="https://flink.apache.org/2021/03/11/batch-execution-mode.html">generalization</a> of stream processing APIs to work over a batch execution model. Hudi completes the missing pieces of the puzzle by providing streaming optimized lake storage, much like how Kafka/Pulsar enable efficient storage for event streaming. <a href="https://hudi.apache.org/docs/powered_by.html">Many organizations</a> have already reaped real benefits of adopting a streaming model for their data lakes, in terms of fresh data, simplified architecture and great cost reductions.</p><p>But first, we needed to tackle the basics — transactions and mutability — on the data lake. In many ways, Apache Hudi pioneered the transactional data lake movement as we know it today. Specifically, during a time when more special-purpose systems were being born, Hudi introduced a server-less, transaction layer, which worked over the general-purpose Hadoop FileSystem abstraction on Cloud Stores/HDFS. This model helped Hudi to scale writers/readers to 1000s of cores on day one, compared to warehouses which offer a richer set of transactional guarantees but are often bottlenecked by the 10s of servers that need to handle them. We also experience a lot of joy to see similar systems (Delta Lake for e.g) later adopt the same server-less transaction layer model that we originally shared way back in <a href="https://eng.uber.com/hoodie/">early </a>’17. We consciously introduced two table types Copy On Write (with simpler operability) and Merge On Read (for greater flexibility) and now these terms are used in <a href="https://github.com/apache/iceberg/pull/1862">projects</a> outside Hudi, to refer to similar ideas being borrowed from Hudi. Through open sourcing and <a href="https://blogs.apache.org/foundation/entry/the-apache-software-foundation-announces64">graduating</a> from the Apache Incubator, we have made some great progress elevating these ideas <a href="http://hudi.apache.org/docs/powered_by.html">across the industry</a>, as well as bringing them to life with a cohesive software stack. Given the exciting developments in the past year or so that have propelled data lakes further mainstream, we thought some perspective can help users see Hudi with the right lens, appreciate what it stands for, and be a part of where it’s headed. At this time, we also wanted to shine some light on all the great work done by <a href="https://github.com/apache/hudi/graphs/contributors">180+ contributors</a> on the project, working with more than 2000 unique users over slack/github/jira, contributing all the different capabilities Hudi has gained over the past years, from its humble beginnings.</p><p>This is going to be a rather long post, but we will do our best to make it worth your time. Let’s roll.</p><h3>Data Lake Platform</h3><p>We have noticed that, Hudi is sometimes positioned as a “<a href="https://cloud.google.com/blog/products/data-analytics/getting-started-with-new-table-formats-on-dataproc">table format</a>” or “transactional layer”. While this is not incorrect, this does not do full justice to all that Hudi has to offer.</p><h3>Is Hudi a “format”?</h3><p>Hudi was not designed as a general purpose table format, tracking files/folders for batch processing. Rather, the functionality provided by a table format is merely one layer in the Hudi software stack. Hudi was designed to play well with the Hive format (if you will), given how popular and widespread it is. Over time, to solve scaling challenges or bring in additional functionality, we have invested in our own native table format with an eye for incremental processing vision. for e.g, we need to support shorter transactions that commit every few seconds. We believe these requirements would fully subsume challenges solved by general purpose table formats over time. But, we are also open to plugging in or syncing to other open table formats, so their users can also benefit from the rest of the Hudi stack. Unlike the file formats, a table format is merely a representation of table metadata and it’s actually quite possible to translate from Hudi to other formats/vice versa if users are willing to accept the trade-offs.</p><h3>Is Hudi a transactional layer?</h3><p>Of course, Hudi had to provide transactions for implementing deletes/updates, but Hudi’s transactional layer is designed around an <a href="https://engineering.linkedin.com/distributed-systems/log-what-every-software-engineer-should-know-about-real-time-datas-unifying">event log</a> that is also well-integrated with an entire set of built-in table/data services. For e.g compaction is aware of clustering actions already scheduled and optimizes by skipping over the files being clustered — while the user is blissfully unaware of all this. Hudi also provides out-of-box tools for ingesting, ETLing data, and much more. We have always been thinking of Hudi as solving a database problem around stream processing — areas that are actually <a href="https://www.infoq.com/presentations/streaming-databases/">very related to each other</a>. In fact, Stream processing is enabled by logs (capture/emit event streams, rewind/reprocess) and databases (state stores, updatable sinks). With Hudi, the idea was that if we build a database supporting efficient updates and extracting data streams while remaining optimized for large batch queries, incremental pipelines can be built using Hudi tables as state store &amp; update-able sinks.</p><p>Thus, the best way to describe Apache Hudi is as a <strong>Streaming Data Lake Platform</strong> built around a <em>database kernel</em>. The words carry significant meaning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*s1jqs8XrpaAU2fRI.png" /></figure><p><strong>Streaming</strong>: At its core, by optimizing for fast upserts &amp; change streams, Hudi provides the primitives to data lake workloads that are comparable to what <a href="https://kafka.apache.org/">Apache Kafka</a> does for event-streaming (namely, incremental produce/consume of events and a state-store for interactive querying).</p><p><strong>Data Lake</strong>: Nonetheless, Hudi provides an optimized, self-managing data plane for large scale data processing on the lake (adhoc queries, ML pipelines, batch pipelines), powering arguably the <a href="https://eng.uber.com/apache-hudi-graduation/">largest transactional lake</a> in the world. While Hudi can be used to build a <a href="https://databricks.com/blog/2020/01/30/what-is-a-data-lakehouse.html">lakehouse</a>, given its transactional capabilities, Hudi goes beyond and unlocks an end-to-end streaming architecture. In contrast, the word “streaming” appears just 3 times in the lakehouse <a href="http://cidrdb.org/cidr2021/papers/cidr2021_paper17.pdf">paper</a>, and one of them is talking about Hudi.</p><p><strong>Platform</strong>: Oftentimes in open source, there is great tech, but there is just too many of them — all differing ever so slightly in their opinionated ways, ultimately making the integration task onerous on the end user. Lake users deserve the same great usability that cloud warehouses provide, with the additional freedom and transparency of a true open source community. Hudi’s data and table services, tightly integrated with the Hudi “kernel”, gives us the ability to deliver cross layer optimizations with reliability and ease of use.</p><h3>Hudi Stack</h3><p>The following stack captures layers of software components that make up Hudi, with each layer depending on and drawing strength from the layer below. Typically, data lake users write data out once using an open file format like Apache <a href="http://parquet.apache.org/">Parquet</a>/<a href="https://orc.apache.org/">ORC</a> stored on top of extremely scalable cloud storage or distributed file systems. Hudi provides a self-managing data plane to ingest, transform and manage this data, in a way that unlocks incremental data processing on them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cED2arxdaU9s8bIC.png" /></figure><p>Furthermore, Hudi either already provides or plans to add components that make this data universally accessible to all the different query engines out there. The features annotated with * represent work in progress and dotted boxes represent planned future work, to complete our vision for the project. While we have strawman designs outlined for the newer components in the blog, we welcome with open arms fresh perspectives from the community. Rest of the blog will delve into each layer in our stack - explaining what it does, how it’s designed for incremental processing and how it will evolve in the future.</p><h3>Lake Storage</h3><p>Hudi interacts with lake storage using the <a href="https://hadoop.apache.org/docs/stable/api/org/apache/hadoop/fs/FileSystem.html">Hadoop FileSystem API</a>, which makes it compatible with all of its implementations ranging from HDFS to Cloud Stores to even in-memory filesystems like <a href="https://www.alluxio.io/blog/building-high-performance-data-lake-using-apache-hudi-and-alluxio-at-t3go/">Alluxio</a>/Ignite. Hudi internally implements its own <a href="https://github.com/apache/hudi/blob/9d2a65a6a6ff9add81411147f1cddd03f7c08e6c/hudi-common/src/main/java/org/apache/hudi/common/fs/HoodieWrapperFileSystem.java">wrapper filesystem</a> on top to provide additional storage optimizations (e.g: file sizing), performance optimizations (e.g: buffering), and metrics. Uniquely, Hudi takes full advantage of append support, for storage schemes that support it, like HDFS. This helps Hudi deliver streaming writes without causing an explosion in file counts/table metadata. Unfortunately, most cloud/object storages do not offer append capability today (except maybe <a href="https://azure.microsoft.com/en-us/updates/append-blob-support-in-azure-data-lake-storage-is-now-generally-available/">Azure</a>). In the future, we plan to leverage the lower-level APIs of major cloud object stores, to provide similar controls over file counts at streaming ingest latencies.</p><h3>File Format</h3><p>Hudi is designed around the notion of base file and delta log files that store updates/deltas to a given base file (called a file slice). Their formats are pluggable, with Parquet (columnar access) and HFile (indexed access) being the supported base file formats today. The delta logs encode data in <a href="http://avro.apache.org/">Avro</a> (row oriented) format for speedier logging (just like Kafka topics for e.g). Going forward, we plan to <a href="https://github.com/apache/hudi/pull/3228">inline any base file format</a> into log blocks in the coming releases, providing columnar access to delta logs depending on block sizes. Future plans also include Orc base/log file formats, unstructured data formats (free form json, images), and even tiered storage layers in event-streaming systems/OLAP engines/warehouses, work with their native file formats.</p><p>Zooming one level up, Hudi’s unique file layout scheme encodes all changes to a given base file, as a sequence of blocks (data blocks, delete blocks, rollback blocks) that are merged in order to derive newer base files. In essence, this makes up a self contained redo log that the lets us implement interesting features on top. For e.g, most of today’s data privacy enforcement happens by masking data read off the lake storage on-the-fly, invoking hashing/encryption algorithms over and over on the same set of records and incurring significant compute overhead/cost. Users would be able to keep multiple pre-masked/encrypted copies of the same key in the logs and hand out the correct one based on a policy, avoiding all the overhead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*p8F5BUnc8jVuQtTr.png" /></figure><h3>Table Format</h3><p>The term “table format” is new and still means many things to many people. Drawing an analogy to file formats, a table format simply consists of : the file layout of the table, table’s schema and metadata tracking changes to the table. Hudi is not a table format, it implements one internally. Hudi uses Avro schemas to store, manage and evolve a table’s schema. Currently, Hudi enforces schema-on-write, which although stricter than schema-on-read, is adopted <a href="https://docs.confluent.io/platform/current/schema-registry/avro.html">widely</a> in the stream processing world to ensure pipelines don’t break from non backwards compatible changes.</p><p>Hudi consciously lays out files within a table/partition into groups and maintains a mapping between an incoming record’s key to an existing file group. All updates are recorded into delta log files specific to a given file group and this design ensures low merge overhead compared to approaches like Hive ACID, which have to merge all delta records against all base files to satisfy queries. For e.g, with uuid keys (used very widely) all base files are very likely to overlap with all delta logs, rendering any range based pruning useless. Much like state stores, Hudi’s design anticipates fast key based upserts/deletes and only requires merging delta logs within each file group. This design choice also lets Hudi provide more capabilities for writing/querying as we will explain below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tHCOunFUL6zj60AE.png" /></figure><p>The <em>timeline</em> is the source-of-truth event log for all Hudi’s table metadata, stored under the .hoodie folder, that provides an ordered log of all actions performed on the table. Events are retained on the timeline up to a configured interval of time/activity. Each file group is also designed as it’s own self-contained log, which means that even if an action that affected a file group is archived from the timeline, the right state of the records in each file group can be reconstructed by simply locally applying the delta logs to the base file. This design bounds the metadata size, proportional to how often the table is being written to/operated on, independent of how large the entire table is. This is a critical design element needs for supporting frequent writes/commits to tables.</p><p>Lastly, new events on the timeline are then consumed and reflected onto an internal metadata table, implemented as another merge-on-read table offering low write amplification. Hudi is able to absorb quick/rapid changes to table’s metadata, unlike table formats designed for slow-moving data. Additionally, the metadata table uses the <a href="https://hbase.apache.org/2.0/devapidocs/org/apache/hadoop/hbase/io/hfile/HFile.html">HFile</a> base file format, which provides indexed lookups of keys avoiding the need for reading the entire metadata table to satisfy metadata reads. It currently stores all the physical file paths that are part of the table, to avoid expensive cloud file listings.</p><p>A key challenge faced by all the table formats out there today, is the need for expiring snapshots/controlling retention for time travel queries such that it does not interfere with query planning/performance. In the future, we plan to build an indexed timeline in Hudi, which can span the entire history of the table, supporting a time travel look back window of several months/years.</p><h3>Indexes</h3><p>Indexes help databases plan better queries, that reduce the overall amount of I/O and deliver faster response times. Table metadata about file listings and column statistics are often enough for lake query engines to generate optimized, engine specific query plans quickly. This is however not sufficient for Hudi to realize fast upserts. Hudi already supports different key based indexing schemes to quickly map incoming record keys into the file group they reside in. For this purpose, Hudi exposes a pluggable indexing layer to the writer implementations, with built-in support for range pruning (when keys are ordered and largely arrive in order) using interval trees and bloom filters (e.g: for uuid based keys where ordering is of very little help). Hudi also implements a HBase backed external index which is much more performant although more expensive to operate. Hudi also consciously exploits the partitioning scheme of the table to implement global and non-global indexing schemes. Users can choose to enforce key constraints only within a partition, in return for <em>O(num_affected_partitions)</em> upsert performance as opposed to <em>O(total_partitions)</em> in the global indexing scenarios. We refer you to this <a href="http://hudi.apache.org/blog/hudi-indexing-mechanisms/">blog</a>, that goes over indexing in detail. Ultimately, Hudi’s writer path ensures the index is always kept in sync with the timeline and data, which is cumbersome and error prone to implement on top of a table format by hand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PCv-DBIG6LgDVzOE.png" /></figure><p>In the future, we intend to add additional forms of indexing as new partitions on the metadata table. Let’s discuss the role each one has to play briefly. Query engines typically rely on partitioning to cut down the number of files read for a given query. In database terms, a Hive partition is nothing but a coarse range index, that maps a set of columns to a list of files. Table formats born in the cloud like Iceberg/Delta Lake, have built-in tracking of column ranges per file in a single flat file (json/avro), that helps avoid planning costs for large/poorly sized tables. This need has been largely reduced for Hudi tables thus far, given Hudi automatically enforces file sizes which help bound time taken to read out stats from parquet footers for e.g. However, with the advent of features like clustering, there is a need for writing smaller files first and then reclustering in a query optimized way. We plan to add indexed column ranges, that can scale to lots of small files and support faster mutations . See <a href="https://cwiki.apache.org/confluence/display/HUDI/RFC-27+Data+skipping+index+to+improve+query+performance">RFC-27</a> to track the design process and get involved.</p><p>While Hudi already supports external indexes for random write workloads, we would like to support <a href="https://github.com/apache/hudi/pull/2487">point-lookup-ish queries</a> right on top of lake storage, which helps avoid the overhead of an additional database for many classes of data applications. We also anticipate that uuid/key based joins will be sped up a lot, by leveraging record level indexing schemes, we build out for fast upsert performance. We also plan to move our tracking of bloom filters out of the file footers and into its <a href="https://issues.apache.org/jira/browse/HUDI-1295">own partition</a> on the metadata table. Ultimately, we look to exposing all of this to the queries as well in the coming releases.</p><h3>Concurrency Control</h3><p>Concurrency control defines how different writers/readers coordinate access to the table. Hudi ensures atomic writes, by way of publishing commits atomically to the timeline, stamped with an instant time that denotes the time at which the action is deemed to have occurred. Unlike general purpose file version control, Hudi draws clear distinction between writer processes (that issue user’s upserts/deletes), table services (that write data/metadata to optimize/perform bookkeeping) and readers (that execute queries and read data). Hudi provides snapshot isolation between all three types of processes, meaning they all operate on a consistent snapshot of the table. Hudi provides <a href="https://cwiki.apache.org/confluence/display/HUDI/RFC+-+22+%3A+Snapshot+Isolation+using+Optimistic+Concurrency+Control+for+multi-writers">optimistic concurrency control</a> (OCC) between writers, while providing lock-free, non-blocking MVCC based concurrency control between writers and table-services and between different table services.</p><p>Projects that solely rely on OCC deal with competing operations, by either implementing a lock or relying on atomic renames. Such approaches are optimistic that real contention never happens and resort to failing one of the writer operations if conflicts occur, which can cause significant resource wastage or operational overhead. Imagine a scenario of two writer processes : an ingest writer job producing new data every 30 minutes and a deletion writer job that is enforcing GDPR taking 2 hours to issue deletes. If there were to overlap on the same files (very likely to happen in real situations with random deletes), the deletion job is almost guaranteed to starve and fail to commit each time, wasting tons of cluster resources. Hudi takes a very different approach that we believe is more apt for lake transactions, which are typically long-running. For e.g async compaction that can keep deleting records in the background without blocking the ingest job. This is implemented via a file level, log based concurrency control protocol which orders actions based on their start instant times on the timeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gA4DaF-4anHMpYth.png" /></figure><p>We are hard at work, improving our OCC based implementation around early detection of conflicts for concurrent writers and terminate early without burning up CPU resources. We are also working on <a href="https://cwiki.apache.org/confluence/display/HUDI/RFC+-+22+%3A+Snapshot+Isolation+using+Optimistic+Concurrency+Control+for+multi-writers#RFC22:SnapshotIsolationusingOptimisticConcurrencyControlformultiwriters-FutureWork(LockFree-ishConcurrencyControl)">adding fully log based</a>, non-blocking concurrency control between writers, where writers proceed to write deltas and conflicts are resolved later in some deterministic timeline order — again much like how stream processing programs are written. This is possible only due to Hudi’s unique design that sequences actions into an ordered event log and the transaction handling code is aware of the relationship/interdependence of actions to each other.</p><h3>Writers</h3><p>Hudi tables can be used as sinks for Spark/Flink pipelines and the Hudi writing path provides several enhanced capabilities over file writing done by vanilla parquet/avro sinks. Hudi classifies write operations carefully into incremental (insert, upsert, delete) and batch/bulk operations (insert_overwrite, insert_overwrite_table, delete_partition, bulk_insert) and provides relevant functionality for each operation in a performant and cohesive way. Both upsert and delete operations automatically handle merging of records with the same key in the input stream (say, a CDC stream obtained from upstream table) and then lookup the index, finally invoke a bin packing algorithm to pack data into files, while <a href="http://hudi.apache.org/blog/hudi-file-sizing/">respecting a pre-configured target file size</a>. An insert operation on the other hand, is intelligent enough to avoid the precombining and index lookup, while retaining the benefits of the rest of the pipeline. Similarly, bulk_insert operation provides several sort modes for controlling initial file sizes and file counts, when importing data from an external table to Hudi. The other batch write operations provide MVCC based implementations of typical overwrite semantics used in batch data pipelines, while retaining all the transactional and incremental processing capabilities, making it seamless to switch between incremental pipelines for regular runs and batch pipelines for backfilling/dropping older partitions. The write pipeline also contains lower layers optimizations around handling large merges by spilling to <a href="https://rocksdb.org/">rocksDB</a> or an external spillable map, multi-threaded/concurrent I/O to improve write performance.</p><p>Keys are first class citizens inside Hudi and the pre-combining/index lookups done before upsert/deletes ensure a key is unique across partitions or within partitions, as desired. In contrast with other approaches where this is left to data engineer to co-ordinate using MERGE INTO statements, this approach ensures quality data especially for critical use-cases. Hudi also ships with several <a href="http://hudi.apache.org/blog/hudi-key-generators/">built-in key generators</a> that can parse all common date/timestamps, handle malformed data with an extensible framework for defining custom key generators. Keys are also materialized with the records using the _hoodie_record_key meta column, which makes it possible to change the key fields and perform repairs on older data with incorrect keys for e.g. Finally, Hudi provides a HoodieRecordPayload interface is very similar to processor APIs in Flink or Kafka Streams, and allows for expressing arbitrary merge conditions, between the base and delta log records. This allows users to express partial merges (e.g log only updated columns to the delta log for efficiency) and avoid reading all the base records before every merge. Routinely, we find users leverage such custom merge logic during replaying/backfilling older data onto a table, while ensuring newer updates are not overwritten causing the table’s snapshot to go back in time. This is achieved by simply using the HoodieDefaultPayload where latest value for a given key is picked based a configured precombine field value in the data.</p><p>Hudi writers add metadata to each record, that codify the commit time and a sequence number for each record within that commit (comparable to a Kafka offset), which make it possible to derive record level change streams. Hudi also provides users the ability to specify event time fields in incoming data streams and track them in the timeline.Mapping these to stream processing concepts, Hudi contains both <a href="https://www.oreilly.com/radar/the-world-beyond-batch-streaming-101/">arrival and event time</a> for records for each commit, that can help us build good <a href="https://ci.apache.org/projects/flink/flink-docs-release-1.13/docs/dev/datastream/event-time/generating_watermarks/">watermarks</a> that inform complex incremental processing pipelines. In the near future, we are looking to add new metadata columns, that encode the source operation (insert, update, delete) for each record, before we embark on this grand goal of full end-end incremental ETL pipelines. All said, we realized many users may simply want to use Hudi as an efficient write layer that supports transactions, fast updates/deletes. We are looking into adding support for <a href="https://github.com/apache/hudi/pull/3306">virtual keys</a> and making the <a href="https://github.com/apache/hudi/pull/3247">meta columns optional</a>, to lower storage overhead, while still making rest of Hudi’s capabilities (metadata table, table services, ..) available.</p><h3>Readers</h3><p>Hudi provides snapshot isolation between writers and readers and allows for any table snapshot to be queries consistently from all major lake query engines (Spark, Hive, Flink, Presto, Trino, Impala) and even cloud warehouses like Redshift. In fact, we would love to bring Hudi tables as external tables with BigQuery/Snowflake as well, once they also embrace the lake table formats more natively. Our design philosophy around query performance has been to make Hudi as lightweight as possible whenever only base columnar files are read (CoW snapshot, MOR read-optimized queries), employing the engine specific vectorized readers in Presto, Trino, Spark for e.g to be employed. This model is far more scalable than maintaining our own readers and users to benefit from engine specific optimizations. For e.g <a href="https://prestodb.io/blog/2021/02/04/raptorx">Presto</a>, <a href="https://trino.io/docs/current/connector/hive-caching.html">Trino</a> all have their own data/metadata caches. Whenever, Hudi has to merge base and log files for a query, Hudi takes control and employs several mechanisms (spillable maps, lazy reading) to improve merge performance, while also providing a read-optimized query on the data that trades off data freshness for query performance. In the near future, we are investing deeply into improving MoR snapshot query performance in many ways such as inlining parquet data, special handling of overwrite payloads/merges.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PsrDxYCuhiupzZQB.png" /></figure><p>True to its design goals, Hudi provides some very powerful incremental querying capabilities that tied together the meta fields added during writing and the file group based storage layout. While table formats that merely track files, are only able to provide information about files that changed during each snapshot or commits, Hudi generates the exact set of records that changed given a point in the timeline, due to tracking of record level event and arrival times. Further more, this design allows large commits to be consumed in smaller chunks by an incremental query, fully decoupling the writing and incremental querying of data. Time travel is merely implemented as an incremental query that starts and stops at an older portion of the timeline. Since Hudi ensures that a key is atomically mapped to a single file group at any point in time, it makes it possible to support full CDC capabilities on Hudi tables, such as providing all possible values for a given record since time t, CDC streams with both before and after images. All of these functionalities can be built local to each file group, given each file group is a self-contained log. Much of our future work in this area will be around bringing such a powerful set of <a href="https://debezium.io/">debezium</a> like capabilities to life in the coming months.</p><h3>Table Services</h3><p>What defines and sustains a project’s value over years are its fundamental design principles and the subtle trade offs. Databases often consist of several internal components, working in tandem to deliver efficiency, performance and great operability to its users. True to intent to act as state store for incremental data pipelines, we designed Hudi with built-in table services and self-managing runtime that can orchestrate/trigger these services to optimize everything internally. In fact, if we compare rocksDB (a very popular stream processing state-store) and Hudi’s components, the similarities become obvious.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*y9Wqeq7vaR28Aa5r.png" /></figure><p>There are several built-in table services, all with the goal of ensuring performant table storage layout and metadata management, which are automatically invoked either synchronously after each write operation, or asynchronously as a separate background job. Furthermore, Spark (and Flink) streaming writers can run in continuous mode, and invoke table services asynchronously sharing the underlying executors intelligently with writers. Archival service ensures that the timeline holds sufficient history for inter service co-ordination (e.g compactions wait for other compactions to complete on the same file group), incremental queries. Once events expire from the timeline, the archival service cleans up any side-effects from lake storage (e.g. rolling back of failing concurrent transactions). Hudi’s transaction management implementation allows all of these services to be idempotent and thus resilient to failure via just simple retries. <a href="http://hudi.apache.org/blog/employing-right-configurations-for-hudi-cleaner/">Cleaner</a> service works off the timeline incrementally (eating our own incremental design dog food), removing file slices that are past the configured retention period for incremental queries, while also allowing sufficient time for long running batch jobs (e.g Hive ETLs) to finish running. Compaction service comes with built-in strategies (date partitioning based, I/O bounded), that merges a base file with a set of delta log files to produce new base file, all while allowing writes to happen concurrently to the file group. This is only possible due to Hudi’s grouping of files into groups and support for flexible log merging, and unlocks non-blocking execution of deletes while concurrent updates are being issues to the same set of records. <a href="http://hudi.apache.org/blog/hudi-clustering-intro/">Clustering</a> service functions similar to what users find in BigQuery or Snowflake, where users can group records that are often queried together by sort keys or control file sizes by coalescing smaller base files into larger ones. Clustering is fully aware of other actions on the timeline such as cleaning, compaction, and it helps Hudi implement intelligent optimizations like avoiding compaction on file groups that are already being clustered, to save on I/O. Hudi also performs rollback of partial writes and cleans up any uncommitted data from lake storage, by use of marker files that track any files created as a part of write operations. Finally, the bootstrap service performs one time zero copy migration of plain parquet tables to Hudi, while allowing both pipelines to operate in parallel, for data validation purposes. Cleaner service is once again aware of these bootstrapped base files and can optionally clean them up, to ensure use-cases like GDPR compliance are met.</p><p>We are always looking for ways to improve and enhance our table services in meaningful ways. In the coming releases, we are working towards a much more <a href="https://github.com/apache/hudi/pull/3233">scalable model</a> of cleaning up partial writes, by consolidating marker file creation using our timeline metaserver, which avoids expensive full table scans to seek out and remove uncommitted files. We also have <a href="https://cwiki.apache.org/confluence/pages/viewpage.action?pageId=181307144">various proposals</a> to add more clustering schemes, unlock clustering with concurrent updates using fully log based concurrency control.</p><h3>Data Services</h3><p>As noted at the start, we wanted to make Hudi immediately usable for common end-end use-cases and thus invested deeply into a set of data services, that provide functionality that is data/workload specific, sitting on top of the table services, writers/readers directly. Foremost in that list, is the Hudi DeltaStreamer utility, which has been an extremely popular choice for painlessly building a data lake out of Kafka streams and files landing in different formats on top of lake storage. Over time, we have also built out sources that cover all major systems like a JDBC source for RDBMS/other warehouses, Hive source and even incrementally pulling data from other Hudi tables. The utility supports automatic checkpoint management tracking source checkpoints as a part of target Hudi table metadata, with support for backfills/one-off runs. DeltaStreamer also integrates with major schema registries such as Confluent’s and also provides checkpoint translation from other popular mechanisms like Kafka connect. It also supports de-duplication of data, multi-level configuration management system, built in transformers that take arbitrary SQL or coerce <a href="http://hudi.apache.org/blog/hudi-meets-aws-emr-and-aws-dms/">CDC log changes</a> into writable forms, that combined with other aforementioned features can be used for deploying production grade incremental pipelines. Finally, just like the Spark/Flink streaming writers, DeltaStreamer is able to run in a continuous mode, with automatic management of table services. Hudi also provides several other tools for snapshotting and incrementally exporting Hudi tables, also importing/<a href="http://hudi.apache.org/blog/exporting-hudi-datasets/">exporting</a>/bootstrapping new tables into Hudi. Hudi also provides commit notifications into Http endpoints or Kafka topics, about table commit activity, which can be used for analytics or building data sensors in workflow managers like Airflow to trigger pipelines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nJxbFmLpDnoOcok8.png" /></figure><p>Going forward, we would love contributions to enhance our <a href="http://hudi.apache.org/blog/ingest-multiple-tables-using-hudi/">multi delta streamer utility</a>, which can ingest entire Kafka clusters in a single large Spark application, to be on par and hardened. To further our progress towards end-end complex incremental pipelines, we plan to work towards enhancing the delta streamer utility and its SQL transformers to be triggered by multiple source streams (as opposed to just the one today) and unlock materialized views at scale. We would like to bring an array of useful transformers that perform masking or data monitoring, and extend support for egress of data off Hudi tables into other external sinks as well. Finally, we would love to merge the FlinkStreamer and the DeltaStreamer utilities into one cohesive utility, that can be used across engines. We are constantly improving existing sources (e.g support for parallelized listings of DFS sources) and adding new ones (e.g S3 event based DFS source)</p><h3>Timeline Metaserver</h3><p>Storing and serving table metadata right on the lake storage is scalable, but can be much less performant compared to RPCs against a scalable meta server. Most cloud warehouses internally are built on a metadata layer that leverages an external database (e.g <a href="https://www.snowflake.com/blog/how-foundationdb-powers-snowflake-metadata-forward/">Snowflake uses foundationDB</a>). Hudi also provides a metadata server, called the “Timeline server”, which offers an alternative backing store for Hudi’s table metadata. Currently, the timeline server runs embedded in the Hudi writer processes, serving file listings out of a local rocksDB store/<a href="https://javalin.io/">Javalin</a> REST API during the write process, without needing to repeatedly list the cloud storage. Given we have hardened this as the default option since our 0.6.0 release, we are considering standalone timeline server installations, with support for horizontal scaling, database/table mappings, security and all the features necessary to turn it into a highly performant next generation lake metastore.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MT_z-M0qz_nQFGPx.png" /></figure><h3>Lake Cache</h3><p>There is a fundamental tradeoff today in data lakes between faster writing and great query performance. Faster writing typically involves writing smaller files (and later clustering them) or logging deltas (and later merging on read). While this provides good performance already, the pursuit of great query performance often warrants opening fewer number of files/objects on lake storage and may be pre-materializing the merges between base and delta logs. After all, most databases employ a <a href="https://dev.mysql.com/doc/refman/8.0/en/innodb-buffer-pool.html">buffer pool</a> or <a href="https://github.com/facebook/rocksdb/wiki/Block-Cache">block cache</a>, to amortize the cost of accessing storage. Hudi already contains several design elements that are conducive for building a caching tier (write-through or even just populated by an incremental query), that will be multi-tenant and can cache pre-merged images of the latest file slices, consistent with the timeline. Hudi timeline can be used to simply communicate caching policies, just like how we perform inter table service co-ordination. Historically, caching has been done closer to the query engines or via intermediate in-memory file systems. By placing a caching tier closer and more tightly integrated with a transactional lake storage like Hudi, all query engines would be able to share and amortize the cost of the cache, while supporting updates/deletes as well. We look forward to building a buffer pool for the lake that works across all major engines, with the contributions from the rest of the community.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WYBe8lAki7yFf2qe.png" /></figure><h3>Onwards</h3><p>We hope that this blog painted a complete picture of Apache Hudi, staying true to its founding principles. Interested users and readers can expect blogs delving into each layer of the stack and an overhaul of our docs along these lines in the coming weeks/months. We view the current efforts around table formats as merely removing decade-old bottlenecks in data lake storage/query planes, problems which have been already solved very well in cloud warehouses like Big Query/Snowflake. We would like to underscore that our vision here is much greater, much more technically challenging. We as an industry are just wrapping our heads around many of these deep, open-ended problems, that need to be solved to marry stream processing and data lakes, with scale and simplicity. We hope to continue to put community first and build/solve these hard problems together. If these challenges excite you and you would like to build for that exciting future, please come join our <a href="http://hudi.apache.org/community.html">community</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5964468678a4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/apache-hudi-blogs/apache-hudi-the-streaming-data-lake-platform-5964468678a4">Apache Hudi — The Streaming Data Lake Platform</a> was originally published in <a href="https://medium.com/apache-hudi-blogs">apache-hudi-blogs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streaming Responsibly Into the Data Lake]]></title>
            <link>https://medium.com/apache-hudi-blogs/streaming-responsibly-into-the-data-lake-9a542b109eef?source=rss----464bbeff5499---4</link>
            <guid isPermaLink="false">https://medium.com/p/9a542b109eef</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[apache-hudi]]></category>
            <category><![CDATA[data-lake]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[analytics]]></category>
            <dc:creator><![CDATA[Vinoth Chandar]]></dc:creator>
            <pubDate>Mon, 15 Mar 2021 17:27:21 GMT</pubDate>
            <atom:updated>2021-03-15T17:27:21.032Z</atom:updated>
            <content:encoded><![CDATA[<h4>How Apache Hudi maintains optimum sized files</h4><blockquote>This blog is a repost of the original blog <a href="https://hudi.apache.org/blog/hudi-file-sizing/">here</a></blockquote><p>Apache Hudi is a data lake platform technology that provides several functionalities needed to build and manage data lakes. One such key feature that hudi provides is self-managing file sizing so that users don’t need to worry about manual table maintenance. Having a lot of small files will make it harder to achieve good query performance, due to query engines having to open/read/close files way too many times, to plan and execute queries. But for streaming data lake use-cases, inherently ingests are going to end up having smaller volume of writes, which might result in lot of small files if no special handling is done.</p><h3>During Write vs After Write</h3><p>Common approaches to writing very small files and then later stitching them together solve for system scalability issues posed by small files but might violate query SLA’s by exposing small files to them. In fact, you can easily do so on a Hudi table, by running a clustering operation, as detailed in a <a href="https://hudi.apache.org/blog/hudi-clustering-intro/">previous blog</a>.</p><p>In this blog, we discuss file sizing optimizations in Hudi, during the initial write time, so we don’t have to effectively re-write all data again, just for file sizing. If you want to have both (a) self managed file sizing and (b) Avoid exposing small files to queries, automatic file sizing feature saves the day.</p><p>Hudi has the ability to maintain a configured target file size, when performing inserts/upsert operations. (Note: bulk_insert operation does not provide this functionality and is designed as a simpler replacement for normal spark.write.parquet).</p><h3>Configs</h3><p>For illustration purposes, we are going to consider only COPY_ON_WRITE table.</p><p>Configs of interest before we dive into the algorithm:</p><ul><li><a href="https://hudi.apache.org/docs/configurations.html#limitFileSize">Max file size</a>: Max size for a given data file. Hudi will try to maintain file sizes to this configured value</li><li><a href="https://hudi.apache.org/docs/configurations.html#compactionSmallFileSize">Soft file limit</a>: Max file size below which a given data file is considered to a small file</li><li><a href="https://hudi.apache.org/docs/configurations.html#insertSplitSize">Insert split size</a>: Number of inserts grouped for a single partition. This value should match the number of records in a single file (you can determine based on max file size and per record size)</li></ul><p>For instance, if your first config value is 120MB and 2nd config value is set to 100MB, any file whose size is &lt; 100MB would be considered a small file.</p><p>If you wish to turn off this feature, set the config value for soft file limit to 0.</p><h3>Example</h3><p>Let’s say this is the layout of data files for a given partition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/0*RN_tUYavq5bSZ6vM.png" /><figcaption><em>Figure: Initial data file sizes for a given partition of interest</em></figcaption></figure><p>Let’s assume the configured values for max file size and small file size limit are 120MB and 100MB. File_1’s current size is 40MB, File_2’s size is 80MB, File_3’s size is 90MB, File_4’s size is 130MB and File_5’s size is 105MB. Let’s see what happens when a new write happens.</p><p><strong>Step 1:</strong> Assigning updates to files. In this step, We look up the index to find the tagged location and records are assigned to respective files. Note that we assume updates are only going to increase the file size and that would simply result in a much bigger file. When updates lower the file size (by say, nulling out lot of fields), then a subsequent write will deem it a small file.</p><p><strong>Step 2:</strong> Determine small files for each partition path. The soft file limit config value will be leveraged here to determine eligible small files. In our example, given the config value is set to 100MB, the small files are File_1(40MB) and File_2(80MB) and file_3’s (90MB).</p><p><strong>Step 3:</strong> Once small files are determined, incoming inserts are assigned to them so that they reach their max capacity of 120MB. File_1 will be ingested with 80MB worth of inserts, file_2 will be ingested with 40MB worth of inserts and File_3 will be ingested with 30MB worth of inserts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*C4SNuDwZREKg-yGk.png" /><figcaption><em>Figure: Incoming records are bin packed to existing small files</em></figcaption></figure><p><strong>Step 4:</strong> Once all small files are bin packed to its max capacity and if there are pending inserts unassigned, new file groups/data files are created and inserts are assigned to them. Number of records per new data file is determined from insert split size config. Assuming the insert split size is configured to 120k records, if there are 300k remaining records, 3 new files will be created in which 2 of them (File_6 and File_7) will be filled with 120k records and the last one (File_8) will be filled with 60k records (assuming each record is 1000 bytes). In future ingestions, 3rd new file will be considered as a small file to be packed with more data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4GwKFUJvtdP5ltYk.png" /><figcaption><em>Figure: Remaining records are assigned to new files</em></figcaption></figure><p>Hudi leverages mechanisms such as custom partitioning for optimized record distribution to different files, executing the algorithm above. After this round of ingestion is complete, all files except File_8 are nicely sized to the optimum size. This process is followed during every ingestion to ensure there are no small files in your Hudi tables.</p><p>Hopefully the blog gave you an overview into how hudi manages small files and assists in boosting your query performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a542b109eef" width="1" height="1" alt=""><hr><p><a href="https://medium.com/apache-hudi-blogs/streaming-responsibly-into-the-data-lake-9a542b109eef">Streaming Responsibly Into the Data Lake</a> was originally published in <a href="https://medium.com/apache-hudi-blogs">apache-hudi-blogs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>