<?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 Junrong Lau on Medium]]></title>
        <description><![CDATA[Stories by Junrong Lau on Medium]]></description>
        <link>https://medium.com/@junronglau?source=rss-546ce49d155------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mMoTiCULitrafk6vyU_YgA.png</url>
            <title>Stories by Junrong Lau on Medium</title>
            <link>https://medium.com/@junronglau?source=rss-546ce49d155------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 13:33:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@junronglau/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[Speed up your spark queries in 15 minutes]]></title>
            <link>https://blog.devgenius.io/speed-up-your-spark-queries-in-15-minutes-4a8da88942cf?source=rss-546ce49d155------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a8da88942cf</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Junrong Lau]]></dc:creator>
            <pubDate>Sun, 02 Apr 2023 11:04:40 GMT</pubDate>
            <atom:updated>2023-04-07T17:47:08.582Z</atom:updated>
            <content:encoded><![CDATA[<p>With the popularity of Spark along with its capabilities and power, here are 5 tips to maximize the performance of your queries</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zwp7_5c-Q2Q4jH-U" /><figcaption>Photo by <a href="https://unsplash.com/@ericwebr?utm_source=medium&amp;utm_medium=referral">Eric Weber</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>In my day-to-day job, one of the most interesting problems I face is when users consult on the optimization of their spark ETL pipelines. They usually present learning opportunities as every person and team works with different datasets and different types of problems to solve.</p><p>After a year of shadowing and learning from our experienced solution architects, here are 5 common areas that allow us to speed up and optimize our queries.</p><h3>Tip #1 — Filter as much data as possible</h3><p>Generally, we would want to only pull out the data that we require in our queries. This helps us in saving the cost and time needed in our read operation and ensuring that we only perform the transformations on the data that is relevant to us. I usually liken this scenario to that of moving houses— You wouldn’t shift all your belongings to your new place before deciding which you should discard, right? It makes more sense to only bring the ones you need to your new home, and then discard the rest. It is simply more energy and time efficient.</p><p>There are 2 kinds of filtering here. The first is <strong>partition filters</strong>, where we should be filtering based on how the underlying table is being partitioned. Usually, it would be some sort of a date column. You can do a simple check using</p><pre>DESCRIBE TABLE EXTENDED my_table</pre><p>to find out which partition column your table is using. Make sure we only retrieve the relevant data based on this partition, as much as possible. Since our underlying table would essentially be stored as multiple, separate files (based on the partitioning column), pulling only the files we need would greatly reduce the time taken to scan through all folders and load our table.</p><p>The second would be <strong>pushed filters</strong>. These are essentially filters that get “pushed” down into the source table, from anywhere in the entire Spark job. For instance, if you join multiple order tables together, perform several transformations, and only filter out the customer ID at the end, what happens is that Spark will try to move this filter to when you first load the orders table, so you don’t unnecessarily include other Customer’s data in your transformations.</p><p>However, not every query is straightforward and hence, there may be cases where the filter fails to get “pushed” to the source. (i.e. if you were to cache an intermediate dataset)</p><p>Hence, it would always be a good idea to double-check the spark query plan to see if it gets included.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*3zQQgFF3aXeOnBcLI9CZXw.png" /><figcaption>Viewing the partition / pushed filters when a table is scanned</figcaption></figure><p>As highlighted above, you can see that for the below query, our partition filters are included as <em>date = 20230215</em> and our pushed filters are for <em>country_id = 3</em></p><pre>SELECT order_id, sales_amount, country_id<br>FROM sales.daily_orders<br>WHERE country_id = 3<br>  AND date = 20230215</pre><p>Apart from the above, we should also select only the columns relevant to us. All of this help to bring the size of our data down which in turn, speeds up other transformation processes.</p><h3>Tip #2 — Broadcast Hash Joins for dimension tables</h3><p>When joining your tables, there are several types of joins that will be used (SortMergeJoin, ShuffleHashJoin, etc). The most efficient join would be the Broadcast join. This join works by broadcasting the smaller table to all nodes of the spark application, and in this way, the smaller table will not need to get shuffled across partitions during the transformation. Usually, the smaller table in this case refers to a dimension table, and spark sets this threshold under 1.5GB. We can do a simple check on the physical space for delta tables:</p><pre>spark.sql(&quot;describe detail schema.delta_table_name&quot;).select(&quot;sizeInBytes&quot;).collect()</pre><p>However, there may be cases where your dimension table exceeds 1.5GB or a fact table is below 1.5GB. If it happens, we can either increase this limit</p><pre>spark.conf.set(&quot;spark.sql.autoBroadcastJoinThreshold&quot;, 12345678)</pre><p>Or we can include the broadcast join hint in our join query</p><pre>from pyspark.sql.functions import broadcast<br><br>fact_table.join(<br>  broadcast(dimension_table),<br>  dimension_table.id = fact_table.id<br>)</pre><p>Do take note of the caveats while using this; There is a hard limit of about 8GB (as of Spark 3.4) and that it should still be able to fit into driver and executor memory, else we would start getting OOM errors. Therefore, if your table is expected to increase drastically in size in the future, please avoid doing this.</p><h3>Tip #3 — Caching intermediate datasets</h3><p>Spark evaluates transformations lazily. That is to say, no actual computations are done until we perform an “action”, like displaying the final dataset or a count operation. This is why spark is so powerful, it chains all the transformations and then optimizes them where possible.</p><p>But this means that when you store any Dataframes in a variable, to be shared as a common, intermediate Dataframe, it does not actually “exist” physically. Let me show you what I mean. Take the below transformation for instance, where <em>sales_df </em>is our fact table containing daily sales data and <em>employee_df </em>is our dimension table holding employee details</p><pre>sales_employee_df = sales_df.join(employee_df, how=&#39;left&#39;, on=&#39;employee_id&#39;)</pre><p>we have joined both tables and assigned them to <em>sales_employee_df</em>. If we were to perform 2 separate transformations, for example:</p><pre>sales_by_employee = sales_employee_df.groupBy(&quot;employee_id&quot;).sum(&quot;sales_amount&quot;)<br>sales_by_region = sales_employee_df.groupBy(&quot;employee_country&quot;).sum(&quot;sales_amount&quot;)</pre><p>We would then trigger the join transformation (between sales and employee df) twice! To spark, these are 2 separate spark jobs and hence, will get submitted twice and incur double the cost and time.</p><p>This may not be a complicated transformation but let&#39;s say our intermediate dataset was a very expensive operation (involving joining on millions of rows from several tables) then the differences start to show.</p><p>To resolve this, we can make use of caching. This allows us to persist the dataset in memory, to be reused whenever needed. However, it is important to note that we should only cache a Dataframe when it will be reused many times throughout the pipeline and that the intermediate Dataframe is a result of long and costly transformations. We should also remember to unpersist it when it is no longer needed.</p><p>To cache a Dataframe, you can invoke the <em>.cache()</em> or <em>.persist()</em> methods. However, they are lazy transformations so we need to invoke an action method like <em>.count()</em></p><pre>sales_employee_df.cache()<br>sales_employee_df.count()</pre><h3>Tip #4 — Avoid UDFs</h3><p>At some point, you would have come across or even used <em>User-Defined Functions (UDFs) </em>in your spark pipelines. While it is a convenient method of defining and applying custom functions, it heavily slows down the efficiencies of your queries, especially if it&#39;s in python. The reason is that the code needs to be serialized and deserialized between the Python Interpreter and JVM, rather than having the Spark SQL query run directly on JVM itself, which introduces overheads. Also, some optimizations like predicate pushdown filters cannot work when we are dealing with UDFs.</p><p>Hence, we should try to avoid incorporating them into our pipelines as much as possible. Chances are, what you are trying to do can be done using native spark transformations, or higher-order SQL functions. If they absolutely must be used, consider trying out Scala UDFs or Pandas UDFs.</p><h3>Tip #5 — Check for skew and spill in your spark jobs</h3><p>For this tip, we would have to dive into the spark history page. It is a slightly more complicated problem that may take another article to cover, but we can attempt some quick fixes and pinpoint the root of the issue.</p><p>First, head over to the spark history server page. If you’re using Databricks, you can easily access it from your cluster’s Spark UI. Find your spark job under the Jobs page, and then take a look at the task metrics.</p><p>If you see the presence of <em>Spill (Disk/Memory) </em>on this page, that indicates that a spill is happening. It is likely to be caused by the shuffling in your dataset (group by, joins). It happens when data is processed in the executors are unable to hold so much data in memory/RAM, which results in them having to save some of it into the disk first. Hence the term spill.</p><p>Additionally, the <em>Summary Metrics</em> will show you the distribution of the records and duration of the tasks as well, where you can check for skew.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b0uiQTBctRUj1htl5Hr-MQ.png" /><figcaption>Distribution of the tasks in a single stage</figcaption></figure><p>In the above example, we can see that from the 75th to 100th percentile, tasks are taking upwards of 500 seconds to complete, and they are handling records that are several times more than other tasks in the 0 to 75th percentile. This phenomenon is described as skew, and it results in a bottleneck in performance because most of your tasks take relatively shorter to complete while there are a few tasks that are stuck and take a way longer time to complete, due to an imbalance in the distribution of records for each task.</p><p>Skew and spill can be related to one another, and if you resolve your skewed data issues, the spill issue may very well be fixed due to a more even distribution, which makes it less likely that only one or two cores are sharing most of the load.</p><p>To fix these issues, we can try the following</p><ul><li>Check that AQE is enabled, and if not, enable it via spark.conf.set(&quot;spark.sql.adaptive.enabled&quot;, true). This may solve the common underlying issues.</li><li>Check that dim tables are using Broadcast hash join as mentioned above</li><li>Inspect your Dataframe before performing a join. For example, there may be a large number of NULLs in the join key. We can then separate them out first, then join the rest of the dataset, and then lastly do a union to piece them back together.</li><li>Tuning shuffle partitions to ensure each partition handles about 200MB worth of data spark.conf.set(&quot;spark.sql.shuffle.partitions&quot;, 12345)</li><li>Salting (last resort)</li></ul><p>Do take note that you need to assess your situation and try different methods to see what works for your dataset and situation. We may not have enough time to cover all of the above methods but that should be enough for you to further deep-dive into the possible methods to fix this.</p><h3>Closing</h3><p>If you are new to spark, all this may seem very overwhelming. Not to worry though, I have developed a <em>python library</em> that easily extracts metrics and details from the spark UI (Databricks), analyzes and detects the issues you may be facing, and recommends the possible next steps to take.</p><p>It is also open source and can work with other environments (albeit with some configuration setup). You can find the GitHub repository <a href="https://github.com/junronglau/spark-monkey">here</a>.</p><p><a href="https://github.com/junronglau/spark-monkey">GitHub - junronglau/spark-monkey: Helper package for spark SQL queries (Databricks)</a></p><p>Stay tuned if you want to see an article about this library, and reach out via <a href="https://www.linkedin.com/in/junronglau/">LinkedIn </a>if you have any questions or collaboration ideas on this. I will be always up for a chat.</p><p><strong>Connect with me: </strong><a href="https://www.linkedin.com/in/junronglau/"><strong>https://www.linkedin.com/in/junronglau/</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a8da88942cf" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/speed-up-your-spark-queries-in-15-minutes-4a8da88942cf">Speed up your spark queries in 15 minutes</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>