<?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 Salim Sayed on Medium]]></title>
        <description><![CDATA[Stories by Salim Sayed on Medium]]></description>
        <link>https://medium.com/@salim-sayed?source=rss-94ade61bf318------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*AATmxpw3Dmap1RzZuMydtw.jpeg</url>
            <title>Stories by Salim Sayed on Medium</title>
            <link>https://medium.com/@salim-sayed?source=rss-94ade61bf318------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 07:17:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@salim-sayed/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[Solar Panels, the economic way]]></title>
            <link>https://salim-sayed.medium.com/solar-panels-the-economic-way-0f7200c39c42?source=rss-94ade61bf318------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f7200c39c42</guid>
            <category><![CDATA[bestofsolar]]></category>
            <category><![CDATA[bestsolarpanels]]></category>
            <category><![CDATA[solar-panel-installation]]></category>
            <category><![CDATA[ilshine]]></category>
            <category><![CDATA[solar]]></category>
            <dc:creator><![CDATA[Salim Sayed]]></dc:creator>
            <pubDate>Wed, 11 Oct 2023 02:08:55 GMT</pubDate>
            <atom:updated>2023-12-13T14:30:42.996Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6i9sDl5_yf7BaXxM0yEkkg.jpeg" /></figure><h3>Introduction</h3><p>Recently I have got solar panels for my house, as a result I geeked so much about it. Here I will share all the tips and tricks I have learned to get you the most economic and optimal way to install solar. The hyper links on the underscored words would provide more information on the topic.</p><h3>Solar Installers</h3><p>There are national and local solar installers like Tesla, SunPower, ADT and Project Solar, etc being national players and many local players like RxSun, CertaSun, Midwest Solar Installers, etc.</p><p>The main difference is the flexibility in choosing the solar panels, reaction time, treatment of state incentive and cost. <strong>I choose RxSun to install solar and paid full cash, </strong>I will compare several others installers below to guide you make your decision.</p><h3>Cost</h3><p>The cost of going solar depends on following factors —</p><ol><li><strong>Cost of the equipments</strong>, permits, installation. The more efficient, lower degradation solar panels and higher efficient inverters are more expensive. The lower degradation solar panels give more power over its life, that provides more incentives. You may need higher efficiency panels only if you have less sun exposure.</li><li><strong>State Incentives, rebate and tax credit. </strong>Here I will discuss IL’s SREC program from my own experience. This is the largest incentive in IL.</li><li><a href="https://www.irs.gov/credits-deductions/residential-clean-energy-credit"><strong>Federal tax credit of 30%</strong></a><strong>. </strong>This is applied on the cost of the solar project minus any discounts. <a href="https://www.irs.gov/credits-deductions/residential-clean-energy-credit">Usually the state incentives are not deducted as a discount</a>, however some installers treat it as a rebate.</li><li><strong>Finance cost</strong>. This is a significant cost. The lease systems are the most expensive in long run, followed by loan and <strong>the best is self financed cach purchase</strong>. You may hear installers offering no interest loan, be aware that may be about 10% expensive that full cash option. Money is never interest free!</li><li><strong>Warranty</strong>. The equipment comes with manufacture warranty but labor is not covered. Some local installers don’t give any additional warranty, national installers like Tesla/Project Solar give 10 years and RxSun gives 25 years of warranty. This is about 10 cents/watt to buy additional warranty. You may not need it if the roof needs replacement in 10-15 years, because you would need to uninstall/reinstall the panels anyways.</li><li><strong>Increase in home insurance</strong>. This can’t be avoided. It may be reduced if you can get LEEDS certification for your home as some insurers like Travelers give discount for that, but again there is cost to get the certification.</li><li><strong>Unplanned roof repair</strong>. This could be significant and would throw away any savings you are expecting. The most common one is having to repair an old roof. The damage due to natural causes and manufacturing defect will be covered by the warranty and insurance.</li><li><strong>Electrical upgrades.</strong> Your electrical system needs to be upgraded to current code. This is additional cost and also offers some opportunities like 200A upgrade.</li><li><strong>Roof orientation</strong>. The south facing roof produces the most energy, that is about 30% more than west facing roof and 40% more than east facing roof (assuming no shades). I wouldn’t think twice to go solar if I have south facing roof, because I would be helping the environment as well as saving money. Sometimes the designers don’t fit all panels on the best sun exposed roof, you should push for it and suggest if they can change the orientation to portrait or landscape to fit more panels.</li></ol><blockquote>If you are getting a new roof then take that opportunity to clear out the south and east sides so that more solar panels can fit there. Sometimes changing the panel orientation can fit more panels on a roof surface.</blockquote><p><a href="https://www.comed.com/SmartEnergy/MyGreenPowerConnection/Pages/SolarRebates.aspx"><strong>10. Comed DG Rebate</strong></a>. This rebate means you will sell all the excess energy to Comed and not take the net metering facility. You will sell excess energy generated in day time and pay for the energy you use when sun is not there. <strong>I will not take it in IL</strong>. It may make sense in sunny state if available.</p><h3><strong>Panel and Inverter Choice</strong></h3><p>Go for the best manufactures offering best warranty out of the box and the ones that degrade the least. I love REC panels because they degrade the least, <a href="https://usa.recgroup.com/products/rec-n-peak-3-black-usa?parent=1480&amp;type=product">they would be left with 92% generation capacity after 25 years</a>. The Sunpower panels have similar degradation but are expensive than REC. The LG and Hanwah Q Cell degrade more than REC/SunPower.</p><blockquote>I went with REC N Peak 3. Lower degradation panels are better investment choice as they generate more power over the years and earn more rebate. You mayn’t need higher efficiency panels because the ROI mayn’t be worth it, rather you can get an additional panel if you have space.</blockquote><p>Most of the installers provide micro inverters except Tesla and SunRun that provide string inverter. The Enphase micro inverters are market leaders, they come with 25 years of warranty, and are also the most expensive. The Tesla’s string inverter has 12.5 years of warranty. <strong>You don’t have a choice between String vs Micro because the installers will decide for you.</strong></p><p>You can however choose a higher efficient Micro inverter so that the power generation is not clipped. Clipping means the panels generate more power than the inverter can consume so the inverter caps it at <strong>maximum continuous output power </strong>rating. The ratio between the panel’s output power and inverter’s maximum continuous output power should be around 1.2. This is also known as DC/AC ratio. The higher the number the higher the loss and lower the number more expensive the inverter.</p><blockquote><strong>If you have higher sun exposer like south facing roof then stick to 1.2 strictly.</strong></blockquote><blockquote>I chose <strong>IQ8M-72–2-US </strong>Enphase microinverters<strong>. Often this upgrade is not expensive, </strong>so definitely ask the cost before picking the default choice the installer gives you. Often the upgrade is $10–20 additional per unit.</blockquote><h3>IL State incentive and Federal credit</h3><p><a href="https://illinoisabp.com/wp-content/uploads/2018/12/Brochurev2.pdf">SREC (aka IL Shine)</a> incentive can’t be claimed by the home owners directly, you need to use a SREC aggregator. Sometimes the installer is also an aggregator like Tesla, CertaSun, etc but mostly local installers use a 3rd part aggregator like Carbon Solutions Groups, etc who would take a 10% cut. One exception being CertaSun that pays 100% of the SREC. Some installers like Project-Solar would let you handle it yourself.</p><blockquote>SREC is $83.75/MW (2023–24 rate ) for 15 years, but most likely you will receive lesser due to commission and escrow. Usually the national installers like Tesla, SunPower have their own calculation and would pay less than official SREC price because they use this as a rebate to reduce the cost of installation.</blockquote><p><strong>For federal tax credit you can use a tax consultant</strong>. I conclude that the <a href="https://www.irs.gov/credits-deductions/residential-clean-energy-credit">30% credit is given on the cost of the system minus any rebate. The state incentives like SREC are not rebate and need not be subtracted from the cost, rather it needs to be reported as earning</a>. The national installers like Tesla and SunPower treat the SREC as a way to reduce the cost of system, so the federal tax rebate is reduced when you are under 30% of tax bracket.</p><blockquote>Imagine a system costs $15,000 and SREC is $6000.</blockquote><blockquote>If the SREC is considered as rebate as per the national installers, the cost of the system becomes $9,000 and the tax credit is 30% of that $2,700.</blockquote><blockquote>If the SREC is applied separately and you pay full $15,000 to the installer then the tax credit is 30% of $15,000 = $4,500. The additional 22% tax on $6,000 is $1320 so the final savings is $3,180 (assuming tax bracket of 22%).</blockquote><blockquote><strong>This is $480 of additional savings for $6,000 SREC when it is claimed separately</strong>.</blockquote><h3>Financing</h3><blockquote>Any kind of financing will increase the cost of the system and the cash option will be the cheapest.</blockquote><p>I bought with 100% cash.</p><p>If I had to finance then I liked RxSun’s no interest loan for 18 months and it was about 12% expensive. I also liked Tesla’s no cost until after installation (except $100).</p><h3>Risk</h3><p>The overall risk is reduced when you have warranty. There is additional risk if you are using a smaller company that has higher chance of <a href="https://chicago.suntimes.com/2023/5/15/23724302/sun-badger-solar-panel-lawsuit-scam">going bankrupt like Sun Badger</a> and paying more money upfront. When paying by cash, most of the installers asked 80% of payment before installation.</p><blockquote>I found Tesla best from overall risk point of view.</blockquote><h3>Timing of installation</h3><blockquote>If you are paying 100% cash then the last quarter of the year is the best time because you can claim the federal credit the same year.</blockquote><p>The current short term bond yield is about 5% so that can give you additional $300 savings (assuming $6,000 being the credit).</p><h3>Avoid Roof Repair</h3><p>It will be extremely costly (more than $3,000) if you have to uninstall the panels to repair roof and then reinstall. The best way to avoid this would be to get a new roof if it is more than 10 years old. If the roof is about 7 years old then wait a couple of years to get new roof then get solar. Additionally get long lasting shingles.</p><h3>Comparison of Installers</h3><p>Here is my evaluation of the installers in the descending order of my choice. <strong>The hyper links are my referral links, hoping this article has helped you.</strong></p><p><a href="https://advocator.getthereferral.com/registerAdvocate?company=MjA3Mg==&amp;salesRep=NTUyOTYy">RxSun</a> — The cost was extremely competitive (under $3 a watt), the marketing and design teams were extremely responsive, freedom to choose equipments, 25 years of warranty, and treating SREC as incentive made it the overall best and cheapest for me.</p><p><a href="https://ts.la/mohammed53331">Tesla</a> — Their cost is also extremely competitive, they give $500 discount for existing Tesla customers, being a $700B company they are the least risky and you pay only $100 until installation. Their SREC payment was less, restricted choice of panels, inverter, and less warranty are the down sides. <strong>It is a great option if you have 5–7 years old roof so you don’t need longer warranty and you don’t want any risk.</strong></p><p><a href="https://projectsolar.com/r?id=igv9h3">Project Solar</a> — Their cost, panels choices (QCell), and 10 years warranty are at par with Tesla. You can’t change panels but you can upgrade the inverters. They will let you handle the state incentives. There cost is extremely competitive, but lack to longer warranty and not able to use better panels was the blocker for me. <strong>It is a great option if you have 5–7 years old roof and you are not an existing Tesla customer.</strong></p><p><a href="https://advocator.getthereferral.com/registerAdvocate?company=MTAzMg==">CertaSun</a> — Their cost is higher than 3 above though they give 100% of SREC, and generation guarantee. They only install Sun Power’s equipments that are top of the line. If you must need Sun Power’s panels then Certa Sun is the best.</p><p>Sun Power — They are the most experienced, few years back they wouldn’t take small installations. They are vertically integrated, provide top of the line equipment and have good rating for customer service. Their cost is higher than Certa Sun for the same equipment and they treat SREC as rebate.</p><p>Midwest Solar Installers — This is another local installer. They provide all kinds of equipment choices and can manage the cost down by juggling the different panel and inverter combinations, they charge only 30% upfront fee for cash purchase where as others charge 80%. Their overall cost was higher.</p><p>ADT, Palmetto — Palmetto installs for itself as well as for Project Solar. Their cost is somewhat around CertaSun’s. I didn’t work with them or ADT much deeply, but it seemed they are a good competition to CertaSun. If you like CersSun then do consult them as well.</p><h3>My recommendation</h3><p>I will advice to install Solar on new roof using full cash purchase and use the south or at least west facing roof as much as possible. Get the best equipments that will not require maintenance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f7200c39c42" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Local cache to improve legacy app’s performance]]></title>
            <link>https://salim-sayed.medium.com/local-cache-to-improve-legacy-apps-performance-f1d443e12ba6?source=rss-94ade61bf318------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1d443e12ba6</guid>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[caching]]></category>
            <dc:creator><![CDATA[Salim Sayed]]></dc:creator>
            <pubDate>Wed, 04 Oct 2023 20:49:26 GMT</pubDate>
            <atom:updated>2023-10-04T20:49:26.017Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Anb9PacfTDECkDUBSpStHQ.jpeg" /></figure><h3>Introduction</h3><p>In this article we would discuss <a href="https://www.ehcache.org/">EhCache</a>, an open-source Java based library, for a local caching solution. There are several tools available and the most famous among them is Redis. It is available as a cloud native solution in the large cloud service providers, hence pretty easy to adopt. EhCache also provides similar capabilities like Redis to store cache both locally and centrally. Particularly the local cache solution of EhCache is better than Redis and has more features. This could be a way to improve performance of a legacy application with less effort.</p><h3>Local Cache</h3><p>The simplest form for of local cache is a static object in JVM’s heap. This is the fastest way to retrieve data. This is a perfect solution for a single process, however mostly several instances of a process needs to run (horizontal scaling). They need to communication between that leads to a centralized cache solution. Centralized cache is slower as it involves network latency and that reduces the advantages as compared to be a standard Key-Value database.</p><p>Local cache is still relevant for applications that,</p><ol><li>Have only 1 process running like a desktop application</li><li>The local cache needs to sync to a database rather than a central cache</li><li>You are looking for improving performance in a legacy application with little effort</li><li>You have large amount of read-only immutable objects that doesn’t changes that frequently. Example — stock symbols, medical procedures, Cars make and model</li></ol><p>The cache in heap has downsides like GC would run more often, though the GC can be tuned to avoid this it is undesirable. Ehcache provides a way to use offheap memory and disk for caching. Cache on offheap memory is also fast but it wouldn’t have any additional GC pressure.</p><h3>Performance of local cache</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*5u9SDzhS4fi4NYhaJEFo_w.png" /></figure><h3>EhCache</h3><p>It is a <a href="https://www.ehcache.org/documentation/3.10/107.html">java based ope-source library that adhears to Java temporary caching API (JSR 107)</a>. It has a very simple implementation that uses a cache configuration XML, EhCache API and enough memory/disk available.</p><p>In the cache configuration you can define multiple cache namespaces, for each namespace define the key, value, heap, off-heap and disk capacity.</p><pre>&lt;config<br>        xmlns:xsi=&#39;http://www.w3.org/2001/XMLSchema-instance&#39;<br>        xmlns=&#39;http://www.ehcache.org/v3&#39;<br>        xmlns:jsr107=&#39;http://www.ehcache.org/v3/jsr107&#39;<br>        xsi:schemaLocation=&quot;http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.0.xsd<br>        http://www.ehcache.org/v3/jsr107<br>        http://www.ehcache.org/schema/ehcache-107-ext-3.0.xsd &quot;&gt;<br><br>    &lt;persistence directory=&quot;&lt;path to cache&gt;&quot; /&gt;<br>    &lt;cache alias=&quot;jCache&quot; &gt;<br>        &lt;key-type&gt;java.lang.Long&lt;/key-type&gt;<br>        &lt;value-type&gt;java.lang.String&lt;/value-type&gt;<br>        &lt;heap unit=&quot;entries&quot;&gt;100&lt;/heap&gt;<br>        &lt;disk persistent=&quot;true&quot; unit=&quot;GB&quot;&gt;40&lt;/disk&gt;<br>    &lt;/cache&gt;<br><br>&lt;/config&gt;</pre><p>The cache can be accessed with simple code as follows,</p><pre>import javax.cache.Cache;<br>import javax.cache.CacheManager;<br>import javax.cache.Caching;<br>import javax.cache.spi.CachingProvider;<br>import java.net.URISyntaxException;<br><br>CachingProvider provider = Caching.getCachingProvider(&quot;org.ehcache.jsr107.EhcacheCachingProvider&quot;);<br><br>CacheManager cacheManager = provider.getCacheManager(<br>        this.getClass().getClassLoader().getResource(&quot;ehCache-jcache-Config.xml&quot;).toURI(),<br>        this.getClass().getClassLoader());<br><br>try(Cache&lt;Long, String&gt; cache = cacheManager.getCache(&quot;jCache&quot;)) {<br>    cache.put(1L, &quot;one-uno-ek&quot;);<br>    String value = cache.get(1L);<br><br>    System.out.println(String.format(&quot;The output is %s &quot;, value));<br>}</pre><p>The above example uses Java Temporary Caching API so that you can change the cache provider without changing your code. However EhCache’s own library has more features so that can be used too.</p><h3>EhCache Performance Result</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*PwM_6HdfjAL3CIR29Mt5Dg.png" /></figure><p>Interestingly there is not much performance difference between disk vs off-heap. Theoretically off-heap should be a little slower than on-heap.</p><p>Note — My colleague Anchal Jain also participated in this research.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1d443e12ba6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Database Choice shouldn’t be so Confusing]]></title>
            <link>https://salim-sayed.medium.com/database-choice-shouldnt-be-so-confusing-a85f2cb1f?source=rss-94ade61bf318------2</link>
            <guid isPermaLink="false">https://medium.com/p/a85f2cb1f</guid>
            <dc:creator><![CDATA[Salim Sayed]]></dc:creator>
            <pubDate>Mon, 25 Sep 2023 16:28:27 GMT</pubDate>
            <atom:updated>2023-09-27T16:03:40.246Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rIB19v7nj0vr00QgD_bVrg.jpeg" /></figure><h3>Introduction</h3><p>Database is a critical component of any software system and often the bottleneck for scalability and performance. This makes it the center of hot arguments, extreme vetting and makes DB centric code a rewrite candidate. It has attracted great innovations like the Dynamo paper. But still the scene is very confusing to choose an appropriate DB for a job and pass the test of time.</p><h3>Confusion</h3><p>Databases are feature rich and their developers are extremely competitive. In recent past both the RDBMS and NoSQL databases (specifically Document, Wide-Column and KeyValue) have adopted the features of each other. Many RDBMS supports BSON schema, sharding for horizontal scalability and <a href="https://www.techtarget.com/searchdatamanagement/definition/MPP-database-massively-parallel-processing-database">MPP architecture</a>. On the other hand NoSQL databases can support transactions across multiple tables, support reference (like foreign key), support JOINs etc. We need to understand the inner workings of these technologies, budget and human resource aspects to make a better decision.</p><h3>Theory of Databases</h3><p><strong>CAP theorem</strong> — It has been proven that Consistency, Availability can’t be provided when network Partition occurs. Network partition means when two nodes of a DB can’t communicate or there is a delay. This doesn’t always happen, but when it does you need to pick one out of Consistency (same state of data is visible) or Availability (DB is accessible).</p><p><strong>RDBMS</strong> — This has been the most popular choice until about 10 years back. Its foundation is based on entity-relationship, optimized for less data, and ACID guarantee for transactions.</p><p>They generally lack in the parallel processing, both in vertical and horizontal sclability aspects. Some DBs do better than others.</p><p>They want to be always consistent for providing ACID guarantee so sometimes they won’t be available.</p><p>Entity-relationship leads data being spread out into multiple tables, so JOIN is required to gather data together for writing business logic. A JOIN operation is <strong>O(log N + N log M + N + M ) </strong>in time complexity to gather data from index and table . However data can be designed to not have JOINS (like NoSQL) and the time complexity would be <strong>O(log N + N)</strong>.</p><p><strong>NoSQL</strong> — This is a loose term that describes entirely different classes of Databases. Document, Wide-Column, Key-Value databases are similar and are applicable for a typical application. File system based (Big data), Graph, Log, Time Series and Ledger databases are for special cases.</p><p>They are built for massive parallel read operations. The Document, Wide-Column, Key-Value databases are great for concurrent but small data reads. The file system bases database (Big data) like Spark Delta-lake are great for less frequent and large amount of data reads. These are designed for scalability from the ground up.</p><p>These support JOIN operation but that gives a major blow to the scalability. The ACID support can be less sophisticated as compared to RDBMS.</p><p>Time complexity for looking up a row is <strong>O(log N), </strong>no separate index and table lookup like RDBMS.</p><p>For Big data system the time complexity is often the full table scan (with some data skipping), that would be O(N). <strong>Big data also takes advantage of quicker continuous disk read as compared to index lookup which uses discrete disk reads.</strong></p><h3>Comparison</h3><p>Read Performance — NoSQL will win over RDBMS. Every read must be planned and coded for. There is no option for ad hoc query.</p><p>Update — RDBMS wins over NoSQL because references data needs to be updated only once. However for NoSQL the design has to be so that reference data is not updated often.</p><p>Scalability — NoSQL wins as the databases are designed from ground up to be scalable and there is option to choose Consistency vs Avaiability. RDBMS gives the option of shard-ing, but you need to be careful not to have JOINS across shards.</p><p>Data model — NoSQL has some advantage being more versatile. Other than some specific use cases the Relational/Document/Key-Value/Wide-Column all can accommodate most of the data models.</p><p>On Premises — if your application is hosted on premises then all kinds of NoSQL databases may not be available to you and you may not have staff to support them. RDBMS being old has more people know it, so it will have the advantage.</p><p>Cost — this is hard to judge. Typically RDBMS being not so great at scalability, with higher volume of processing the cost will be higher than NoSQL. For small volume operations NoSQL may be expensive because they are hardly free in the cloud whereas there are free opensource RDBMS available in the cloud.</p><p>Ad hoc query — RDBMS are great for ad hoc query and hence provides quick turn around time for new features.</p><h3>How to Choose</h3><p>Here is a simple decision tree to get you started.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C342bEk6EdL8chWMe9YT8g.png" /></figure><h3>Notes</h3><p>A great deal is knowledge is shared by <a href="https://www.youtube.com/watch?v=qI_g07C_Q5I&amp;t=2682s">Martin Fowler</a> and <a href="https://www.youtube.com/watch?v=eEENrNKxCdw">Rick Haulihan</a> in these youtube videos.</p><p>Mitchelle Reyes and Maidul Islam are two others peers of mine participated in this research.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a85f2cb1f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spark Delta-lake merge slowness due to skewed partitions]]></title>
            <link>https://salim-sayed.medium.com/spark-delta-lake-merge-slowness-due-to-skewed-partitions-f212285bd04f?source=rss-94ade61bf318------2</link>
            <guid isPermaLink="false">https://medium.com/p/f212285bd04f</guid>
            <dc:creator><![CDATA[Salim Sayed]]></dc:creator>
            <pubDate>Wed, 20 Sep 2023 20:58:06 GMT</pubDate>
            <atom:updated>2023-10-02T19:33:06.041Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Data Partition" src="https://cdn-images-1.medium.com/max/1024/1*wtUC3co-VGMA_iNHGu9CGw.jpeg" /></figure><h3><strong>Note</strong></h3><p>This issue pertains to open-source version of Spark and delta lake. The Databricks version has an entirely different execution plan that is pretty much immune to partition skew related issues for the merge operation. Spark 3.3 and Delta-lake 2.2 are used.</p><h3><strong>Merge Operation</strong></h3><p>This is a delta-lake operation to merge one data set into a delta table. The syntax looks as following. The delta_table1 is partitioned and the partitions are uneven.</p><pre>val delta_table1 = DeltaTable.forPath(&quot;path to delta table 1&quot;) // Partitioned<br>val table2 = ..... a dataframe //partition or not doesn&#39;t matter here<br><br>delta_table1.merge(table2),&quot;join condition .... filter conditions&quot;)<br>.whenMatched().updateAll()<br>.whenNotMatched().insertAll().execute()</pre><p>The delta-lake API, converts this syntax into a series of operations as below</p><pre>== Physical Plan ==<br>AdaptiveSparkPlan (25)<br>+- == Final Plan ==<br>   AQEShuffleRead (17)<br>   +- ShuffleQueryStage (16), Statistics(sizeInBytes=1161.3 GiB, rowCount=1.34E+8)<br>      +- Exchange (15)<br>         +- SerializeFromObject (14)<br>            +- MapPartitions (13)<br>               +- DeserializeToObject (12)<br>                  +- SortMergeJoin FullOuter (11)<br>                     :- Sort (5)<br>                     :  +- ShuffleQueryStage (4), Statistics(sizeInBytes=23.9 GiB, rowCount=1.45E+6)<br>                     :     +- Exchange (3)<br>                     :        +- Project (2)<br>                     :           +- Scan ExistingRDD mergeMaterializedSource (1)<br>                     +- Sort (10)<br>                        +- ShuffleQueryStage (9), Statistics(sizeInBytes=1161.7 GiB, rowCount=1.34E+8)<br>                           +- Exchange (8)<br>                              +- Project (7)<br>                                 +- Scan parquet  (6)<br><br>.... &lt;others parts of the plan are removed&gt; ....<br>(11) SortMergeJoin<br>Left keys [2]: [&lt;join key1&gt;, &lt;join key2&gt;]<br>Right keys [2]: [&lt;join key1&gt;, &lt;join key2&gt;]<br>Join condition: &lt;any filter condition&gt;<br><br>(15) Exchange<br>Input [99]: [&lt;all the columns in delta_table1&gt;]<br>Arguments: hashpartitioning(&lt;partition column as defined for delta table1&gt;#6447L, 105), REPARTITION_BY_COL, [id=#1309]<br><br>.... &lt;others parts of the plan are removed&gt; ....</pre><p>This includes 2 main steps,</p><ol><li>A full outer join between the 2 tables, stage 11</li><li>Rebuild delta_table1 using the defined partition schema, stage 15</li></ol><h3><strong>Rebuild the partitioned delta table</strong></h3><p>This is the last step of the merge operation. After the 2 sets of data been merged, <strong>the result data is repartitioned as per the partitioning strategy defined for the delta table being merged into</strong>. This process involves shuffle of data across partitions, but that is not the slowest part. The slowest part is that it uses only 1 task per partition. If delta_table1 has only 10 partitions then only 10 tasks in parallel will run even though there are more than 10 CPUs assigned to the job. When those partitions are heavily skewed, the tasks for large partitions will take much longer than others, hence full capacity of the cluster won’t be used.</p><p>As depicted below, not all CPUs will be equally loaded and more CPUs than the partitions can’t be used. The following example will take 182 minutes to finish and can only use maximum 6 CPUs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x6VVF3rt5gwgM3YXqGut_w.png" /></figure><h3>Solution</h3><h4>More and even partitions</h4><p>The solution is to create more partitions so that more CPUs can be used in parallel and use a partition key that reduces the skew in size. Sometimes it is not possible to create even partitions but we can always create more partitions.</p><p>The following partitioning schema will result in the job time to be 45 minutes that is about 4X faster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LZmtf_PjTOds2XgkB94dTQ.png" /></figure><h4>Partition strategy</h4><p>Ideally the partitions should be aligned with business use case and the read pattern so that the data is naturally filtered while reading.</p><p>However <strong>for this specific purpose of improving the merge perfrmance you can choose any partitioning strategy as long as there are more and even partitions</strong>. You can use a hash mechanism to evenly divide data.</p><h4>Small file problem</h4><p>Small partitions which are already smaller will even get more smaller. This can’t be avoided fully but can be managed using Spark 3’s adaptive query execution parameters “spark.sql.adaptive.coalescePartitions.*”. <a href="https://spark.apache.org/docs/latest/sql-performance-tuning.html">This documentation</a> will help choose those parameters.</p><h4>What didn’t help</h4><p><strong>Adaptive query execution mechanism</strong></p><p>Spark 3’s adaptive query execution mechanism tries to solve the large file problem using the parameters spark.sql.adaptive.optimizeSkewsInRebalancePartitions.enabled and spark.sql.adaptive.rebalancePartitionsSmallPartitionFactor. But these parameters help the join operation by breaking large partitions into smaller ones to favor parallelism. However unfortunately these parameters don’t help with the rebuilding a partitioned delta-table.</p><p><strong>spark.databricks.delta.merge.repartitionBeforeWrite.enabled</strong></p><p>Enabling this parameter also didn’t help though documentation suggests that it might.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oOSpH6xmGmmz-1kQJWzbRA.png" /></figure><h3>Databricks magic</h3><p>Interestingly Databricks generates an entirely different plan and it doesn’t suffer from this slowness. It uses semi-join rather than a full outer join and entirely skips the rebuil of delta-table. I wish this is released to open source delta lake and Spark sooner than later, but until then you can use this trick.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f212285bd04f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Performance tips for open source Delta Lake — part2]]></title>
            <link>https://salim-sayed.medium.com/performance-tips-for-open-source-delta-lake-part2-9da41a28638d?source=rss-94ade61bf318------2</link>
            <guid isPermaLink="false">https://medium.com/p/9da41a28638d</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[delta-lake]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Salim Sayed]]></dc:creator>
            <pubDate>Sat, 23 Jan 2021 01:05:56 GMT</pubDate>
            <atom:updated>2021-01-23T01:10:46.786Z</atom:updated>
            <content:encoded><![CDATA[<h3>Performance tips for open source Delta Lake — part2</h3><p>As we discussed in my <a href="https://salim-sayed.medium.com/performance-tips-for-spark-delta-lake-part1-adfc5a9e9ce1">last post</a> that the primary mechanism of performance improvement is to reduce the amount of data to be processed; followed by choosing the right operation like delete/update vs merge. Delta lake archives this by partition pruning and data skipping. We know how partition pruning is achieved so let’s just discuss data skipping specially for a runtime environment outside of Databricks.</p><h4>Data Skipping</h4><p>At Databricks environment you can use Z-Order and Optimize command to arrange data in such a way that the statistics on the Parquet files help Spark to skip a file just by looking at those statistics and without scanning the whole file. When Z-Order is not available <strong>you can just order your data using the same keys which you use to update the data</strong>. It is important to maintain the desired order of the data , otherwise the delta lake will become inefficient after each merge process.</p><p>Let’s do an experiment to understand this. Let’s create a delta take and partition it by a column “facility” and arrange that data within each partition by another column “id”.</p><pre>case class Patient(id:String,facility:String, name:String, age:Int, admitOn:Timestamp)</pre><pre>val df = spark.createDataFrame(<em>Seq</em>(<br>  <em>Patient</em>(id=&quot;100&quot;,name=&quot;Name90&quot;,facility = &quot;StJude&quot;,age=10,admitOn = Timestamp.<em>valueOf</em>(&quot;2010-01-01 00:00:00&quot;)),<br>  <em>Patient</em>(id=&quot;110&quot;,name=&quot;Name80&quot;,facility = &quot;StJude&quot;,age=29,admitOn = Timestamp.<em>valueOf</em>(&quot;2019-03-01 00:00:00&quot;)),<br>  <em>Patient</em>(id=&quot;120&quot;,name=&quot;Name70&quot;,facility = &quot;StJude&quot;,age=55,admitOn = Timestamp.<em>valueOf</em>(&quot;2010-04-01 00:00:00&quot;)),<br>  <em>Patient</em>(id=&quot;130&quot;,name=&quot;Name20&quot;,facility = &quot;StJude&quot;,age=92,admitOn = Timestamp.<em>valueOf</em>(&quot;2015-05-01 00:00:00&quot;)),<br>  <em>Patient</em>(id=&quot;140&quot;,name=&quot;Name10&quot;,facility = &quot;StJude&quot;,age=38,admitOn = Timestamp.<em>valueOf</em>(&quot;2010-06-01 00:00:00&quot;)),<br>  <em>Patient</em>(id=&quot;150&quot;,name=&quot;Name40&quot;,facility = &quot;StJude&quot;,age=81,admitOn = Timestamp.<em>valueOf</em>(&quot;2017-07-01 00:00:00&quot;)),<br>  <em>Patient</em>(id=&quot;160&quot;,name=&quot;Name50&quot;,facility = &quot;StJude&quot;,age=15,admitOn = Timestamp.<em>valueOf</em>(&quot;2010-01-01 00:00:00&quot;)),<br>  <em>Patient</em>(id=&quot;170&quot;,name=&quot;Name45&quot;,facility = &quot;StPatrick&quot;,age=90,admitOn = Timestamp.<em>valueOf</em>(&quot;2010-01-11 00:00:00&quot;)),<br>  <em>Patient</em>(id=&quot;180&quot;,name=&quot;Name65&quot;,facility = &quot;StPatrick&quot;,age=80,admitOn = Timestamp.<em>valueOf</em>(&quot;2013-01-21 00:00:00&quot;)),<br>  <em>Patient</em>(id=&quot;190&quot;,name=&quot;Name35&quot;,facility = &quot;StPatrick&quot;,age=20,admitOn = Timestamp.<em>valueOf</em>(&quot;2014-01-01 00:00:00&quot;)),<br>  <em>Patient</em>(id=&quot;200&quot;,name=&quot;Name55&quot;,facility = &quot;StPatrick&quot;,age=30,admitOn = Timestamp.<em>valueOf</em>(&quot;2015-01-01 00:00:00&quot;)),<br>  <em>Patient</em>(id=&quot;210&quot;,name=&quot;Name15&quot;,facility = &quot;StPatrick&quot;,age=19,admitOn = Timestamp.<em>valueOf</em>(&quot;2016-01-01 00:00:00&quot;)),<br>  <em>Patient</em>(id=&quot;220&quot;,name=&quot;Name75&quot;,facility = &quot;StPatrick&quot;,age=51,admitOn = Timestamp.<em>valueOf</em>(&quot;2017-01-01 00:00:00&quot;)),<br>  <em>Patient</em>(id=&quot;250&quot;,name=&quot;Name05&quot;,facility = &quot;StPatrick&quot;,age=5,admitOn = Timestamp.<em>valueOf</em>(&quot;2019-09-21 00:00:00&quot;))<br>))<br><br>df.repartitionByRange(4,df(&quot;facility&quot;),df(&quot;id&quot;).asc).<br>  write.format(&quot;delta&quot;).mode(SaveMode.<em>Overwrite</em>).<br>  partitionBy(&quot;facility&quot;).<br>  save(&quot;/temp/demo/patients&quot;)</pre><p>This is how the data looks like under “/temp/demo/patients/facility=StPatrick/”. Data is in the order of “id” because I used rangePartitionBy , I would have got similar result if I had used orderBy.</p><pre>Content of /temp/demo/patients/facility=StPatrick/part-00002-70831948-6d02-4986-b3db-326e27d30ae4.c000.snappy.parquet<br>+---+------+---+-------------------+<br>| id|  name|age|            admitOn|<br>+---+------+---+-------------------+<br>|170|Name45| 90|2010-01-11 00:00:00|<br>|180|Name65| 80|2013-01-21 00:00:00|<br>|190|Name35| 20|2014-01-01 00:00:00|<br>|200|Name55| 30|2015-01-01 00:00:00|<br>+---+------+---+-------------------+</pre><pre>Content of /temp/demo/patients/facility=StPatrick/<strong>part-00003-dacf9578-88a7-4cba-b31f-d68abdad3faf.c000.snappy.parquet</strong><br>+---+------+---+-------------------+<br>| id|  name|age|            admitOn|<br>+---+------+---+-------------------+<br>|210|Name15| 19|2016-01-01 00:00:00|<br>|220|Name75| 51|2017-01-01 00:00:00|<br>|250|Name05|  5|2019-09-21 00:00:00|<br>+---+------+---+-------------------+</pre><p>The corresponding Parquet files contain max, min statistics for the first 30 columns as determined by spark.databricks.delta.properties.defaults.dataSkippingNumIndexCols parameter. A read/update/delete/merge process for id==220 would skip the 1st file and only recreate the 2nd file . If the data was not arranged then these operation would need to recreate both the files, hence slow.</p><h4>Maintaining ordered data</h4><p><a href="https://salim-sayed.medium.com/performance-tips-for-spark-delta-lake-part1-adfc5a9e9ce1">As we discussed</a> a merge operation updates data using a right outer join . A SortMergeJoin operation hashes the data by join condition, sorts the data by join condition, shuffles it, executes the join for each shuffle partition and then combines the results. In this process the ordering of the data changes to the join condition. So it is necessary for the delta lake to be ordered by exactly the same key which is used for merge, otherwise after each merge the data order will be changed for the touched files and their efficiency will go down. If you have multiple ways to merge data into the delta lake then you will need to reorder it frequently as explained in next section.</p><p>Let’s see an example by updating our delta lake by using “id” as matching condition and then see the order of the data.</p><pre>val update = spark.createDataFrame(Seq(<br><em>Patient</em>(id=&quot;220&quot;,name=&quot;Name75&quot;,facility = &quot;StPatrick&quot;,age=15,admitOn = Timestamp.<em>valueOf</em>(&quot;2015-01-01 00:00:00&quot;)),<br><em>Patient</em>(id=&quot;270&quot;,name=&quot;Name95&quot;,facility = &quot;StPatrick&quot;,age=45,admitOn = Timestamp.<em>valueOf</em>(&quot;2020-01-01 00:00:00&quot;))<br>    ))</pre><pre>val table = DeltaTable.forPath(&quot;/temp/demo/patients/&quot;)</pre><pre>table.as(&quot;h&quot;).merge(update.alias(&quot;u&quot;),&quot;h.id=u.id&quot;).whenMatched().updateAll().whenNotMatched().insertAll().execute()</pre><p>I can see in delta log that only one file got recreated which is faster that recreating both the files. It could skip the other file because data was ordered.</p><pre>.....<br>{<strong>&quot;remove&quot;</strong>:{&quot;path&quot;:&quot;facility=StPatrick/<strong>part-00003-dacf9578-88a7-4cba-b31f-d68abdad3faf.c000.snappy.parquet</strong>&quot;,&quot;deletionTimestamp&quot;:1611358701405,&quot;dataChange&quot;:true}}<br>{&quot;add&quot;:{&quot;path&quot;:&quot;facility=StPatrick/part-00000-37e29125-2503-4d29-a43c-c8fa70dec0da.c000.snappy.parquet&quot;,&quot;partitionValues&quot;:{&quot;facility&quot;:&quot;StPatrick&quot;},&quot;size&quot;:1051,&quot;modificationTime&quot;:1611358701000,&quot;dataChange&quot;:true}}</pre><p>Let’s see that the updated data preservers the order as per the join condition in the merge statement.</p><pre>+---+------+---+-------------------+<br>| id|  name|age|            admitOn|<br>+---+------+---+-------------------+<br>|170|Name45| 90|2010-01-11 00:00:00|<br>|180|Name65| 80|2013-01-21 00:00:00|<br>|190|Name35| 20|2014-01-01 00:00:00|<br>|200|Name55| 30|2015-01-01 00:00:00|<br>+---+------+---+-------------------+</pre><pre>+---+------+---+-------------------+<br>| id|  name|age|            admitOn|<br>+---+------+---+-------------------+<br>|210|Name15| 19|2016-01-01 00:00:00|<br>|220|Name75| 15|2015-01-01 00:00:00|<br>|250|Name05|  5|2019-09-21 00:00:00|<br>|270|Name95| 45|2020-01-01 00:00:00|<br>+---+------+---+-------------------+</pre><blockquote>You need to design the order of the delta lake as per the join condition of the most frequent merge process. This will keep the data eternally ordered, hence performant.</blockquote><p>Let’s see what is the new order if we merge using another join condition, say “name”.</p><pre>val update = spark.createDataFrame(<em>Seq</em>(<br><em>Patient</em>(id=&quot;190&quot;,name=&quot;Name35&quot;,facility = &quot;StPatrick&quot;,age=40,admitOn = Timestamp.<em>valueOf</em>(&quot;2015-01-01 00:00:00&quot;)),<br><em>Patient</em>(id=&quot;220&quot;,name=&quot;Name75&quot;,facility = &quot;StPatrick&quot;,age=15,admitOn = Timestamp.<em>valueOf</em>(&quot;2015-01-01 00:00:00&quot;)),<br><em>Patient</em>(id=&quot;270&quot;,name=&quot;Name95&quot;,facility = &quot;StPatrick&quot;,age=45,admitOn = Timestamp.<em>valueOf</em>(&quot;2020-01-01 00:00:00&quot;))<br>))<br>val table = DeltaTable.<em>forPath</em>(&quot;/temp/demo/patients/&quot;)<br>table.as(&quot;h&quot;).merge(update.alias(&quot;u&quot;),&quot;h.name=u.name&quot;).whenMatched().updateAll().whenNotMatched().insertAll().execute()</pre><p>As you see below both the files are now ordered by “name”. This has disturbed the order by “id” and related statistics. If there is a filter on id==220 then Spark can’t skip any file because min and max range of id for these files will be 170–270 and 200–250, both of them includes 220.</p><pre>+---+------+---+-------------------+<br>| id|  name|age|            admitOn|<br>+---+------+---+-------------------+<br>|290|Name25| 45|2020-01-01 00:00:00|<br>|190|Name35| 40|2015-01-01 00:00:00|<br>|170|Name45| 90|2010-01-11 00:00:00|<br>|180|Name65| 80|2013-01-21 00:00:00|<br>|270|Name95| 45|2020-01-01 00:00:00|<br>+---+------+---+-------------------+</pre><pre>+---+------+---+-------------------+<br>| id|  name|age|            admitOn|<br>+---+------+---+-------------------+<br>|250|Name05|  5|2019-09-21 00:00:00|<br>|210|Name15| 19|2016-01-01 00:00:00|<br>|200|Name55| 30|2015-01-01 00:00:00|<br>|220|Name75| 35|2015-01-01 00:00:00|<br>+---+------+---+-------------------+</pre><h4>Restoring the order</h4><p>In Databricks environment you can use Optimize with Z order but that option is not available outside. However you can always use the following.</p><pre>spark.read.format(&quot;delta&quot;).load(&quot;/temp/demo/patients/&quot;).<br>orderBy(&quot;id&quot;).      write.format(&quot;delta&quot;).option(&quot;dataChange&quot;,&quot;false&quot;).mode(SaveMode.<em>Overwrite</em>).<br>partitionBy(&quot;facility&quot;).<br>save(&quot;/temp/demo/patients/&quot;)</pre><p>Please notice option(&quot;dataChnge&quot;,&quot;false&quot;) , it tells that this operation didn’t cause any data change so any stream consumer won’t get these as new records.</p><p>There are other benefits of Z-order like it work effectively for multiple columns as <a href="https://docs.databricks.com/delta/optimizations/file-mgmt.html">explained here</a>.</p><h4>Can the ordering be done based on multiple columns</h4><p>When ordering is done by multiple columns, data is fully packed based on the 1st column but not so much by 2nd column onwards unless both columns follow the same natural order. This is where Z-Order wins. However you can still use a tip here, try to use the natural identity keys (not surrogate keys) for ordering and use it for all filter operations. This is a narrow case but you will be surprised how much it works.</p><p>Example — if I am searching this dataset by “name” and I happen to always have “id” with me then I would always filter the data by “id” and “name” so that data is skipped by “id”.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9da41a28638d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Performance Tips for Spark Delta Lake — part1]]></title>
            <link>https://salim-sayed.medium.com/performance-tips-for-spark-delta-lake-part1-adfc5a9e9ce1?source=rss-94ade61bf318------2</link>
            <guid isPermaLink="false">https://medium.com/p/adfc5a9e9ce1</guid>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[delta-lake]]></category>
            <dc:creator><![CDATA[Salim Sayed]]></dc:creator>
            <pubDate>Mon, 18 Jan 2021 17:08:14 GMT</pubDate>
            <atom:updated>2021-01-21T02:54:05.569Z</atom:updated>
            <content:encoded><![CDATA[<h3>Performance Tips for Spark Delta Lake — part1</h3><p>A system which has been using a data lake knows very well the painful process of updating records in it and the in-proportionate time and resources it requires for small volume read and write operations. Apache delta lake has helped solve many of these issues as well as ACID transaction control and time travel. In this article we will mainly discuss the tips and tricks for performance improvement using open source Spark delta lake. Unfortunately some key performance features are only available on the Data bricks managed Spark and delta lake environments. You would not be entirely out of luck if you are running Spark workload on-premise or private cloud environments, tips in this article will help.</p><h3>Less data is more performance</h3><p>As you may be aware that the less data we can process to execute an operation the faster the performance would be. A row can’t be updated in a file based data lake, rather the entire file containing that row needs to rewritten. Delta lake operations are optimized to skip as much data as possible and you need to take benefit of those features to the fullest. Records in a delta lake can be</p><ol><li>Added/deleted/updated using the `DeltaTable.merge` statement. This is the most versatile API which can handle all scenarios.</li><li>Updated using `DeltaTable.update` statement.</li><li>Added using `df.write.format(“delta”).mode(SaveMode.Append).save(“path/to/delta-lake”)`.</li></ol><h3>DeltaTable.merge</h3><p>This API skips data as described in the following flowchart. The implementation is <a href="https://github.com/delta-io/delta/blob/7533738c17944d1cbff9913329ed3fe1f9997e13/src/main/scala/org/apache/spark/sql/delta/commands/MergeIntoCommand.scala#L252-L274">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*nDEa-2nSZznJzt67Xw7Cfw.png" /><figcaption>fig 1. merge process flow in delta lake.</figcaption></figure><h3>Tips</h3><ul><li>Provide partition filtering explicitly</li></ul><p>Lets say your merge statement looks like -</p><pre>destination.as(&quot;d&quot;).merge(source.as(&quot;s&quot;),&quot;d.matchKey1=s.matchKey2 and d.partitionKey=s.partitionKey&quot;).whenMatched().updateAll().whenNotMatched().insertAll().execute()</pre><p>It won’t automatically prune the partitions based on the data present in the “source”. You can provide that condition explicitly so that step 5 in the above chart is triggered. If the “source” is much smaller in comparison to “destination” and if it contains data for a subset of partitions then this will save you a huge amount of time.</p><pre>val parts = source.select(&quot;partitionKey&quot;).distinct().collect().map(_.getAs[String](&quot;partitionKey&quot;))</pre><pre>destination.as(&quot;d&quot;).merge(source.as(&quot;s&quot;),&quot;d.matchKey1=s.matchKey2 and d.partitionKey=s.partitionKey and d.partitionKey in (&lt;list of partition keys&gt;)&quot;).whenMatched().updateAll().whenNotMatched().insertAll().execute()</pre><ul><li>Provide Broadcast hint for small “source”</li></ul><p>If the “source” data frame is small, then providing broadcast hint can save time in step 6 of the above flowchart.</p><pre>val parts = source.select(&quot;partitionKey&quot;).distinct().collect().map(_.getAs[String](&quot;partitionKey&quot;))<br></pre><pre>destination.as(&quot;d&quot;).merge(broadcast(source).as(&quot;s&quot;),&quot;d.matchKey1=s.matchKey2 and d.partitionKey=s.partitionKey and d.partitionKey in (&lt;list of partition keys&gt;)&quot;).whenMatched().updateAll().whenNotMatched().insertAll().execute()</pre><ul><li>Use appropriate syntax for Add operations</li></ul><p>Merge is a versatile syntax that can be used for all kinds of operations — add, update and delete. If you simply need to add new data when it doesn’t exist and not add them when a match is found then don’t write `whenMatched` expression. This will use ‘left anti’ join rather than ‘right outer’ join in step 7 which is faster.</p><pre>destination.as(&quot;d&quot;).merge(source.as(&quot;s&quot;),&quot;d.matchKey1=s.matchKey2&quot;).whenNotMatched().insertAll().execute()</pre><p>If you are want to always append/add new records without any check then simple use,</p><pre>source.write.format(&quot;delta&quot;).mode(SaveMode.Append).save(&quot;path/to/delta-lake&quot;)</pre><ul><li>Order data in the delta lake as per the matching condition of merge statement</li></ul><p>This is rather a hard ask to maintain if your have multiple conditions to merge into the delta-lake and you are not using data bricks runtime environment because you can’t use z-index. However if you have a single condition to merge data into the delta lake then you are lucky. Example — lets say your delta lake has 100 columns “column1”,”column2&quot; to “column100” but you always merge data into it using “column1” like `destination.as(“d”).merge(source.as(“s”),”d.column1=s.column1&quot;)….` then you can arrange the delta lake in the order of column1. The underlying parquet files maintain basic statistics like count, min, max which is used by Spark to skip entire files in step 6. This subject needs more conversation and perhaps another post in near future.</p><h3>DeltaTable.update, DeltaTable.delete</h3><p>These operations are faster as compared to DeltaTable.merge as it doesn’t involve join operations as DeltaTable.merge does but rather filter operations alone. The overall flow is same, it finds the files containing the data and then recreates those files with intended updates/deletes.</p><h4>Tips</h4><p>Add filters on partition keys explicitly if possible.</p><p>destinatio.as(&quot;d&quot;).delete(&quot;d.partitionColumn in (&lt;list of values&gt;) and &lt;delete condition&gt;)&quot;</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adfc5a9e9ce1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>