<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ajay Bose on Medium]]></title>
        <description><![CDATA[Stories by Ajay Bose on Medium]]></description>
        <link>https://medium.com/@ajaybose?source=rss-bc108255bf9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*pL9KoIvUbWbB5wss.</url>
            <title>Stories by Ajay Bose on Medium</title>
            <link>https://medium.com/@ajaybose?source=rss-bc108255bf9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 21:17:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ajaybose/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Comparing various storage formats for object storage compatibility]]></title>
            <link>https://medium.com/@ajaybose/comparing-various-storage-formats-for-object-storage-compatibility-25b732cc50ef?source=rss-bc108255bf9------2</link>
            <guid isPermaLink="false">https://medium.com/p/25b732cc50ef</guid>
            <category><![CDATA[hive]]></category>
            <category><![CDATA[data-lakehouse]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[apache-iceberg]]></category>
            <dc:creator><![CDATA[Ajay Bose]]></dc:creator>
            <pubDate>Mon, 30 Dec 2024 08:55:15 GMT</pubDate>
            <atom:updated>2024-12-30T09:24:09.908Z</atom:updated>
            <content:encoded><![CDATA[<p>We have been using parquet storage format for storing our petabyte scale tables in Google Cloud Storage using Hive as our meta store. We encountered some issues with this setup</p><ol><li><strong>Hive writes are always done twice</strong> : Hive is not built for <a href="https://cloud.google.com/learn/what-is-object-storage?hl=en">object storage</a>, but is built for hadoop like storage engines where renaming files is O(1) operation. But in an object storage like GCS , <a href="https://cloud.google.com/storage/docs/rename-hns-folders#:~:text=If%20your%20folder%20contains%20many,with%20only%20some%20objects%20moved.">renaming a folder is an O(n) operation</a> since the contents of that files needs to be copied over to a new folder. There is no O(1) renaming in object storage. Hive relies heavily on renaming folders to offer atomicity. Each new write is written to a staging folder, Once the write is complete, the staging folder will be renamed with the actual folder name. This works great in a traditional file system and a distributed file system , but not in object storage.</li><li><strong>Hive storage is costing twice: </strong>Once the hive write to actual folder is complete, hive deletes the staging directory (That is how renaming works in object storage, copy source to target , delete source ). But google started offering soft delete functionality. Which means that whenever the <a href="https://cloud.google.com/storage/docs/soft-delete">bucket protection(soft delete)</a> is turned on, all the deleted staging folder is going to the soft delete space, the storage in soft delete space is not free either (Think of it as a recycle bin). At one point we were paying more for the data in the soft delete space than the actual storage.</li></ol><p>In this article I try to explore data lake formats like <a href="https://iceberg.apache.org/">Apache Iceberg</a> and <a href="https://hudi.apache.org/">Apache Hudi</a>, which claim to be built for object storage.</p><p>First let’s reproduce the problem. We will read a hive parquet table, do some transformation and write a new hive parquet table as output. We will keep a tab on how much time each write takes and how many objects are being created etc.</p><p>We are doing the following</p><pre>val df = spark.table(&quot;input_table&quot;)<br>df.write.saveAsTable(&quot;database.test_output_new&quot;)</pre><p>We will now analyze the output table location in GCS where the contents of the table is written.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*8RbqcndU4uKU60yfKK23FA.png" /></figure><p>Now let’s see the soft delete space below. As you can see the same objects are present in soft delete space as well. This is because spark initially wrote these files into the staging area and then upon commit copies over the files to the final table location. Then it deletes the staging directories, which goes into the soft delete space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ellO0avVho1fQdIyHWJJ0Q.png" /></figure><p>The contents of our sample data is small, But a single new partition write to a big table often contains terabytes of data. Copying over a terabyte of data takes significant amount of time even if it is within the same bucket, We are not only talking about storage cost here but also saving several minutes of time per table write. In some cases the copy from staging directories to actual storage takes 75% of the the total time , as you can see in <a href="https://stackoverflow.com/questions/69950723/how-to-avoid-hive-staging-area-write-on-cloud?source=post_page-----25b732cc50ef--------------------------------">this SO thread</a>.</p><p>Now let’s try the same thing using apache iceberg and see if we are able to solve this problem or not.</p><h3>Apache Iceberg</h3><p>Apache iceberg handles <a href="https://medium.com/snowflake/how-apache-iceberg-enables-acid-compliance-for-data-lakes-9069ae783b60">atomicity</a> in a different way than hive. There are metatdata files associated with each table. The metadata is updated only after the write is completed. This way even if data is written partially since the data files are not yet part of the metadata the table consistency and atomicity is unaffected. So we are expecting apache iceberg to handle the problems about dual write which we had mentioned at the beginning of this article.</p><p>When writing to apache iceberg we wont be writing it as a hive table, but as an iceberg table, Below is the code for that. You should add the spark3 runtime jar to spark shell class path, if you are using spark shell</p><pre>spark-shell  --name spark_session --conf --num-executors 100  --driver-memory 4g --executor-memory 16g --executor-cores 3 —driver-cores 1 --conf spark.sql.broadcastTimeout=-1 --jars  gs://da0e807e4a1ef3afe3608218be763e9017a7e38336ce6d6bf110d681a63a0c/application/jars/iceberg-spark-runtime_3.jar</pre><pre>val df = spark.sql(&quot;select * from input_table&quot;)<br><br>import org.apache.iceberg.spark.SparkSchemaUtil<br>import org.apache.spark.sql._<br>import org.apache.iceberg.hadoop._<br>import org.apache.iceberg.types.Types._<br>import org.apache.iceberg.PartitionSpec<br><br>val tables = new HadoopTables(spark.sparkContext.hadoopConfiguration)<br>val schema = SparkSchemaUtil.convert(df.schema)<br>val partitionSpec = PartitionSpec.builderFor(schema).build()<br>val location = &quot;gs://test_iceberg_cbb/data/first_iceberg_table/&quot;<br>val table = tables.create(schema, partitionSpec, location)<br><br>df.write.format(&quot;iceberg&quot;).mode(&quot;overwrite&quot;).save(&quot;gs://test_iceberg/data/first_iceberg_table/&quot;)</pre><p>Now let’s check the GCS for it’s contents. As you can see below the write is succesful , both data and metadata write is complete.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d6_rEUiY9r1g6yhCmDRzTw.png" /></figure><p>Now let’s checkout the soft delete space. In the data folder, as you can see there is no object in the soft delete space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-rbfXyrm8Dq4n9b40Y1crA.png" /></figure><p>With this small experiment we could conclude that apache iceberg has definitive advantages over apache hive if your data lake is on top of an object storage.</p><h3>References</h3><ul><li><a href="https://stackoverflow.com/questions/69950723/how-to-avoid-hive-staging-area-write-on-cloud">How to avoid Hive Staging Area Write on Cloud</a></li><li><a href="https://medium.com/expedia-group-tech/a-short-introduction-to-apache-iceberg-d34f628b6799">A Short Introduction to Apache Iceberg</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25b732cc50ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spark Jobs and Table Storage]]></title>
            <link>https://medium.com/@ajaybose/spark-jobs-and-table-storage-498cb2693c64?source=rss-bc108255bf9------2</link>
            <guid isPermaLink="false">https://medium.com/p/498cb2693c64</guid>
            <category><![CDATA[hive]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[spark]]></category>
            <dc:creator><![CDATA[Ajay Bose]]></dc:creator>
            <pubDate>Fri, 13 Sep 2024 16:41:21 GMT</pubDate>
            <atom:updated>2024-09-15T16:28:13.698Z</atom:updated>
            <content:encoded><![CDATA[<p>Performance of a spark/distributed application depends on how the input tables are stored. Let’s analyze how a spark application’s performance is dependent on the input number of files. We will also check how to store hive tables with the right file size.</p><p>Let’s start from the basics. Have you ever read from a data source , processed the data and written to a database/file storage using spark ? Have you observed the output is not always just a single file, but a set of files ? Why is that ? Let’s try doing the same and observe how many files are getting created.</p><p>We will read customer profile data from a table stored in gcs and exposed as a hive table, group by customer name, do count and write this information back to gcs. For the first attempt we are disabling adaptive query execution. In the next attempt we will turn it on and see what is the benefit it is bringing.</p><pre>val df = spark.table(&quot;input_table&quot;)<br><br>val aggregated_df = df.groupBy(&quot;first_name&quot;).agg(countDistinct(&quot;profile_id&quot;).alias(&quot;first_name_count&quot;))<br><br>aggregated_df.printSchema()<br><br>spark.conf.set(&quot;spark.sql.adaptive.enabled&quot;, false)<br><br>spark.conf.set(&quot;spark.sql.shuffle.partition&quot;,100)<br><br>aggregated_df.write.format(&quot;parquet&quot;).save(&quot;gs://ajbose-bucket/data/ajbose_test_data_new&quot;)</pre><p>Let’s examine the spark UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WCp4Z9AY-6v1JLT3Rsjx5g.png" /></figure><p>I have tagged the spark UI with the information that we are going to discuss below. We can observe the following from the spark UI</p><h3>Understanding the number of tasks in each phase</h3><ol><li>There are three stages in this simple data processing job , the first is to read data from the underlying table’s files. Second is a shuffle to support the wide transformation “groupBy on fullName” . The third is for the distinct operation and writing transformed data to the output table.</li><li>In the first stage there are 138 tasks. Why are there 138 tasks ? It is an odd number right? Actually the number of tasks in the reading phase for any table is corresponding to the number of files in that table/partition that is being read.</li><li>In the second and third phase we have exactly 100 tasks , Why is that. It is because we have set the shuffle parts to 100. Whenever spark will have to shuffle the data it will be exactly split into 100 parts( We have turned off Adaptive query execution, which is a feature in spark3. I will write a seperate article about adaptive query execution. )</li></ol><p>Any guesses on how many parts will the output table have ? It will be 100 , Why ? Because it was written by 100 different tasks and each task will write a separate file to the output location. But is the file size ideal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*dlfANOIVCHp3WypUvKteHg.png" /></figure><p>We have too many small files. Too many small files are not good for performance because of the following reasons</p><p>1. <strong>Overhead of Opening Files</strong>: The overhead of opening and closing a large number of files can significantly degrade performance. This is especially true for file systems like HDFS where each file, regardless of its size, requires a block.</p><p>2.<strong> Increased Garbage Collection</strong>: Handling a large number of small Java objects can trigger more frequent garbage collection, which can slow down the processing speed.</p><p>3. <strong>Network Overhead</strong>: Transferring a large number of small files across the network can lead to increased network overhead.</p><p>4.<strong> Task Scheduling Overhead</strong>: Each partition is processed as a separate task. When there are a large number of small files, there are a correspondingly large number of tasks. This leads to increased task scheduling overhead.</p><p>5. <strong>Data Skew</strong>: Small files can often lead to data skew if they are not evenly distributed. Some nodes might be overloaded with data while others have little to do.</p><p>6.<strong> Inefficient Utilization of Memory and CPU</strong>: When Spark reads a small file, it doesn’t fully utilize the memory and CPU, leading to inefficient resource utilization.</p><p>To summarize, while writing tables from spark, it is important that wepack the data into right file sizes. How do we do that?</p><h3>Writing Correctly packaged Tables From Spark</h3><p>From the earlier example you would have understood that how many parts a table has is directly affected by the shuffle parts configuration if the transformation/processing of data involves a wide transformation, And often all processing involve wide transformation. In that case setting the right number of shuffle partitions before the write to table/file path will result in rightly packaged hive tables with right file sizes.</p><p>How do we determine the right number of shuffle parts ? We estimate the size of the data frame and before writing the dataframe to disk we set the shuffleParts according to our esitmates. Below is the code snippets for estimating the shuffle parts.</p><pre>```scala<br>import org.apache.spark.sql.DataFrame<br><br>def estimateShuffleParts(df: DataFrame): Long = {<br>  // Get the size of the first row<br>  val firstRowSize = df.head().mkString.getBytes.length<br><br>  // Get the total number of rows<br>  val numRows = df.count()<br><br>  // Calculate the approximate size<br>  val size = firstRowSize * numRows<br><br>  // 128 MB files.<br>  size / (1024*1024*128L)<br>}<br><br>val df = spark.read.json(&quot;examples/src/main/resources/people.json&quot;)<br><br><br>```</pre><p>Let’s run the same job , but now with the right shuffle parts to see how it is effecting the files in the table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CNA6sWKWLszhOwyOcs-bdw.png" /></figure><p>As you can see this time the files are partitioned better.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=498cb2693c64" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Key Considerations While designing ETL Jobs]]></title>
            <link>https://medium.com/@ajaybose/key-considerations-while-designing-etl-jobs-1b9d54c09353?source=rss-bc108255bf9------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b9d54c09353</guid>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[etl-pipeline]]></category>
            <dc:creator><![CDATA[Ajay Bose]]></dc:creator>
            <pubDate>Sun, 19 May 2024 05:07:15 GMT</pubDate>
            <atom:updated>2025-01-02T02:59:14.398Z</atom:updated>
            <content:encoded><![CDATA[<p>A typical data processing job in airflow has the following components</p><ol><li>A high level airflow DAG.</li><li>Tasks inside each DAG.</li><li>A processing engine to execute each task. eg: Spark.</li></ol><p>How do we decide what tasks are involved a DAG ? Why cant an airflow DAG contain just one task which will execute all the needed steps in a processing engine like spark as shown below ?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lefVW8AjQL57TD_0IjsGjg.png" /></figure><p>How do we decide if we should create a new task in airflow DAG or if we should do the processing in the processing engine ( spark/SQL ) itself?</p><p><strong>How many data assets is it creating. </strong>It is best if each airflow task is creating only one data asset. If the job is creating more than one data asset it is best to divide them into two separate airflow tasks.</p><p><strong>Volume of data: </strong>If the processing job is handling too much data. Then it is best to handle it in separate jobs. That way load per job comes down and even if one job fails the retry is handling much less data and will take us considerably less time to re-process and process.</p><p><strong>Idempotency : </strong>When the task is retriggered multiple times is the effect Idempotent ?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b9d54c09353" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learnings from implementing Hive on Google Cloud Storage]]></title>
            <link>https://medium.com/@ajaybose/learnings-from-implementing-hive-on-google-cloud-storage-3b4587e05602?source=rss-bc108255bf9------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b4587e05602</guid>
            <category><![CDATA[cloud-storage]]></category>
            <category><![CDATA[cloud-cost-optimization]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[hive]]></category>
            <category><![CDATA[gcp]]></category>
            <dc:creator><![CDATA[Ajay Bose]]></dc:creator>
            <pubDate>Fri, 03 May 2024 06:28:28 GMT</pubDate>
            <atom:updated>2024-05-03T06:28:28.861Z</atom:updated>
            <content:encoded><![CDATA[<p>Cloud Storage is the managed object store offering from google cloud. In our organization we are making use of cloud storage as the backend for storing data. This enables us to create tables in both HIVE and Big Query while maintaining data at just one place.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jz88dzpwIaF9F3_K9Zgq_Q.png" /></figure><p>Having hive and big query on top of the same data enables us to</p><ol><li>Run our scheduled and legacy data workflows on cheaper spark compute, accessing the data using the hive meta store.</li><li>All our OLAP can be done using big query which is faster and comes with an intuitive user interface.</li></ol><p>While hive is built to work on top of traditional file systems such as HDFS , it works well with object storage as well. Object storage differs from the traditional file storage in the following ways.</p><ol><li>There is no concept of folders/directories.</li><li>All objects have a UUID associated and is stored in flat structure. Each object will have a detailed metadata associated with it. This flat structure allows object store to scale effectively since they are not constrained to traditional name stores which fails at handling density and a particular storage branch.</li><li>In a traditional file system renaming files is a constant time operation. But in an object store each object insider the <em>conceptual</em> folder needs to be renamed.</li></ol><h3>Inserting data into hive table</h3><p>Hive insertInto operation into an existing table seems to work pretty slow in GCS. This is because insert into writes all the data into a temporary directory and then renames the temporary directory into the main directory once the entire write is successful . This works well in a traditional file system. But when it comes to an object store, renaming is not a constant time opetation. Because of this <em>insert into</em> statements seems to take a lot of time when there are a lot of objects involved.</p><p>We solved this by converting all our <em>insert into’s into a Save </em>operation in GCS. Below is the high level algorithm we used</p><pre><br>boolean insertInto( df:DataFrame , table: String , partitionCols : List[String]){<br>    Map[Partition] = findPartitionValues(df,partitionCols)<br>    for(partition : Partition ){<br>        filteredDF = filteDF(df,partition)<br>        val path = formPath(table,partition)<br>        filteredDF.save(path)<br>    }<br>}</pre><h3>Maintaining data and access control</h3><p>For all the important data assets its best to go for a one to one relationship between tables and buckets. That is only data associated with a single table goes into that particular bucket. This enables you to</p><ol><li>Control access at the bucket level itself. Even though you can control access to the datasets at a BQ/HIVE data warehousing level. Having access control at the source level gives you finer control and single source of control.</li><li>It will be easier to calculate storage cost associated with a bucket this way.</li><li>You will also be able to archive data of a table, by changing the class of a bucket.</li></ol><h3>Soft Delete Strategy</h3><p>Soft delete is a new feature that was rolled out to all GCS buckets starting last month. This keeps deleted data in the soft deleted space for configured amount of time before permanently deleting the data.</p><p>In order to make use of this feature we divided our buckets into two</p><ol><li>In which intermediate working tables are stored . These buckets were configured to not have soft delete enabled. The intermediate tables are often snapshot tables and are re-written , this is considered objects delete and would have consumed a lot of soft delete storage space. Classifying them as</li><li>In which important downstream facing tables are maintained. These buckets were configured to have a larger window of soft deletion period. To safeguard from accidental deletions. This is better than backing them up to a cold line storage which involves a high network and class A/B operation costs.</li></ol><h3>Cost Implications</h3><p>Google provides multiple classes of storage depending on the frequency of data access. They are nearline, cold line and archive . Google also provides a new storage class called auto class which automatically categorizes and stores the data depending on how we are accessing it. For most of our buckets we have configured them to be auto-classs. We are seeing significant cost benefits from this change.</p><h3>Dealing with growing storage</h3><p>With managed storage comes the ability to store unlimited amount of data but it also comes with a responibility to clean up unwanted data. We have made it a practice in our team to prune tables which are verionesd snapshot of data at various points in time. By making pruning of data a part of the data management workflow, we are seeing significant reduction in storage cost and elimination of manual work for one time clean ups.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b4587e05602" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>