<?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 Rishika Idnani on Medium]]></title>
        <description><![CDATA[Stories by Rishika Idnani on Medium]]></description>
        <link>https://medium.com/@rishikaidnani?source=rss-bf66ef80b7ba------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*F9QfOpxhcjy4GIk8JcFjWQ.jpeg</url>
            <title>Stories by Rishika Idnani on Medium</title>
            <link>https://medium.com/@rishikaidnani?source=rss-bf66ef80b7ba------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 13:16:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rishikaidnani/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[Late arriving 
data : Challenges and Traditional Solutions]]></title>
            <link>https://medium.com/art-of-data-engineering/late-arriving-data-challenges-and-traditional-solutions-1e5522e06878?source=rss-bf66ef80b7ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e5522e06878</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-warehouse]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[analytics]]></category>
            <dc:creator><![CDATA[Rishika Idnani]]></dc:creator>
            <pubDate>Fri, 09 Feb 2024 02:33:41 GMT</pubDate>
            <atom:updated>2024-02-20T18:50:59.083Z</atom:updated>
            <content:encoded><![CDATA[<h3>Late arriving data : Challenges and Traditional Solutions</h3><p>In my experience with data engineering, a recurring challenge I’ve encountered is the issue of late-arriving data. This encompasses various scenarios such as users arriving late to the data store, events being delayed in reaching the data store. Moreover, ETL processes typically run with today’s partition date as the reference point, which means they process only the data that has arrived on the same day in the data store. Consequently, ETL processes often overlook the attributes associated with late-arriving data, resulting in their omission from the aggregated or transformed datasets generated by the ETLs. As a consequence, the derived datasets are incomplete, lacking crucial data from the source due to the challenge of late-arriving data.</p><p><strong>Data Loss in traditional ETL</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*56w-kCOKect0rWXGi0iXOA.png" /><figcaption>Traditional ETL running for today’s date only</figcaption></figure><p>In traditional data engineering practices, a common approach to address this challenge is by extending the scope of ETL processes beyond just the current day’s data. Essentially, the ETL pipeline is designed to process not only the data from the current day but also to reprocess data (partitions) from the preceding N days (look-back window) to accommodate any late-arriving data. While this strategy ensures that late-arriving data is accounted for, it also entails recomputing data that has already been processed. As a result, this approach consumes additional resources and leads to the overwriting of previously processed partitions, potentially causing inefficiencies in data processing and storage utilization.</p><p><strong>Workaround to mitigate data loss</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LVs2jPbxNBI-zobm3QIkKQ.png" /><figcaption>ETL running with look back window</figcaption></figure><p>Furthermore, this approach is not foolproof, particularly in cases where the data delay extends over an extended period. Implementing a lookback window to read old partitions spanning several months to accommodate reprocessing of historical data and re-writing old partitions becomes impractical and resource-intensive.</p><p>To address this challenge, the industry has embraced technologies enabling incremental processing, thereby avoiding the need for re-processing all historical data repeatedly. Concepts such as change data capture (CDC) have emerged, along with corresponding technologies like Apache Hudi. These solutions enable data engineers to capture and process only the changes or updates to existing datasets, significantly improving efficiency and reducing resource overhead associated with traditional data processing methods.</p><p><em>Thank you for reading! If you found this interesting, follow me on </em><a href="https://medium.com/@rishikaidnani"><em>Medium</em></a><em> and subscribe to my latest articles. Also, you can catch me on </em><a href="https://www.linkedin.com/in/rishikaidnani/"><em>LinkedIn</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e5522e06878" width="1" height="1" alt=""><hr><p><a href="https://medium.com/art-of-data-engineering/late-arriving-data-challenges-and-traditional-solutions-1e5522e06878">Late arriving 
data : Challenges and Traditional Solutions</a> was originally published in <a href="https://medium.com/art-of-data-engineering">Art of Data Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing Spark ETL Jobs: Harnessing Glue as a Powerful Metastore]]></title>
            <link>https://medium.com/@rishikaidnani/optimizing-spark-etl-jobs-harnessing-glue-as-a-powerful-metastore-215609f3c04c?source=rss-bf66ef80b7ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/215609f3c04c</guid>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[etl]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[aws-glue]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Rishika Idnani]]></dc:creator>
            <pubDate>Mon, 22 Jan 2024 01:33:41 GMT</pubDate>
            <atom:updated>2024-02-11T20:26:45.399Z</atom:updated>
            <content:encoded><![CDATA[<p>Companies are increasingly embracing the approach to store vast amount of data in data lakes like s3 and query them (data lake house) using data query engines like Presto, Trino and Athena . To optimize and organize the querying process, metastores like Hive (HMS) and Glue data catalog play a pivotal role by serving as a metadata layer over the underlying raw data stored in S3 datalake.</p><p>These metastores not only enable the creation and storage of essential metadata, including details about table structures, updates, and partitions, but also streamline the overall data management process. In summary, the storage of vast datasets in data lakes, coupled with intelligent utilization of data query engines and metastores, represents powerful approach for companies to harness the full potential of querying their data resources.</p><p>Writing Spark SQL ETLs that consumes raw datasets from this datalake and process it into more transformed derived dataset is very common.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/0*10FEbcMgNfoPwnvd" /><figcaption>ETL flow</figcaption></figure><p>Unlike the conventional method of establishing JDBC connections in ETL processes to directly query data engines, a more efficient and reliable approach involves Spark ETLs directly accessing dataset metadata from the Hive Metastore (HMS) or Glue data catalog. By leveraging this metadata, Spark can seamlessly retrieve the underlying data from the data lake, processing it efficiently on its cluster. This method not only ensures faster execution but also enhances the overall reliability of the ETL process providing a more optimal solution compared to traditional JDBC connections. After write operations to glue catalog from spark, users can query updated data from query engines like Athena</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/0*KasP3mSTRmObDbgd" /><figcaption>Query flow</figcaption></figure><p>Below code snippet is to enable spark use glue catalog as metastore. This code runs on Spark AWS EMR.</p><pre>//  Create spark session with enable hive support. Ideal goal is to use glue as catalog<br><br>val sparkSession: SparkSession = SparkSession<br> .builder()<br> .appName(&quot;lakeformation_poc&quot;)<br> .config(&quot;spark.hadoop.hive.metastore.client.factory.class&quot;, &quot;com.amazonaws.glue.catalog.metastore.AWSGlueDataCatalogHiveClientFactory&quot;)<br> .enableHiveSupport()<br> .getOrCreate()<br><br>[Otpional] It can also be passed from spark-submit<br>--conf spark.hadoop.hive.metastore.client.factory.class=com.amazonaws.glue.catalog.metastore.AWSGlueDataCatalogHiveClientFactory</pre><p>Below is the log from the spark job run that specifies glue was used as metastore</p><pre>INFO AWSGlueClientFactory: Setting region to : us-east-1</pre><p>Reading/Querying tables from spark code (without any jdbc connection to query engine) will get table’s metadata from glue</p><pre>val df = sparkSession.sql(&quot;SELECT * FROM public.test_table&quot;)<br>df.printSchema()<br>println(df.count())</pre><p>After obtaining the metadata, Spark reads the corresponding dataset from the data lake, leveraging the metadata information. Subsequently, Spark performs a series of transformations and operations on this data within its cluster.</p><p>Writing transformed/derived data back to glue catalog will also ensure that underlying tables are updated with latest metadata. Below code snippet writes back to glue catalog. Consequently, querying the dataset from Athena immediately reflects the most recent changes</p><pre>// data df write to s3<br>val tableName = &quot;public.test_table&quot;<br>val s3WritePath = &quot;s3://&lt;s3_bucket&gt;/&lt;s3_prefix&gt;/2024-01-09/&quot;<br>df.write.mode(&quot;overwrite&quot;).parquet(s3WritePath)<br><br>// update the table metadata to point to new s3<br>sparkSession.sqlContext.sql(s&quot;ALTER TABLE ${tableName} SET LOCATION &#39;${s3WritePath}&#39; &quot;)<br><br>// Athena table repaired pointing to updated location<br>athena &gt; Location:  s3://&lt;s3_bucket&gt;/&lt;s3_prefix&gt;/2024-01-09/<br><br>Location:            s3://&lt;s3_bucket&gt;/&lt;s3_prefix&gt;/2024-01-09/<br>Table Type:          EXTERNAL_TABLE</pre><p>In summary, opting for Spark jobs with a metastore to retrieve dataset metadata, as opposed to establishing direct JDBC connections to query engines, proves to be a more efficient and expeditious approach.</p><p>References:</p><p><a href="https://docs.aws.amazon.com/emr/latest/ReleaseGuide/emr-spark-glue.html">Use the AWS Glue Data Catalog as the metastore for Spark SQL</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=215609f3c04c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Complex types in Spark — Arrays, Maps & Structs]]></title>
            <link>https://medium.com/@rishikaidnani/complex-types-in-spark-arrays-maps-structs-b9410678c527?source=rss-bf66ef80b7ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9410678c527</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-processing]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Rishika Idnani]]></dc:creator>
            <pubDate>Thu, 14 Dec 2023 20:16:46 GMT</pubDate>
            <atom:updated>2023-12-14T20:16:46.157Z</atom:updated>
            <content:encoded><![CDATA[<h3>Complex types in Spark — Arrays, Maps &amp; Structs</h3><p>In Apache Spark, there are some complex data types that allows storage of multiple values in a single column in a data frame. This article will cover 3 such types ArrayType, MapType, and StructType and also when to use which type.</p><p>Often times, while ingesting data in Spark for data processing, whether from a Hive table or other upstream sources, it’s common to encounter scenarios where the DataFrame schema and specific attributes fall into distinctive types. Furthermore, when constructing a DataFrame in Spark, the choice of how to store, read, and structure the data becomes pivotal for facilitating seamless data processing and efficient querying.</p><p><strong>ArrayType:</strong></p><p>This represents an array of elements of a specific data type. It allows you to store an ordered sequence of values under a single column in a DataFrame. When your data/column in source that contains an array of values. Example : list of personas, sequence of endpoints, etc.</p><pre>import org.apache.spark.sql.types.{StructType, StringType, ArrayType}<br>import org.apache.spark.sql.{Row, Column}<br>import scala.collection.JavaConversions._<br>import org.apache.spark.sql._<br>import org.apache.spark.sql.functions._<br><br>val data = Seq(Row(&quot;UserA&quot;, Array(&quot;apple&quot;, &quot;orange&quot;)))<br><br><br>val schema = new StructType().add(&quot;user&quot;, StringType).add(&quot;food&quot;, ArrayType(StringType))<br><br>val df = spark.createDataFrame(spark.sparkContext.parallelize(data), schema)<br><br>df.show(false)<br><br>+-----+---------------+<br>|user |food           |<br>+-----+---------------+<br>|UserA|[apple, orange]|<br>+-----+---------------+<br><br>val citrus_df = df.withColumn(&quot;is_citrus&quot;, array_contains($&quot;food&quot;,&quot;orange&quot;))<br>citrus_df.show(false)<br><br>+-----+---------------+---------+<br>|user |food           |is_citrus|<br>+-----+---------------+---------+<br>|UserA|[apple, orange]|true     |<br>+-----+---------------+---------+</pre><p><strong>MapType</strong></p><p>This represent a map of key-value pairs within a DataFrame or a Spark SQL table. Its concept is similar to that of a dictionary in python. The MapType in Spark allows us to store such key-value mappings in a single column. Example : mapping of configurations, properties et al.</p><pre>import org.apache.spark.sql.types.{StructType, StringType, ArrayType, MapType, IntegerType}<br>import org.apache.spark.sql.{Row, Column}<br>import scala.collection.JavaConversions._<br>import org.apache.spark.sql._<br>import org.apache.spark.sql.functions._<br><br>val data = Seq(Row(&quot;UserA&quot;, Map(&quot;apple&quot; -&gt; 3, &quot;orange&quot; -&gt; 7)))<br><br>val schema = new StructType().add(&quot;user&quot;, StringType).add(&quot;food_with_count&quot;, MapType(StringType, IntegerType))<br><br>val df = spark.createDataFrame(spark.sparkContext.parallelize(data), schema)<br><br>df.show(false)<br><br>+-----+-------------------------+<br>|user |food_with_count          |<br>+-----+-------------------------+<br>|UserA|{apple -&gt; 3, orange -&gt; 7}|<br>+-----+-------------------------+</pre><p><strong>StructType</strong></p><p>This represents hierarchical data and is collection of data of different types. Its concept is similar to that of a row in a table. StructType has fixed number of StructFields (columns). When data in source is structured or nested/complex hierarchy data where each record has multiple fields with different data types thisStructType allows you to organize these fields in a structured manner within a single column. Overall, this make data processing easy and convenient to perform operations on nested data</p><pre>val data = Seq(<br> Row(<br>  Row(&quot;UserA_fn&quot;, &quot;UserA_ln&quot;), Array(&quot;apple&quot;, &quot;orange&quot;), Map(&quot;apple&quot; -&gt; 3, &quot;orange&quot; -&gt; 7)<br>),  Row(<br>  Row(&quot;UserB_fn&quot;, &quot;UserB_ln&quot;), Array(&quot;spinach&quot;, &quot;apple&quot;), Map(&quot;spinach&quot; -&gt; 3, &quot;apple&quot; -&gt; 4)<br>)<br>)<br><br>val schema = new StructType()<br>.add(&quot;user_name&quot;, new StructType().add(&quot;first_name&quot;, StringType).add(&quot;last_name&quot;, StringType))<br>.add(&quot;food&quot;, ArrayType(StringType))<br>.add(&quot;food_with_count&quot;, MapType(StringType, IntegerType))<br><br>val df = spark.createDataFrame(spark.sparkContext.parallelize(data), schema)<br><br>df.show(false)<br><br>+------------+----------------+--------------------------+<br>|user_name   |food            |food_with_count           |<br>+------------+----------------+--------------------------+<br>|{UserA_fn, }|[apple, orange] |{apple -&gt; 3, orange -&gt; 7} |<br>|{UserA_fn, }|[spinach, apple]|{spinach -&gt; 3, apple -&gt; 4}|<br>+------------+----------------+--------------------------+<br><br><br>val citrus_df = df.withColumn(&quot;is_citrus&quot;, array_contains($&quot;food&quot;,&quot;orange&quot;))<br>citrus_df.show(false)<br><br>+------------+----------------+--------------------------+---------+<br>|user_name   |food            |food_with_count           |is_citrus|<br>+------------+----------------+--------------------------+---------+<br>|{UserA_fn, }|[apple, orange] |{apple -&gt; 3, orange -&gt; 7} |true     |<br>|{UserA_fn, }|[spinach, apple]|{spinach -&gt; 3, apple -&gt; 4}|false    |<br>+------------+----------------+--------------------------+---------+</pre><h4>Summary</h4><p>To sum it up, strategic decision-making process proves instrumental in enhancing the ease of subsequent data processing and querying operations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9410678c527" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improve s3 write performance with magic committer in Spark3]]></title>
            <link>https://medium.com/towards-data-engineering/improve-s3-write-performance-with-magic-committer-in-spark3-d509e49f9710?source=rss-bf66ef80b7ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/d509e49f9710</guid>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[big-data-analytics]]></category>
            <category><![CDATA[etl]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Rishika Idnani]]></dc:creator>
            <pubDate>Fri, 17 Mar 2023 22:15:37 GMT</pubDate>
            <atom:updated>2024-02-23T09:55:30.003Z</atom:updated>
            <content:encoded><![CDATA[<h4>Comparing traditional &amp; magic s3 committer and a guide to use magic committer</h4><p>In data engineering, the utilization of object stores like Amazon S3 is ubiquitous, serving as a data lake for storing both raw and transformed data. Consequently, a many spark Extract, Transform &amp; Load (ETL) jobs write data back to s3, highlighting the importance of speeding up these writes to improve overall ETL pipeline efficiency and speed. Moreover, mitigating failures during the write stage is imperative to ensure the completion of processes and prevent incomplete or inaccurate data.</p><p>With the introduction of Spark 3.2, data engineers now benefit from an enhancement called magic committer (also known as s3a committer). This committer not only enhances the performance of Spark ETL processes but also bolsters reliability and scalability, marking a significant advancement in data engineering workflows.</p><p>Magic committer uses a different approach to writing data in s3 as compared to other traditional Hadoop output committers.</p><h3><strong>Tradition Committer vs Magic Committer</strong></h3><p><strong>Below is how traditional committer works:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WyjtVP2LnJ9uG3XkTYuJig.png" /><figcaption>Workflow of traditional output committer</figcaption></figure><p>While write is in progress, if we list the final s3 path we will see a <em>_temporary/</em></p><pre>aws s3 ls s3://&lt;bucket_name&gt;/prefix/<br>        PRE _temporary/</pre><p>While write is in successful, if we list the final s3 path we will see a <em>_SUCCESS</em> file of size 0 written</p><pre>aws s3 ls s3://&lt;bucket_name&gt;/prefix/<br>2023-03-16 00:29:57 0 _SUCCESS</pre><p>Imagine if a failure occurs while the copying files operation is in progress, the <strong>data output can be corrupted</strong>. In addition to being unsafe, it can also be very slow.</p><p>Magic committers writes data directly to the final S3 destination in parallel, instead writing files to a temporary location and then moving them to the final destination.</p><p><strong>Below is how magic committers work:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*ecLXcqXlj1MzjuOkEB-jpg.png" /><figcaption>Workflow of magic committer</figcaption></figure><p>Since it directly writes data to final destination, overhead of copying files to a temporary location and moving them later is avoided which in return increases the <strong>performance</strong>.</p><p>Since writes happen in parallel across multiple spark tasks/executors, it is <strong>scalable</strong> horizontally to handle large datasets</p><p>Either all data is written successfully, or none of it is written at all. This helps to <strong>prevent data inconsistencies and corruption</strong>.</p><p>While write is in progress, if we list the final s3 path we will see a __magic</p><pre>aws s3 ls s3://&lt;bucket_name&gt;/prefix/<br>        PRE __magic/</pre><p>While write is in successful, if we list the final s3 path we will see a _SUCCESS file (and size won’t be 0) written</p><pre>aws s3 ls s3://&lt;bucket_name&gt;/prefix/<br>2023-03-17 13:33:20 13756 _SUCCESS</pre><p>_SUCCESS file will have <em>committer:magic</em> mentioned</p><h3><strong>How to enable magic committer in spark</strong></h3><pre>    val spark: SparkSession = SparkSession<br>      .builder()<br>      .appName(name = appName.getOrElse(getClass.getName))<br>      .config(&quot;spark.serializer&quot;, &quot;org.apache.spark.serializer.KryoSerializer&quot;)<br>      .config(&quot;spark.hadoop.fs.s3a.impl&quot;, &quot;org.apache.hadoop.fs.s3a.S3AFileSystem&quot;)<br>      .config(&quot;spark.hadoop.fs.s3a.committer.magic.enabled&quot;, &quot;true&quot;)<br>      .config(&quot;spark.hadoop.mapreduce.outputcommitter.factory.scheme.s3a&quot;, &quot;org.apache.hadoop.fs.s3a.commit.S3ACommitterFactory&quot;)<br>      .config(&quot;fs.s3a.committer.name&quot;, &quot;magic&quot;)<br>      .config(&quot;spark.sql.sources.commitProtocolClass&quot;, &quot;org.apache.spark.internal.io.cloud.PathOutputCommitProtocol&quot;)<br>      .config(&quot;spark.sql.parquet.output.committer.class&quot;, &quot;org.apache.spark.internal.io.cloud.BindingParquetOutputCommitter&quot;)<br>      .getOrCreate()</pre><p>To determine the committer being utilized, we can refer to the Spark driver logs</p><p>Below log will ensure the magic committer is used</p><pre>INFO AbstractS3ACommitterFactory: Using committer magic to output data to s3a://…</pre><p>Additionally, ls on the s3 directory will indicate the __magic while the job is running</p><pre>aws s3 ls s3://&lt;bucket_name&gt;/prefix/<br>        PRE __magic/</pre><p>Once the job finishes, ls on the output s3 directory will have a non 0 byte _SUCCESS file and the content of the file will have &quot;committer&quot; : &quot;magic&quot;</p><p>If the warning below appears in the Spark driver logs, it indicates that this committer is not in use, potentially signaling an issue with its implementation. Moreover, the warning explicitly states that it is unsafe and slow.</p><pre>WARN AbstractS3ACommitterFactory: Using standard FileOutputCommitter to commit work. This is slow and potentially unsafe.</pre><p><strong><em>Note</em>:</strong> If the ETL pipeline employs table formats like Delta, Apache Iceberg, or Apache Hudi to write data to S3, the S3 committer is irrelevant because these table formats manage the commit process differently.</p><h3><strong>Conclusion</strong></h3><p>The Magic Committer is recommended to be used in ETL pipelines that write to s3 unless the ETL is already using table formats like Delta, Hudi, or Iceberg. This committer provides better performance and fault tolerance than traditional committers. This is because the Magic Committer can avoid the overhead of creating new output files and copying data to them for each write operation.</p><p><em>Thank you for reading! If you found this interesting, follow me on </em><a href="https://medium.com/@rishikaidnani"><em>Medium</em></a><em> and subscribe to my latest articles. Also, you can catch me on </em><a href="https://www.linkedin.com/in/rishikaidnani/"><em>LinkedIn</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d509e49f9710" width="1" height="1" alt=""><hr><p><a href="https://medium.com/towards-data-engineering/improve-s3-write-performance-with-magic-committer-in-spark3-d509e49f9710">Improve s3 write performance with magic committer in Spark3</a> was originally published in <a href="https://medium.com/towards-data-engineering">Towards Data Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solving data skewness in Spark with Salting]]></title>
            <link>https://medium.com/@rishikaidnani/solving-data-skewness-in-spark-with-salting-98f3c3c30451?source=rss-bf66ef80b7ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/98f3c3c30451</guid>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[data-skew]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[salting]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Rishika Idnani]]></dc:creator>
            <pubDate>Thu, 23 Feb 2023 20:17:24 GMT</pubDate>
            <atom:updated>2023-02-23T20:17:24.080Z</atom:updated>
            <content:encoded><![CDATA[<p>Data skewness refers to the non-uniform distribution of data in a dataset. Skewed data causes certain nodes/workers in a Spark cluster to be overloaded (while other workers are idle or less loaded) leading to performance degradation, slow processing and longer ETL run times.</p><p>Salting is technique used to mitigate the effects of skewness by adding random, unique values, known as “salts,” to the data. The salts are added to the keys in a way that evenly distributes the data across multiple partitions/workers. This reduces the skewness and ensures each partition/worker has roughly equal number of data points</p><p>We will go through an example on how to do this. Let’s say we have 2 datasets : One is language dataset which is more like a dimension dataset and is a smaller dataset. Another is language usage by users dataset. The language usage by users data is a massive (since it has many users data who use multiple languages) and is skewed.</p><p>Below is how Language and Language Usage Dataset looks like:</p><pre>#Language Dataset<br>val language_data = Seq((&quot;Java&quot;), (&quot;Python&quot;))<br>val rdd = spark.sparkContext.parallelize(language_data)<br>val language_df = rdd.toDF(&quot;language&quot;)<br>language_df.show(false)<br>+--------+<br>|language|<br>+--------+<br>|Java    |<br>|Python  |<br>+--------+</pre><pre>#Language usage by users Dataset<br>val language_users_data = Seq((&quot;Java&quot;, &quot;Rishika&quot;), <br>                              (&quot;Java&quot;, &quot;abc_user&quot;), <br>                              (&quot;Python&quot;, &quot;abc_user&quot;))<br>val rdd = spark.sparkContext.parallelize(language_users_data)<br>val language_users_df = rdd.toDF(&quot;language_name&quot;, &quot;user_name&quot;)<br>language_users_df.show(false)<br>+-------------+---------+<br>|language_name|user_name|<br>+-------------+---------+<br>|Java         |Rishika  |<br>|Java         |abc_user |<br>|Python       |abc_user |<br>+-------------+---------+</pre><p>Since, language usage is a massive dataset and has significantly more records that language dataset, when we join these two datasets, join skew will occur. Performance of the join operation will be significantly degraded because join keys will be unevenly distributed. This can be solved with salting technique.</p><p>Salt keys will partition data into smaller chunks. The number of these chunks will depend on number of unique salt keys used. The join operation will now happen on smaller chunks instead of full dataset. This ensures that each node in the cluster has a roughly equal amount of data to process, reducing the chances of data skew.</p><p>Step 1 — We will create salt keys in Language and Language Usage Dataset</p><pre># Salt Keys in Language Dataset<br>val salt_explode = &quot;explode(array(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19))&quot;<br>val language_salted_df = df.withColumn(&quot;salt_key&quot;, expr(salt_explode)).withColumn(&quot;language_salted&quot;, concat(col(&quot;language&quot;), lit(&quot;_&quot;), col(&quot;salt_key&quot;)))<br>language_salted_df.show(false)<br>+--------+--------+---------------+<br>|language|salt_key|language_salted|<br>+--------+--------+---------------+<br>|Java    |0       |Java_0         |<br>|Java    |1       |Java_1         |<br>|Java    |2       |Java_2         |<br>|Java    |3       |Java_3         |<br>|Java    |4       |Java_4         |<br>|Java    |5       |Java_5         |<br>|Java    |6       |Java_6         |<br>|Java    |7       |Java_7         |<br>|Java    |8       |Java_8         |<br>|Java    |9       |Java_9         |<br>|Java    |10      |Java_10        |<br>|Java    |11      |Java_11        |<br>|Java    |12      |Java_12        |<br>|Java    |13      |Java_13        |<br>|Java    |14      |Java_14        |<br>|Java    |15      |Java_15        |<br>|Java    |16      |Java_16        |<br>|Java    |17      |Java_17        |<br>|Java    |18      |Java_18        |<br>|Java    |19      |Java_19        |<br>+--------+--------+---------------+<br>only showing top 20 rows<br># Each language (join key) will be suffixed by each number between 1 to 19</pre><pre># Salt Keys in Language Usage Dataset<br>val salt_expr = &quot;concat(language_name, &#39;_&#39;, FLOOR(RAND(123456)*19))&quot;<br>val language_users_salted_df = language_users_df.withColumn(&quot;language_name_salt_key&quot;, expr(salt_expr))<br>language_users_salted_df.show(false)<br>+-------------+---------+----------------------+<br>|language_name|user_name|language_name_salt_key|<br>+-------------+---------+----------------------+<br>|Java         |Rishika  |Java_1                |<br>|Java         |abc_user |Java_13               |<br>|Python       |abc_user |Python_8              |<br>+-------------+---------+----------------------+<br># Each language_name (join key) will be suffixed by any random number between 1 to 19</pre><p>Step 2 — We join them on salt keys instead of original join keys which will improve performance because dataset will now be more evenly distributed.</p><pre># Join Language and Language Usage dataset<br>val join_df = language_salted_df<br>                .join(language_users_salted_df, <br>                 language_salted_df(&quot;language_salted&quot;)===<br>                 language_users_salted_df(&quot;language_name_salt_key&quot;), &quot;inner&quot;)<br>+--------+--------+---------------+-------------+---------+----------------------+<br>|language|salt_key|language_salted|language_name|user_name|language_name_salt_key|<br>+--------+--------+---------------+-------------+---------+----------------------+<br>|Python  |8       |Python_8       |Python       |abc_user |Python_8              |<br>|Java    |1       |Java_1         |Java         |Rishika  |Java_1                |<br>|Java    |13      |Java_13        |Java         |abc_user |Java_13               |<br>+--------+--------+---------------+-------------+---------+----------------------+<br># We can only select required columns and not select salt keys<br><br>val final_df = join_df.select(&quot;language&quot;, &quot;user_name&quot;)<br>final_df.show(false)<br>+--------+---------+<br>|language|user_name|<br>+--------+---------+<br>|Python  |abc_user |<br>|Java    |Rishika  |<br>|Java    |abc_user |<br>+--------+---------+</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*dRDcOUWpXdqIjUg7cQwQpQ.jpeg" /><figcaption>Without Salting, the key will go to one executor</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*hy4bS3ET7f6xw1-tb12q_A.jpeg" /><figcaption>With Salting, the same key will be distributed on different executors</figcaption></figure><p>I ran the join with much bigger datasets without salting and with salting. Below is performance graph of CPU utilization with salting and w/o salting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lFKoExstBy5vT-4SaaBc4A.png" /><figcaption>Without Salting</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r-VwIAFuU-LJnvyL7vOLWQ.png" /><figcaption>With Salting</figcaption></figure><p><strong>Final Thought</strong></p><p>In conclusion, salting is a useful technique for addressing data skewness in Spark ETL pipelines. By adding a unique identifier, known as a salt, to the data before it is partitioned, the data is more evenly distributed across all nodes in the cluster, reducing the risk of slow tasks and improving the performance of the pipeline.</p><p>In any case, it is important to continuously monitor the performance of your Spark ETL pipeline, and to take steps to address data skewness if it is affecting the performance of your pipeline. By doing so, you can ensure that your Spark ETL pipeline runs smoothly and efficiently, and that the results of your processing are accurate and reliable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98f3c3c30451" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Restoring objects from Glacier to S3 using Batch Operations (using Python boto3)]]></title>
            <link>https://medium.com/@rishikaidnani/restoring-objects-from-glacier-to-s3-using-batch-operations-using-python-boto3-618e9891b849?source=rss-bf66ef80b7ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/618e9891b849</guid>
            <category><![CDATA[aws-batch]]></category>
            <category><![CDATA[aws-s3]]></category>
            <category><![CDATA[boto3]]></category>
            <category><![CDATA[aws-glacier]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Rishika Idnani]]></dc:creator>
            <pubDate>Tue, 30 Nov 2021 03:20:30 GMT</pubDate>
            <atom:updated>2021-11-30T03:20:30.830Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*z6IfziKJ_eJxu9kLL514SQ.png" /></figure><p>S3 Batch operations gives us the leverage of performing actions across billions of objects and terabytes of data with a single request. In scenarios, when we want to restore objects in bulk, looping over the enormous list and restoring each object is a very time consuming and not an efficient process. This is where batch operations would come in handy. All we need to do is, specify the list of objects to be restored and AWS will manage the job of restoring these objects.</p><p>To start, let’s create a manifest which is basically a csv file containing list of all objects we want to restore. This csv file will have 2 columns : bucket name and object name. Here is an example of the manifest file (manifest.csv) :</p><pre>my_s3_bucket,file_1_to_be_restored.txt<br>my_s3_bucket,file_2_to_be_restored.txt<br>my_s3_bucket,file_3_to_be_restored.txt<br>my_s3_bucket,file_4_to_be_restored.txt<br>.<br>.</pre><p>Next, save this csv file and upload to the s3 bucket. I am uploading to same s3 bucket my_s3_bucket where all the objects to be restored exists:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5XwkekZvLP5HtKqIq0pGvQ.png" /><figcaption>Bucket with manifest file and objects in glacier to be restored</figcaption></figure><p>Let’s ensure all the access required to create and run the batch operations job is in place. Below are the accesses the IAM role that will be used for batch operations will need :</p><ul><li>It should have trust policy established with service batchoperations.s3.amazonaws.com</li><li>s3:RestoreObjectfor bucket where objects needs to be restored (target resource)</li><li>s3:GetBucketLocation, s3:GetObject, s3:GetObjectVersion for bucket where manifest.csv exists</li><li>s3:GetBucketLocation, s3:PutObject for bucket where log report should be added</li><li>s3:CreateJob, s3:DescribeJob, s3:ListJobs, and s3:UpdateJobStatuswith<em> </em>Resource:&quot;*&quot;as create job is a resource-less action.</li></ul><p>Refer AWS <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/batch-ops-iam-role-policies.html#batch-ops-iam-role-policies-trust">doc</a> for detailed explanation on IAM permissions around batch operations.</p><p>Once all the permissions are in place, let’s write a python code using boto3 library to create the job.</p><p>First, let’s create a main function with some important values required to create the job. Few things to note :</p><ul><li>Manifest object should be the S3 path s3://my_s3_bucket/manifest.csv to our manifest.csv file we made above</li><li>Mention the AWS region appropriately while creating s3ControlClient</li><li>Account ID can be grabbed using caller_identity_function</li></ul><p><em>Snippet below</em></p><pre>import boto3<br>if __name__ == &quot;__main__&quot;:<br>    <br>    s3ControlClient = boto3.client(&#39;s3control&#39;, region_name=&#39;us-east-2&#39;)</pre><pre>    my_s3_bucket = &quot;my_s3_bucket&quot;</pre><pre>    manifest_path = &quot;s3://my_s3_bucket/manifest.csv&quot; </pre><pre>    account_id = boto3.client(&#39;sts&#39;).get_caller_identity()[&#39;Account&#39;]</pre><pre>    create_batch_operations_job(s3ControlClient, bucket_name, manifest_path, account_id)</pre><p>Next, let’s write the code for function create_batch_operations. Few things to note :</p><ul><li>Manifest format should be S3BatchOperations_CSV_20180820 since manifest file we made is in CSV</li><li>Mention S3 prefix to store the generated restore reports. For example, batch_operations/restore_reports will generate report to s3://my_s3_bucket/batch_operations/restore_reports/</li><li>ExpirationInDays value 2 (or whatever day value you specified)will make temporary copies of the object (we want to restore) available in S3 for those many days and will later delete from S3. <em>Note: Restoring files doesn’t remove the Glacier copy.</em></li></ul><p><em>Snippet below</em></p><pre>def create_batch_operations_job(s3ControlClient, bucket_name, manifest_path, account_id):<br>    <br>    role_arn = &#39;arn:aws:iam::%s:role/&lt;AWS role with permissions&gt;&#39; % account_id<br>    bucket_arn = &#39;arn:aws:s3:::%s&#39; % bucket_name<br><br>    response = s3ControlClient.create_job(<br>        AccountId=account_id,<br>        ConfirmationRequired=False,<br>        Operation={<br>            &#39;S3InitiateRestoreObject&#39;: {<br>                &#39;ExpirationInDays&#39;: 2,<br>                &#39;GlacierJobTier&#39;: &#39;STANDARD&#39;<br>            }<br>        },<br>        Manifest={<br>            &#39;Spec&#39;: {<br>                &#39;Format&#39;: &#39;S3BatchOperations_CSV_20180820&#39;,<br>                &#39;Fields&#39;: [&#39;Bucket&#39;, &#39;Key&#39;]<br>            },<br>            &#39;Location&#39;: {<br>                &#39;ObjectArn&#39;: &#39;%s/%s&#39; % (bucket_arn, manifest_path),<em><br>                </em>&#39;ETag&#39;: &#39;&lt;etag&gt;&#39;  <em># call generate etag<br><br>            </em>}<br>        },<br>        Report={<br>            &#39;Bucket&#39;: bucket_arn,<br>            &#39;Format&#39;: &#39;Report_CSV_20180820&#39;,<br>            &#39;Enabled&#39;: True,<em><br>            </em>&#39;Prefix&#39;: &#39;batch_operations/restore_reports&#39;,<br>            &#39;ReportScope&#39;: &#39;AllTasks&#39;<br>        },<br>        Description=&quot;Restore Request &quot; + datetime.now().strftime(&#39;%Y-%m-%d %H:%M:%S&#39;),<br>        Priority=5,<br>        RoleArn=role_arn<br>    )<br>    print(&quot;Batch Job created&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5TT6Yi6dwoPf7W6lFLxwNA.png" /><figcaption>Batch Operations job created and completed from the above code</figcaption></figure><p>Our object’s restore is initiate and we should be seeing their temporary copies in S3 in a few hours (based on restore tier you choose) and these copies will be available in S3 for 3 (or whatever number of days you specified) days and later will be deleted automatically. Once the restore is completed successfully, copyaws s3 cp command should work on restore objects without any error (<em>Object is of storage class GLACIER. Unable to perform download operations on GLACIER objects</em>).</p><p><strong>References:</strong></p><ul><li><a href="https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3control.html#S3Control.Client.create_job">S3Control - Boto3 Docs 1.26.33 documentation</a></li><li><a href="https://aws.amazon.com/premiumsupport/knowledge-center/s3-batch-operation-initiate-restore/">Restore Amazon S3 objects in S3 Glacier or Glacier Deep Archive</a></li><li><a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/batch-ops-initiate-restore-object.html">Restore objects</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=618e9891b849" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Restoring objects from Glacier to S3 using Batch Operations (using AWS Console)]]></title>
            <link>https://medium.com/@rishikaidnani/restoring-objects-from-glacier-to-s3-using-batch-operations-using-aws-console-5dcb51f96ed9?source=rss-bf66ef80b7ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/5dcb51f96ed9</guid>
            <category><![CDATA[aws-glacier]]></category>
            <category><![CDATA[aws-batch]]></category>
            <category><![CDATA[restore]]></category>
            <category><![CDATA[aws-s3]]></category>
            <dc:creator><![CDATA[Rishika Idnani]]></dc:creator>
            <pubDate>Fri, 29 Oct 2021 21:55:54 GMT</pubDate>
            <atom:updated>2021-11-03T19:42:46.372Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*gvU73qEUb61k5OZkXiBzxA.png" /><figcaption>AWS S3 Batch Operations</figcaption></figure><p>S3 Batch operations gives us the leverage of performing actions across billions of objects and terabytes of data with a single request. In scenarios, when we want to restore objects in bulk, looping over the enormous list and restoring each object is a very time consuming and not an efficient process. This is where batch operations would come in handy. All we need to do is, specify the list of objects to be restored and AWS will manage the job of restoring these objects.</p><p>To start, let’s create a manifest which is basically a .csvfile containing list of all objects we want to restore. This file will have 2 columns : bucket name and object name along with prefix. Here is an example of the manifest file (manifest.csv) :</p><pre>my_s3_bucket,file_1_to_be_restored.txt<br>my_s3_bucket,file_2_to_be_restored.txt<br>my_s3_bucket,file_3_to_be_restored.txt<br>my_s3_bucket,file_4_to_be_restored.txt<br>.<br>.</pre><p>Next, save this file and upload to the S3 bucket. I am uploading to same s3 bucket my_s3_bucket where all the objects to be restored will exists:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5XwkekZvLP5HtKqIq0pGvQ.png" /><figcaption>Bucket with manifest file and all objects in glacier to be restored</figcaption></figure><p>Let’s ensure all the access required to create and run the batch operations job is in place. Below are the access the IAM role that will be used for batch operations will need :</p><ul><li>It should have trust policy established with service batchoperations.s3.amazonaws.com</li><li>s3:RestoreObjectfor bucket where objects needs to be restored (target resource)</li><li>s3:GetBucketLocation, s3:GetObject, s3:GetObjectVersion for bucket where manifest.csv exists</li><li>s3:GetBucketLocation, s3:PutObject for bucket where log/completion report should be added</li><li>IAM of the AWS role (logged in) that will be used to create job (via console) should have permission s3:CreateJob, s3:DescribeJob, s3:ListJobs, and s3:UpdateJobStatuswith<em> </em>Resource:&quot;*&quot;as create job is a resource-less action. <em>Note</em> : <em>this can be different from the IAM role (with the first 4 points of permissions mentioned) that (we will pass while creating batch job) the batch job will use to restore the objects.</em></li></ul><p>Refer AWS <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/batch-ops-iam-role-policies.html#batch-ops-iam-role-policies-trust">doc</a> for detailed explanation on IAM permissions around batch operations.</p><p>Once all the permissions are in place, go to S3 service on AWS console and click on Batch Operations (on left). Then click on Create Job (on right).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b3s0GVkKt00ZtLTwmvz61w.png" /><figcaption>Batch Operations and Create Job on S3 AWS Console</figcaption></figure><p>Fill in all the details in Create Job section. Manifest format should be CSV and Manifest object should be the S3 path s3://my_s3_bucket/manifest.csv to our manifest.csv file mentioned above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YlLxv_0d6dNAmZmHFUYslw.png" /><figcaption>Create Job for Batch Operations Step 1</figcaption></figure><p>Next — Choose Operation section: Select Restore operation and Glacier as Restore source. The number of days field value 3 (or whatever day value you specified)will decide the number of days the temporary copies of the restored objects be available in S3 (and will later be deleted from S3).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QZsFzOFanVh5U0srAHhuMg.png" /><figcaption>Choose Operation Step for Batch Operations restore</figcaption></figure><p>Next — in configuring additional options: we have the option to get a complete log report(error/success/description) to the S3 path we mention in the field Completion Report Destination (in my case s3://my_s3_bucket/restore_reports ). In permissions section, mention the IAM role, the one that has all the above mentioned permissions/access.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BbZe4pLFwVvKf-v9XmVySA.png" /><figcaption>Configure additional options step for Batch Operations</figcaption></figure><p>After all these steps are completed and once the job is created, go back to Batch Operations on left panel and we should be seeing the job we created. Select the job, and click on Run Job to start restore process. Refresh and wait till the job completes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MCDoYJSYeCTod-Ow-ei4Og.png" /><figcaption>Select the job and click on run to start restore process</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*97CefUAifCqk3WStzuta8A.png" /><figcaption>Refresh and wait until the job status is completed</figcaption></figure><p>Our object’s restore is initiated and we should be seeing temporary copies in S3 in a few hours (based on restore tier you choose).</p><p><em>Note: Restoring files doesn’t remove the Glacier copy.</em></p><p>These temporary copies will be available in S3 for 3 (or whatever number of days you specified) days and later will be automatically deleted. Once the restore is completed successfully, copy aws s3 cp command should work on restore objects without the error : <em>Object is of storage class GLACIER. Unable to perform download operations on GLACIER objects.</em></p><p><strong>References:</strong></p><ul><li><a href="https://aws.amazon.com/premiumsupport/knowledge-center/s3-batch-operation-initiate-restore/">Restore Amazon S3 objects in S3 Glacier or Glacier Deep Archive</a></li><li><a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/batch-ops-initiate-restore-object.html">Restore objects</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5dcb51f96ed9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>