<?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 Mridusingh on Medium]]></title>
        <description><![CDATA[Stories by Mridusingh on Medium]]></description>
        <link>https://medium.com/@mridusingh1991?source=rss-0d9ade9052ea------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*KU8IjmFgak0fdGxA</url>
            <title>Stories by Mridusingh on Medium</title>
            <link>https://medium.com/@mridusingh1991?source=rss-0d9ade9052ea------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 12:57:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mridusingh1991/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[The Mapping Converts. The Business Rule Might Not.]]></title>
            <link>https://medium.com/@mridusingh1991/the-mapping-converts-the-business-rule-might-not-91c25c5318e3?source=rss-0d9ade9052ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/91c25c5318e3</guid>
            <category><![CDATA[cloud-migration]]></category>
            <category><![CDATA[informatica]]></category>
            <category><![CDATA[data-migration]]></category>
            <category><![CDATA[etl]]></category>
            <category><![CDATA[databricks]]></category>
            <dc:creator><![CDATA[Mridusingh]]></dc:creator>
            <pubDate>Mon, 16 Nov 2026 13:57:21 GMT</pubDate>
            <atom:updated>2026-11-16T13:57:21.901Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Why successful Informatica-to-Databricks conversion is only the beginning of ETL modernization.</em></p><p>Most ETL migration conversations start with a simple question: how much of the existing code can we convert automatically?</p><p>It’s an important question. But it isn’t the question that determines whether a migration succeeds.</p><p>A converted mapping can run successfully, produce the expected row count and still calculate the wrong business number.</p><p>That’s because translating transformations is not the same as preserving business semantics. An automated conversion can preserve the structure of a mapping without resolving every business assumption embedded in it. A Lookup becomes a join, an Update Strategy becomes a MERGE, the notebook runs green, and nobody has checked whether earned premium or claim reserves still mean what they meant before.</p><p>I’ll use one hypothetical throughout: a large insurance enterprise retiring a PowerCenter estate that processes policy and claims data. It is an illustrative scenario, not a project report. My background spans approximately eleven years of data engineering across Informatica PowerCenter, SSIS, SQL, Snowflake and Databricks, including an Informatica-to-SSIS modernization project. This article is a technical analysis of the engineering challenges involved in modernizing PowerCenter workloads on Databricks, based on how both platforms behave and on Databricks’ documentation.</p><h3>Assess the estate before conversion</h3><p>Assessment decides sequencing, and sequencing decides risk. Inventory the workflows and their dependencies, then profile each mapping for the places where logic hides: mapplets and reusable transformations, Lookups (caching, SQL overrides, multiple-match policy), Source Qualifier SQL overrides that push business rules into the source database, Update Strategy flags, parameter files and workflow variables, stored procedures and external dependencies.</p><p>Score each object on technical complexity and business criticality. A simple mapping that feeds regulatory reporting deserves more verification than a complicated one feeding a retired dashboard.</p><h3>What automated conversion can and cannot solve</h3><p>Genie Migrate converts Informatica PowerCenter workloads, imported as XML exports, into Databricks notebooks. In the documentation I checked for this article, PowerCenter support is Beta. Two neighbouring products are easy to confuse with it. Lakeflow Connect is a set of managed ingestion connectors, not a mapping converter. Lakebridge is a Databricks Labs migration toolkit, and its documentation does not list PowerCenter as a supported source.</p><p>Automated conversion reduces mechanical effort. It does not certify that business semantics, historical behaviour and financial calculations are equivalent. Genie Migrate’s own guidance says to compare each notebook with its mapping, and row counts and key aggregates with PowerCenter output, before production. That is where validation starts. The loop below shows where reconciliation feeds back into remediation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5OuC1jJO7lEIvFkbKpHqew.png" /></figure><h3>Lookup, Joiner and Update Strategy</h3><p>A PowerCenter Lookup can be configured for what happens when several rows match: return the first, the last, any value, or report an error. A Spark join has no such setting. It returns every match. If a policy has two rows that satisfy the lookup condition, each claim joined to it comes back twice and every additive measure doubles. “First” in the legacy mapping may also have depended on sort order that nobody wrote down, and “any” is non-deterministic by definition. The rule has to be made explicit:</p><pre>from pyspark.sql import functions as F, Window as W</pre><pre>OPEN_END = F.lit(&quot;9999-12-31&quot;).cast(&quot;date&quot;)<br>c, p = claims.alias(&quot;c&quot;), policy.alias(&quot;p&quot;)</pre><pre>candidates = c.join(<br>    p,<br>    (F.col(&quot;c.policy_id&quot;) == F.col(&quot;p.policy_id&quot;))   # use &lt;=&gt; only if the legacy lookup matched NULL keys<br>    &amp; (F.col(&quot;c.loss_date&quot;) &gt;= F.col(&quot;p.effective_start&quot;))<br>    &amp; (F.col(&quot;c.loss_date&quot;) &lt;  F.coalesce(F.col(&quot;p.effective_end&quot;), OPEN_END)),<br>    &quot;left&quot;)                                          # unmatched claims survive with NULL policy columns</pre><pre>one_per_claim = W.partitionBy(&quot;c.claim_id&quot;).orderBy(<br>    F.col(&quot;p.effective_start&quot;).desc(), F.col(&quot;p.policy_version_id&quot;).desc())  # illustrative rule: reconcile with legacy</pre><pre>resolved = (candidates<br>    .withColumn(&quot;rn&quot;, F.row_number().over(one_per_claim))<br>    .filter(&quot;rn = 1&quot;)<br>    .select(&quot;c.*&quot;, &quot;p.policy_version_id&quot;, &quot;p.underwriting_class&quot;))</pre><p>The selection rule here, latest effective start then highest policy_version_id, is illustrative. It does not reproduce every PowerCenter Lookup configuration, so reconcile it with what the legacy Lookup did (first, last, any, error and its ordering) and change it only deliberately. claim_id must uniquely identify an input claim, the tie-breaker must be unique, and the date interval must follow the agreed effective-date semantics. Verify cardinality in a validation task, using write metrics or a post-load count, rather than a count action inside the transformation. Range joins can be expensive, so reduce the policy side to the date window you need and measure before tuning.</p><p>Nulls need the same attention. In Spark SQL a plain = never matches two nulls. If the legacy join matched null keys, you need null-safe equality (&lt;=&gt;); if it did not, keep =. A &quot;not in lookup&quot; pattern ported as NOT IN returns no rows when the subquery contains a null, which NOT EXISTS avoids. For Joiner, check the join type: master and detail outer joins name the side that keeps all rows, so they don&#39;t map onto left and right joins by name.</p><p>Update Strategy needs the most care. PowerCenter’s row-level Update Strategy and target handling can depend on processing and ordering behaviour. A Databricks MERGE, by contrast, requires an unambiguous source-to-target match for updates: when several source rows match one target row, the merge can fail, and Databricks Runtime 16.0 and above checks the ON and WHEN MATCHED conditions for such duplicates. Any implicit winner-selection rule in the legacy pipeline needs to be made explicit before migration. I wouldn’t assume a universal “last row wins”: behaviour depends on mapping configuration and target loading mode, so establish it by running the legacy job with duplicate keys.</p><h3>SCD Type 2: preserving history</h3><p>An SCD Type 2 implementation is not simply a MERGE statement. The effective-date model and the treatment of historical changes matter as much. Decide what sets the effective start: the business-effective timestamp, the source change timestamp or another agreed event-time field. Avoid ingestion time unless that is explicitly the intended business definition. The clocks differ. An endorsement can take effect on 1 March (business-effective), be recorded by the policy system on 14 March (source event time) and be loaded on 15 March (ingestion time). The wrong clock moves as-of reports. Also decide whether intervals are half-open so adjacent versions never overlap, and what the sequencing contract is when two changes share a timestamp. Those are either duplicates or distinct events, and discarding them silently is a business decision made by accident. A unique source event ID plus a source sequence is the safest way to tell them apart.</p><p>A single MERGE handles one in-order change per key per batch. It is not enough when a key has several changes in a batch, because each version’s end depends on the next version’s start. That needs a staged approach: deduplicate on a scoped event ID and remember events across batches, because Delta does not enforce uniqueness and a replay a week later is not caught by deduplicating inside one batch; resolve same-instant events by an explicit sequence; derive versions with window functions; quarantine late arrivals instead of splicing history in place; then close the current row and insert the new versions in one MERGE. Retries need a batch control record, deterministic quarantine keys and a single writer enforced by the orchestrator, because nothing at table level stops two runs overlapping. For change feeds, Lakeflow’s AUTO CDC offers SCD Type 1 and 2 declaratively, but you still map the legacy effective-date semantics onto it.</p><p>The staged implementation is in a <a href="https://github.com/hello-mridu-labs/scd2-databricks-illustrative">companion repository on GitHub</a>. It demonstrates event deduplication across batches, replay handling and SCD2 history management as an illustrative design, not a framework. It quarantines late-arriving events instead of rebuilding history, and its test suite has not yet been run on Databricks, so treat it as unvalidated until you have run it in your own workspace.</p><h3>Data parity: technical correctness versus business correctness</h3><p>Row counts are useful, but they are not proof that the business outcome has been preserved. Validate in layers: source-to-target counts; distinct business keys; null and duplicate profiles; aggregates by the dimensions the business slices by; financial metrics with an explicit tolerance for decimal behaviour; record-level comparison by key or row hash; and, for SCD2, per-key version comparison, because a dimension can match on current rows and be wrong in every historical one.</p><p>Then classify the differences. A technical defect means the new code does not do what the specification says. A business-definition difference means both systems do what their own specifications say, and the specifications differ. Consider an illustrative case. The legacy mapping uses a “first value” lookup against policy versions with an undocumented sort, so a claim takes the earliest overlapping version. The new notebook takes the version in force on the loss date. Portfolio incurred totals agree, but incurred by underwriting class does not, wherever an endorsement changed the class mid-term. Separately, another mapping returns a claim with a 10,000 reserve twice because its lookup has two current rows. That second one is a plain defect.</p><p>Both appear as variances. Engineers fix the defect. A business owner decides which definition is correct, and that decision is recorded and versioned. Triage by root cause, not by table.</p><h3>Scaling and production readiness</h3><p>A design that works on a pilot slice often fails on the full estate. Notebook-side validation, full-table EXCEPT comparisons and MERGE conditions that cannot prune files are all comfortable at small volume. At enterprise volume, I would look at partitioning or clustering aligned to the MERGE predicate, compaction (OPTIMIZE) because incremental loads leave small files, broadcast joins for small dimensions with Adaptive Query Execution handling runtime join selection and skew, incremental processing by change window, and job dependencies that mirror the PowerCenter workflow graph.</p><p>Monitor batch counts, freshness and quarantine volume. Run reconciliation as a scheduled job with alerts, not a cutover task. Keep Bronze immutable so a batch can be replayed. Reconciliation consumes compute too, so tier it: full aggregates and key-level hashes for critical tables, sampling for the rest. I won’t quote performance figures; they only mean something measured on your own data.</p><h3>Conclusion</h3><p>Conversion tooling compresses the mechanical work. What remains is making implicit behaviour explicit (ordering, nulls, cardinality, effective dates), treating parity as a deliverable with owners, and designing every load to be replayed.</p><p>For those who have worked on PowerCenter migrations: which implicit behaviour surprised you most, and how did you catch it before the business did?</p><h3>Documentation referenced</h3><ul><li><a href="https://docs.databricks.com/aws/en/migration/agentic-code-converter">Genie Migrate</a></li><li><a href="https://databrickslabs.github.io/lakebridge/docs/overview/">Lakebridge (Databricks Labs)</a></li><li><a href="https://docs.databricks.com/aws/ingestion/lakeflow-connect">Lakeflow Connect</a></li><li><a href="https://docs.databricks.com/aws/en/delta/merge">Delta Lake MERGE</a></li><li><a href="https://docs.databricks.com/aws/en/ldp/cdc">Lakeflow AUTO CDC APIs</a></li><li><a href="https://spark.apache.org/docs/latest/sql-ref-null-semantics.html">Spark SQL NULL semantics</a></li><li><a href="https://github.com/hello-mridu-labs/scd2-databricks-illustrative">Companion code: illustrative staged SCD Type 2 notebook</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91c25c5318e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Valid SQL, Wrong Business Number: A Join-Fanout Lab for Natural-Language Analytics]]></title>
            <link>https://medium.com/@mridusingh1991/valid-sql-wrong-business-number-a-join-fanout-lab-for-natural-language-analytics-087473f69f3d?source=rss-0d9ade9052ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/087473f69f3d</guid>
            <category><![CDATA[databricks-genie]]></category>
            <category><![CDATA[nl]]></category>
            <dc:creator><![CDATA[Mridusingh]]></dc:creator>
            <pubDate>Mon, 26 Oct 2026 15:28:07 GMT</pubDate>
            <atom:updated>2026-10-26T15:28:07.414Z</atom:updated>
            <content:encoded><![CDATA[<p>A synthetic insurance lab on how grain mismatches produce valid but wrong numbers, and what that means for natural-language analytics on Databricks.</p><h3>A plausible question, a plausible number</h3><p>An analyst asks for total incurred losses by policy type for the current financial year, and a query returns three rows of numbers that look entirely reasonable. Nothing errors, nothing warns, and the totals feed whatever comes next: a reserving discussion, a board pack, a pricing review.</p><p>This article is about the case where that query is valid SQL and still answers a different question from the one the analyst asked. I built a small synthetic insurance dataset, reproduced the failure in DuckDB, fixed it, and then tried to break my own fixes and my own tests. Along the way I connect the lab to natural-language analytics on Databricks, and I am explicit about where the lab ends and where inference begins.</p><p>One limit up front: I have not reproduced this in a Databricks Genie Agent. The bad query below is a query shape I constructed, not SQL that Genie generated. What the lab demonstrates is a failure mode that any system, human or AI, can hit when it combines tables of different grain.</p><h3>The synthetic experiment: 103,500 against 40,500</h3><p>The same question returns 103,500 from the bad query and 40,500 from the corrected one. The data is synthetic, the amounts carry no currency, and the experiment ran in a notebook on DuckDB. I have not run it on a Databricks warehouse.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*l48-EyAGyoOhK-YE3-MHBg.png" /></figure><p>The bad total overstates the expected one by 63,000. It is about 2.56 times the expected value, which is an overstatement of about 155.6%. It is not a 256% increase, a distinction worth keeping straight when you describe errors like this to a stakeholder. The query joined 10 rows from only 4 distinct claims.</p><p>COMMERCIAL_PROPERTY is correct, which matters. One row in three being right makes the output look less suspicious than a uniformly inflated one.</p><h3>Assumptions</h3><p>These are choices for a teaching example, not an insurance accounting standard.</p><ul><li>Financial year: 1 April 2026 to 31 March 2027, with 1 April 2027 as the exclusive upper bound.</li><li>Basis: accident year. A claim is in scope when its loss_date falls in the financial year.</li><li>Valuation date: 26 October 2026.</li><li>Incurred amount: signed paid_amount + reserve_change over the ledger up to the valuation date.</li><li>Recoveries are negative paid amounts, so the figure is net of recoveries.</li><li>IBNR and claim expenses are excluded.</li><li>A claim with no ledger activity and a NULL snapshot is treated as zero.</li></ul><p>The basis matters because “incurred in the financial year” has at least two defensible meanings. Accident-year incurred counts claims whose losses occurred in the year, valued at a date. Movements posted during the financial year count ledger changes by posting date, which includes development on older claims. They are different metrics, and a query that filters on transaction_date while summing a cumulative claim snapshot mixes the two. The bad query below does exactly that, and I come back to it.</p><h3>Understand the grain before the join</h3><p>The error comes from summing a column whose grain is one row per claim after joining to a table whose grain is one row per ledger event. The schema has three tables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*gYAEDp21Ga2PBFkk9lL2-A.png" /></figure><p>claims.incurred_amount is a cumulative snapshot: one number that already includes every payment, reserve movement and recovery for that claim. The ledger holds the events behind it. In this dataset the snapshot is built to reconcile with the ledger, so the signed ledger amount (paid_amount + reserve_change) summed per claim equals the snapshot for every claim that has ledger rows.</p><p>A claim with several ledger events becomes several rows after the join, and the snapshot is repeated on each one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*yjVtWATdvXOxfCl98d7xFA.png" /></figure><p>C4 has a single ledger row, so its snapshot is counted once and comes out right. C5 has no ledger rows and no snapshot value, so the inner join removes it. Both details come back later.</p><h3>The incorrect SQL: valid, plausible, wrong</h3><p>The query below is an intentionally constructed bad query shape. It is not SQL generated by Genie or by any other system. It is the kind of statement a person or a model could write when asked for incurred losses in a financial year and handed a claims table and a ledger.</p><pre>SELECT p.policy_type,<br>       SUM(c.incurred_amount) AS total_incurred,<br>       COUNT(*)               AS joined_rows<br>FROM claims c<br>JOIN policies p            ON p.policy_id = c.policy_id<br>JOIN claim_transactions t  ON t.claim_id  = c.claim_id<br>WHERE t.transaction_date &gt;= DATE &#39;2026-04-01&#39;<br>  AND t.transaction_date &lt;  DATE &#39;2027-04-01&#39;<br>GROUP BY p.policy_type<br>ORDER BY p.policy_type;</pre><p>It runs. The joins are legitimate, the keys are right, and the filter looks like a financial-year filter. The arithmetic of the failure is plain once you count rows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*QeN3wdv_B9stUeMq4Uk1yA.png" /></figure><p>The check that exposes it needs no knowledge of the right answer. Compare the number of rows after the join with the number of distinct claims on the preserved side:</p><pre>SELECT COUNT(*)                    AS rows_after_join,<br>       COUNT(DISTINCT c.claim_id)  AS distinct_claims_after_join,<br>       SUM(c.incurred_amount)      AS repeated_header_sum<br>FROM claims c<br>JOIN claim_transactions t ON t.claim_id = c.claim_id;</pre><p>In the executed notebook this returns 10 rows, 4 distinct claims and a repeated sum of 103,500. Ten rows for four claims means 2.5 rows per claim on average, and a sum taken over a repeated claim-level column is multiplied by that repetition.</p><p>There is a second defect in the query, and it matters for the metric rather than the arithmetic. The metric is accident-year incurred, which is scoped by claims.loss_date. The query scopes by transaction_date. In this dataset every ledger row happens to fall inside the financial year, so the filter removes nothing and the two definitions give the same population. That is a property of the sample data, not of the query. With older claims in the table, the transaction-date filter would change which claims are counted, and the cumulative snapshot would still be summed whole.</p><p>The join itself is not the mistake. A claims-to-ledger join is correct whenever you aggregate ledger columns at ledger grain. The mistake is the combination of a claim-grain measure and a ledger-grain join.</p><h3>The corrected SQL: aggregate to claim grain first</h3><p>The fix is to bring the ledger to the grain of the table it joins to. The ledger is aggregated to one row per claim, restricted to the valuation date, and only then joined to claims and policies. The financial-year filter moves to claims.loss_date, which is what the accident-year definition says.</p><pre>WITH claim_incurred AS (<br>    SELECT claim_id,<br>           SUM(COALESCE(paid_amount, 0) + COALESCE(reserve_change, 0)) AS incurred<br>    FROM claim_transactions<br>    WHERE transaction_date &lt;= DATE &#39;2026-10-26&#39;<br>    GROUP BY claim_id<br>)<br>SELECT p.policy_type,<br>       SUM(COALESCE(ci.incurred, 0)) AS total_incurred,<br>       COUNT(*)                      AS claim_count<br>FROM claims c<br>JOIN policies p              ON p.policy_id = c.policy_id<br>LEFT JOIN claim_incurred ci  ON ci.claim_id = c.claim_id<br>WHERE c.loss_date &gt;= DATE &#39;2026-04-01&#39;<br>  AND c.loss_date &lt;  DATE &#39;2027-04-01&#39;<br>GROUP BY p.policy_type<br>ORDER BY p.policy_type;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*uuvmWclii1loh7_kBANMaw.png" /></figure><p>Three details carry the correctness.</p><ol><li><strong>One row per claim on each side.</strong> After claim_incurred is built, both inputs to the join have one row per claim_id, so nothing can multiply. COUNT(*) is safe here for the same reason.</li><li><strong>LEFT JOIN to the aggregated ledger.</strong> Claim C5 was reported on 24 October 2026 and has no ledger rows yet. An inner join would drop it from the claim count, and in PERSONAL_AUTO the count would read 2 instead of 3. The amount would not change, only because C5 contributes zero. Whether a reported claim with no reserve should count as zero incurred is a modelling decision. Real claims systems often set an initial reserve, so treat this as an assumption of the example.</li><li><strong>COALESCE in two places.</strong> Inside the aggregation it guards against NULL ledger amounts. Outside it turns the NULL that a left join produces for C5 into zero.</li></ol><p>The ledger is the measure source here. The snapshot column is not summed at all. It is used separately as a reconciliation target.</p><p>A note on how I validated the 40,500. My reference total is the sum of the claim snapshots at claim grain, and the corrected ledger query reproduces it for every policy type. Because I built the snapshots to equal the ledger, that agreement holds by construction. It shows the corrected query is internally consistent, not that the snapshot would reconcile in a real system. In production the ledger is usually the system of record and the snapshot is the thing you reconcile against it.</p><h3>Why the obvious shortcuts fail</h3><h3>SUM(DISTINCT amount)</h3><p>The tempting patch for a repeated amount is SUM(DISTINCT c.incurred_amount).</p><pre>SELECT p.policy_type,<br>       SUM(DISTINCT c.incurred_amount) AS distinct_amount_sum<br>FROM claims c<br>JOIN policies p            ON p.policy_id = c.policy_id<br>JOIN claim_transactions t  ON t.claim_id  = c.claim_id<br>WHERE t.transaction_date &gt;= DATE &#39;2026-04-01&#39;<br>  AND t.transaction_date &lt;  DATE &#39;2027-04-01&#39;<br>GROUP BY p.policy_type<br>ORDER BY p.policy_type;</pre><p>On the sample data the total is 28,500, not 40,500. PERSONAL_AUTO comes back as 12,000 against an expected 24,000, because C1 and C2 both carry a snapshot of 12,000 and DISTINCT collapses them into one value.</p><p>The reason is general. DISTINCT deduplicates values, while the fanout duplicates entities. The two coincide only when no two different claims share an amount, and nothing in the data model guarantees that. The result then depends on the data&#39;s value distribution rather than on its keys, so it can be right today and wrong after the next load. In a real portfolio, round reserve figures and standard payment amounts can make collisions likely. If you need one value per claim, dedupe by claim, or better, aggregate at claim grain before joining.</p><h3>An effective-dated dimension can reintroduce the fanout</h3><p>The corrected query is only as safe as its joins. Suppose the policy dimension is stored per policy term instead of per policy. Policy P1 has two terms:</p><pre>CREATE TEMP TABLE policy_terms (<br>  policy_id VARCHAR, policy_type VARCHAR, term_start DATE, term_end DATE<br>);<br>INSERT INTO policy_terms VALUES<br>(&#39;P1&#39;,&#39;PERSONAL_AUTO&#39;, DATE &#39;2025-04-01&#39;, DATE &#39;2026-03-31&#39;),<br>(&#39;P1&#39;,&#39;PERSONAL_AUTO&#39;, DATE &#39;2026-04-01&#39;, DATE &#39;2027-03-31&#39;),<br>(&#39;P2&#39;,&#39;PERSONAL_AUTO&#39;, DATE &#39;2026-04-01&#39;, DATE &#39;2027-03-31&#39;),<br>(&#39;P3&#39;,&#39;HOMEOWNERS&#39;,     DATE &#39;2026-04-01&#39;, DATE &#39;2027-03-31&#39;),<br>(&#39;P4&#39;,&#39;COMMERCIAL_PROPERTY&#39;, DATE &#39;2026-04-01&#39;, DATE &#39;2027-03-31&#39;);</pre><p>The ledger aggregation is already correct, so the only change is the policy join. Joining on policy_id alone matches C1 to both P1 terms:</p><pre>-- claim_incurred CTE as above, then:<br>SELECT pt.policy_type, SUM(COALESCE(ci.incurred, 0)) AS total_incurred<br>FROM claims c<br>JOIN policy_terms pt ON pt.policy_id = c.policy_id<br>LEFT JOIN claim_incurred ci ON ci.claim_id = c.claim_id<br>WHERE c.loss_date &gt;= DATE &#39;2026-04-01&#39; AND c.loss_date &lt; DATE &#39;2027-04-01&#39;<br>GROUP BY pt.policy_type;</pre><p>PERSONAL_AUTO becomes 36,000: C1’s 12,000 is counted twice, plus C2’s 12,000. Adding the effective-date condition to the join key restores 24,000:</p><pre>JOIN policy_terms pt<br>  ON  pt.policy_id = c.policy_id<br>  AND c.loss_date &gt;= pt.term_start<br>  AND c.loss_date &lt;= pt.term_end</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*gasZ1bqAURgGCOJ-C5tNNw.png" /></figure><p>This is a second grain mismatch, one level further from the fact table. The ledger fix does nothing for it, because the duplication now happens in the dimension. It also shows why “the query aggregates first” is not a complete safety argument. Every join in the path needs a stated cardinality.</p><p>A term table with overlapping or gapped dates would break the effective-dated join in other ways, such as zero matches or two matches, so the dimension needs its own integrity checks.</p><h3>Negative tests: can the checks actually fail?</h3><p>A check that has only ever passed tells you little. The notebook therefore injects three known defects and confirms that each is detected. All three tests passed in the executed notebook. They show that these detectors catch these specific defects in this synthetic dataset. They do not show coverage of production defects in general.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*lTd11PV_9Kk20vw8HT8SQA.png" /></figure><h3>Test A: duplicate ledger event</h3><p>The detector fingerprints each event by its attributes. In the notebook the copy of T10 is added inside the query, so the base table stays untouched; run against the table as shown below, the same query returns no rows on clean data.</p><pre>SELECT claim_id, transaction_type, paid_amount, reserve_change, transaction_date,<br>       COUNT(*) AS copies<br>FROM claim_transactions<br>GROUP BY claim_id, transaction_type, paid_amount, reserve_change, transaction_date<br>HAVING COUNT(*) &gt; 1;</pre><p>The limitation is important. Identical attributes do not prove duplication in a real ledger. Two genuine payments of the same amount to the same claim on the same day can exist. A production check should use the source system’s event identifier or a documented business key, and treat an attribute match only as a candidate for review.</p><h3>Test B: snapshot mismatch</h3><pre>WITH ledger AS (<br>  SELECT claim_id,<br>         SUM(COALESCE(paid_amount, 0) + COALESCE(reserve_change, 0)) AS ledger_incurred<br>  FROM claim_transactions<br>  WHERE transaction_date &lt;= DATE &#39;2026-10-26&#39;<br>  GROUP BY claim_id<br>)<br>SELECT c.claim_id,<br>       c.incurred_amount                                        AS snapshot,<br>       COALESCE(l.ledger_incurred, 0)                           AS ledger_incurred,<br>       COALESCE(c.incurred_amount, 0) - COALESCE(l.ledger_incurred, 0) AS difference<br>FROM claims c<br>LEFT JOIN ledger l ON l.claim_id = c.claim_id<br>WHERE ABS(COALESCE(c.incurred_amount, 0) - COALESCE(l.ledger_incurred, 0)) &gt; 0.005;</pre><p>On clean data this returns no rows. After the tamper it reports C1 with a difference of 1,000. In a real system a reconciliation like this will produce legitimate differences from late postings, snapshot timing and valuation cutoffs, so the useful design is a tolerance and an explanation for each class of difference, not a demand for zero.</p><h3>Test C: policy-term fanout</h3><p>The notebook demonstrates the defect by running both joins and comparing totals. That proves the fanout exists and the fix removes it. It is not itself a production detector, because it needs the right answer in advance. A detector that does not need the answer asserts the cardinality directly: every claim must match exactly one term.</p><pre>SELECT c.claim_id, COUNT(*) AS matched_terms<br>FROM claims c<br>JOIN policy_terms pt<br>  ON  pt.policy_id = c.policy_id<br>  AND c.loss_date &gt;= pt.term_start<br>  AND c.loss_date &lt;= pt.term_end<br>GROUP BY c.claim_id<br>HAVING COUNT(*) &lt;&gt; 1;</pre><p>This assertion was not part of the three executed negative tests. I include it as the check I would add, and it should be run and tested like the others before anyone relies on it.</p><h3>What this means for Databricks Genie</h3><p>The lab shows that a grain mismatch produces a valid, plausible and wrong number. It does not show that Genie produces that query. Everything below separates what Databricks documents from what I infer.</p><h3>The inference</h3><p>A natural-language analytics system that generates or selects SQL over several tables has to decide which column to aggregate and how to join. If a claim-grain snapshot and a ledger-grain table are both available and the question mentions a date that lives on the ledger, a query of the shape above is one of the things such a system could produce. That is an engineering inference from how the failure arises, not an observation. I have not tested a Genie Agent, so I cannot say how often, or whether, Genie does this on a schema like mine. The Genie documentation itself says Genie is nondeterministic, so a single clean run would also prove little in either direction.</p><h3>What the documentation supports</h3><p>Databricks now calls these environments Genie Agents, and says they were formerly Genie Spaces (<a href="https://docs.databricks.com/aws/en/genie-agents/monitor">monitoring page</a>). The statements below come from the current pages as I read them.</p><ul><li><strong>Incorrect joins and metric errors are named failure categories.</strong> The <a href="https://docs.databricks.com/aws/en/genie/troubleshooting">troubleshooting page</a> lists them. For joins it suggests defining foreign keys in Unity Catalog, defining join relationships in the knowledge store, or pre-joining tables into a view. For metrics it suggests SQL expressions, example queries, or views that pre-aggregate the metric.</li><li><strong>Join relationships carry a cardinality label.</strong> In the <a href="https://docs.databricks.com/aws/en/genie/knowledge-store">knowledge store</a> you can mark a relationship many to one, one to many or one to one, and Unity Catalog primary and foreign keys are saved as join relationships automatically. In the pages I read, nothing says a defined relationship prevents a generated query from summing a claim-grain column after a fanning-out join. Treat it as context for Genie, not as a guard.</li><li><strong>Business logic as SQL expressions.</strong> The same page says measures, filters and fields defined as SQL expressions give more consistent results than text instructions, and it states that Genie is nondeterministic.</li><li><strong>Pre-joined views and metric views are recommended.</strong> The <a href="https://docs.databricks.com/aws/en/genie/best-practices">best-practices page</a> advises pre-joining or denormalizing with views or metric views, aiming for five or fewer tables, and reviewing the generated SQL. It also advises saving reviewed questions as benchmarks.</li><li><strong>Metric views document fanout explicitly.</strong> The <a href="https://docs.databricks.com/aws/en/business-semantics/metric-views/joins">metric view joins page</a> says joins default to many-to-one, that a one-to-many join needs YAML specification 1.1 and Databricks Runtime 18.1 or above, and that a plain count over a nested one-to-many join counts a row once per match. It also says the at_most_one_match assertion is not validated at runtime. The <a href="https://docs.databricks.com/aws/en/metric-views/yaml-ref">YAML reference</a> adds that a false assertion makes measures such as SUM and COUNT return incorrect results. A metric view encodes join semantics once, but the encoding can itself be wrong.</li><li><strong>Benchmarks.</strong> The <a href="https://docs.databricks.com/aws/en/genie/benchmarks">benchmarks page</a> describes up to 500 questions per agent, run as new conversations. In Chat mode, results are compared with a provided SQL answer. A response is graded Good if the result matches, including when numeric values round to the same four significant digits. Detail for a run is visible for one week. The page does not mention a benchmark API.</li><li><strong>Monitoring.</strong> The <a href="https://docs.databricks.com/aws/en/genie-agents/monitor">monitoring page</a> describes viewing generated SQL with Show code, a Monitor tab with filters, and feedback options of Yes, Fix it and Request review. It states that feedback alone does not change the agent’s behavior.</li></ul><h3>What a benchmark can and cannot tell you</h3><p>A benchmark that passes shows that, for that question, in that run, the generated result matched the reference under the grading rules. The four-significant-digit tolerance is also worth knowing. On a total in the hundreds of millions, a small omission such as a recovery could fall inside that tolerance. I derive that from the grading rule and have not tested it. Benchmarks are evidence for the questions you tested, not a proof for questions you did not.</p><h3>How I would test it in a real agent</h3><p>Attach Unity Catalog versions of the three tables to a Genie Agent. Ask the question in several phrasings, with and without the words “transaction” and “financial year”. Record the question, the generated SQL from Show code, the result and the number of runs, and compare each with the ledger baseline. Report what happens, including runs where Genie gets it right. That would turn the inference above into an observation.</p><h3>A production-readiness checklist</h3><p>Three kinds of control do different jobs, and they should not be confused. Data-model controls remove the opportunity for the error, so they sit upstream of any query. Deterministic data-quality tests run in SQL, know nothing about Genie, and tell you whether the data and the reference queries are right. Genie-specific evaluation tells you whether the agent produces acceptable answers for the questions you chose to test. Only the first prevents the failure. The second detects it in data and reference logic. The third detects regressions in agent behavior for known questions.</p><p>The items below are engineering practice. Where a Databricks feature is involved, the previous section says what is documented.</p><h3>Prevent</h3><ul><li>Write down the grain of every table exposed for analytics, and the keys that define it.</li><li>Do not expose a cumulative claim snapshot next to its ledger without saying which one is the measure source.</li><li>Provide a curated view or a governed metric definition at the grain of the intended measure, and consider hiding the ambiguous column.</li><li>State each join’s cardinality, including effective-dated dimensions, and join on the full business key plus the date condition.</li><li>Write the metric definition down: basis, valuation date, recoveries, exclusions, financial-year convention.</li><li>Do not treat a declared join relationship, or a metric view, as proof of correct aggregation.</li></ul><h3>Detect</h3><ul><li>Read the generated SQL for any answer that matters, where the product shows it.</li><li>Compare rows after a join with distinct entities on the preserved side.</li><li>Reconcile the result against a baseline query that does not share the suspect logic.</li><li>Reconcile snapshots against ledger totals with an agreed tolerance.</li><li>Check uniqueness and event duplication using the source’s own identifiers or documented business keys.</li><li>Assert one match per claim for every effective-dated dimension.</li></ul><h3>Maintain</h3><ul><li>Keep the deterministic SQL tests in a scheduled job, and make each one prove it can fail with an injected defect.</li><li>Add representative questions to a benchmark suite when an agent is available, with several phrasings of each.</li><li>Read benchmark results as evidence for tested questions, not as a guarantee.</li><li>Review real usage and feedback for suspicious results, and turn each confirmed error into a test.</li></ul><h3>What the lab does and does not show</h3><p>It shows that, on this synthetic schema, summing a claim-level snapshot after joining to ledger rows inflates the total from 40,500 to 103,500, that aggregating the ledger to claim grain first fixes it, and that SUM(DISTINCT) and an id-only join to a term-grained dimension do not. It shows that three detectors catch three injected defects.</p><p>It does not show that Genie generates the bad query, that any Genie response is wrong, or that the corrected query suits a real insurance accounting model. The data is synthetic, the metric definition is simplified, and the snapshot reconciles with the ledger by construction. The SQL was executed in DuckDB and not in Databricks. The product statements come from the documentation pages linked in this article and from no testing of the product.</p><h3>Conclusion</h3><p>A query that runs is not evidence that the number means what the reader thinks it means. Here the SQL was valid, the joins were on the right keys, and one of three rows was correct. The error sat in the combination of a claim-level measure and a ledger-level join, and in a metric definition nobody had written down.</p><p>Correctness comes from three places: a metric definition that says what is being counted, a data model whose grain is explicit and whose joins have stated cardinality, and validation that can fail. Natural-language interfaces make the first two more important, because the person asking never sees the SQL. They do not replace any of the three.</p><h3>Sources</h3><p>Databricks documentation pages used for product statements, as read on 26 October 2026:</p><ul><li><a href="https://docs.databricks.com/aws/en/genie/knowledge-store">Genie knowledge store (join relationships, example SQL, SQL expressions)</a></li><li><a href="https://docs.databricks.com/aws/en/genie/troubleshooting">Troubleshoot Genie answers</a></li><li><a href="https://docs.databricks.com/aws/en/genie/best-practices">Genie best practices</a></li><li><a href="https://docs.databricks.com/aws/en/genie/benchmarks">Genie benchmarks</a></li><li><a href="https://docs.databricks.com/aws/en/genie-agents/monitor">Test and monitor a Genie Agent</a></li><li><a href="https://docs.databricks.com/aws/en/business-semantics/metric-views/joins">Joins in metric views</a></li><li><a href="https://docs.databricks.com/aws/en/metric-views/yaml-ref">Metric view YAML reference</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=087473f69f3d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why a Databricks Job Suddenly Started Scanning 1,100 Partitions Instead of 30]]></title>
            <link>https://medium.com/@mridusingh1991/why-a-databricks-job-suddenly-started-scanning-1-100-partitions-instead-of-30-ee08a9d6659c?source=rss-0d9ade9052ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee08a9d6659c</guid>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Mridusingh]]></dc:creator>
            <pubDate>Fri, 14 Aug 2026 09:24:27 GMT</pubDate>
            <atom:updated>2026-08-14T09:24:27.349Z</atom:updated>
            <content:encoded><![CDATA[<h3>The 500 GB Shuffle Nobody Expected</h3><p><em>Note: This article is based on a representative production-style scenario that combines patterns commonly encountered while working with Apache Spark and Databricks. Implementation details, timelines, and metrics have been generalized for educational purposes.</em></p><h3>1. Background</h3><p>The pipeline in question was boring, and boring was the point.</p><p>A daily batch job on Databricks. Four Delta tables joined together — one large transactional fact table partitioned by event date, two reference dimensions, and one small control table that carried the set of dates eligible for processing on any given run. Output written back to Delta, partitioned by the same date column, consumed downstream by a semantic layer and a handful of scheduled extracts.</p><p>It had run every morning for roughly fourteen months. Typical wall-clock runtime was around 22 minutes on a fixed cluster, with the heaviest stage accounting for roughly 12 of those minutes. The SLA was 45 minutes, which gave the job enough headroom that nobody looked at it. There were no alerts on runtime, only on failure, and it did not fail.</p><p>Then, over roughly eight weeks, it stopped being boring.</p><p>The runtime crept up. Not in a single jump — that would have made the investigation trivial, because you could correlate it with a deployment or a config change. It moved in the way that hides from humans: 26 minutes, then 31, then 38, then 44. By the time somebody raised a ticket, the job was landing at about 55 minutes and breaching the SLA on most weekdays. Downstream extracts were arriving after the business had started asking for them.</p><p>The code had not been touched in five months. The cluster configuration had not been touched at all.</p><p>That combination — no code change, no config change, steadily worsening performance — is the shape of the problem this article is about. It almost always means something <em>outside</em> the code changed the <em>plan</em> the code produces.</p><h3>2. Initial assumptions</h3><p>Every performance investigation starts with a folk theory, and the folk theory here was the usual one: the cluster is too small.</p><p>It is worth being honest about why that theory is so popular. It is cheap to test, it requires no understanding of the workload, and often enough it produces a small improvement, which then gets mistaken for confirmation. It also happens to be the only lever most people have permission to pull without a code review.</p><p>Four hypotheses went on the whiteboard.</p><p><strong>Hypothesis 1: the cluster is underpowered.</strong></p><p>Tested first, because it was easiest. Worker count was doubled. Across three runs, wall-clock time moved by less than a minute — inside normal run-to-run variance.</p><p>That hypothesis didn’t survive the data. But the interesting part was not that scaling failed; it was the specific way in which it failed. The cluster had already been provisioned with more than 200 concurrent task slots. The dominant stage ran exactly 200 tasks before the change, and it ran exactly 200 tasks after it. Doubling the workers doubled the number of slots available and left the number of tasks untouched, so half the cluster had nothing to do.</p><p>That is not a symptom of an undersized cluster. That is a symptom of parallelism being capped by something other than the cluster — and at this point nobody yet knew what.</p><p>The cluster was scaled back down. It stayed down for the rest of the investigation, deliberately — throwing hardware at an unexplained regression destroys your ability to measure anything.</p><p><strong>Hypothesis 2: cloud object storage got slower.</strong></p><p>Plausible, because object storage throughput is genuinely variable and prefix-level throttling is a real phenomenon that produces exactly this kind of gradual degradation as key distribution changes.</p><p>Checked the read side: bytes read per task, task deserialization time, and the scan node’s own duration metrics in the SQL tab. Per-task read throughput was consistent with historical runs. There were no retry storms in the driver logs, no 503-class errors, and the scan stages themselves were not the slow ones.</p><p>Storage was reading fine. It was just being asked to open considerably more files than it used to — which was a clue, but not one that was recognised yet.</p><p><strong>Hypothesis 3: source data volume grew.</strong></p><p>The obvious explanation for “reads more, takes longer.” It was checked properly rather than assumed: row counts and file counts for the fact table across the eight-week window.</p><p>The fact table had grown about 6%. Daily incremental volume was flat. Nothing in the source system had changed shape.</p><p>A 6% growth in the underlying table does not produce a 140% runtime increase. Something was amplifying it.</p><p><strong>Hypothesis 4: network latency between compute and storage.</strong></p><p>Worth eliminating because a degraded network path produces slow shuffle reads, and slow shuffle reads look like everything else being slow. Shuffle read blocked time was pulled from the stage metrics and compared against total task time. It was a low single-digit percentage — the tasks were not sitting around waiting for bytes to arrive. They were busy.</p><p>Four hypotheses, four eliminations. All four shared the same flaw: they were hypotheses about the <em>environment</em>. Nothing in the environment had changed.</p><h3>3. Investigation</h3><h3>3.1 The Jobs tab: find the stage that owns the clock</h3><p>The first useful move in any Databricks performance investigation is not to open the code. It is to open the Spark UI and answer one question: <em>which stage is spending the time?</em></p><p>The Jobs tab for the degraded run showed the expected structure — a handful of jobs corresponding to the write actions and a couple of collects — but the distribution of time was lopsided. One stage accounted for roughly 35 minutes of the ~55 minute run. Everything else was noise around it.</p><p>That is a useful shape. It means the problem is localized. You are not looking for a systemic slowdown; you are looking for one specific piece of work that got expensive.</p><p>Drilling into that stage, the summary metrics were:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*55L7WohskwtoAO7tzSHrFw.png" /></figure><p>The task distribution was <em>even</em>. Median 9.5 minutes, max 11 minutes. That immediately rules out the most commonly assumed cause of a slow Spark stage — skew. When one key dominates, you see 199 tasks finishing in a minute and one task running for forty. That is not what this was. Every task was doing a lot of work, and they were all doing roughly the same amount of it.</p><p>This matters because skew and volume have completely different fixes, and reaching for salting or spark.sql.adaptive.skewJoin on a non-skewed stage is how people waste a week.</p><p>But the row that should have stopped the room was the first one. Two hundred tasks in the baseline. Two hundred tasks in the degraded run. Two hundred tasks after the cluster was doubled. A number that refuses to move across fourteen months, a 140% runtime regression, and a hardware change is not a coincidence. It is a constant somebody typed.</p><p>That was noted and set aside. The investigation went looking for what the tasks were actually <em>doing</em> first.</p><h3>3.2 The scan node: expected 30, observed 1,100</h3><p>The Delta scan nodes in the SQL / DataFrame tab expose two numbers that almost nobody reads: the number of files read, and the partition filters actually applied at the scan.</p><p>This pipeline processes a rolling window. It should be touching somewhere around <strong>30 date partitions</strong>.</p><p>The degraded run’s fact scan reported reading files from roughly <strong>1,100 date partitions</strong>.</p><p>This was the first clue, and it was a big one. It is not a subtle ratio, it is not a derived metric, and it does not depend on interpreting anything. The job was opening the entire history of the fact table, every morning, to produce thirty days of output.</p><p>It also explained hypothesis 2. Storage was not slow. Storage was being asked to list and open roughly thirty-five times more files than the workload required, and it was doing that competently.</p><p>And it explained the shape of the curve. If the job scans the whole table rather than a window, then every day of accumulated history makes tomorrow’s run marginally slower. Fourteen months of accumulation, read in full, every day. The 6% table growth measured in hypothesis 3 was real; it was just being applied to a scan that had stopped being bounded.</p><p>The obvious question: the code contains a date restriction. Why was it not being applied at the scan?</p><h3>3.3 The task count that would not move</h3><p>Before answering that, the number from §3.1 came back.</p><p>Two hundred tasks. Exactly. In every run, at every cluster size, across the whole regression.</p><p>spark.sql.shuffle.partitions was at its default of 200, which made the number look innocent — it is the value everybody expects to see, so it reads as background. But the stage in question sat downstream of a join, and under Adaptive Query Execution a post-shuffle stage should not present a fixed task count at all. AQE coalesces shuffle partitions based on the actual size of the shuffle output, so the task count is expected to <em>vary</em> between runs as data volume varies.</p><p>This one did not vary. Not by one task, not in either direction, not when the data being processed grew by an order of magnitude.</p><p>A constant task count is a strong signal that shuffle partitioning is being constrained explicitly rather than being coalesced adaptively — and AQE declines to coalesce exactly one category of shuffle: the ones the user asked for explicitly. A signal, though, is not a finding. The plan would have to confirm it.</p><p>Clue one said the job was reading far too much. Clue two said the job was pinned to a fixed width regardless of how much it read. Clue three — from the very first hypothesis — said adding hardware could not help, because the width was not the cluster’s to set.</p><p>Three clues, one shape. Something in the code was fixing the parallelism.</p><h3>3.4 The SQL tab: counting Exchanges, and finding the constant</h3><p>The Spark UI told a very different story from the cluster metrics dashboard.</p><p>The SQL / DataFrame tab in Databricks gives you the full physical plan for a query as a DAG, annotated with per-node metrics. This is the single most under-used diagnostic surface in Spark, and it is where this investigation actually got solved.</p><p>Counting Exchange nodes in the DAG for the main query, excluding the write: <strong>seven</strong>.</p><p>The per-node labels narrowed it immediately. Six of them were hashpartitioning on the various join keys — expected, since each join in the chain used a different key, so each required its own redistribution. The seventh was labelled:</p><pre>Exchange RoundRobinPartitioning(200), REPARTITION_BY_NUM</pre><p>That is not a shuffle Spark inserts on its own initiative. HashPartitioning is what a join requires. RangePartitioning is what a sort requires. RoundRobinPartitioning with a REPARTITION_BY_NUM tag comes from exactly one place: a user calling repartition(n) with a number and no columns.</p><p>There was the constant. There was the reason 200 tasks never moved — that tag is precisely what tells AQE to leave the partition count alone. And there was the reason doubling the cluster achieved nothing.</p><p>The code had not changed in five months, so this line had been sitting there the entire time, in every one of the fourteen months of healthy runs. Which meant it was not sufficient on its own to explain the regression — it was the thing the regression <em>landed on</em>.</p><h3>3.5 EXPLAIN FORMATTED: the pruning that was not there</h3><p>EXPLAIN FORMATTED is where you stop guessing about the scan. Unlike the default EXPLAIN, it prints a compact numbered plan tree first and then a detail block per operator, which makes it readable for plans with dozens of nodes.</p><p>Here is the relevant fragment of the fact-table scan on the degraded plan, generalized:</p><pre>(1) Scan parquet <br>Output [6]: [event_date#31, entity_key#32, attr_key#33, status_code#34, ...]<br>Batched: true<br>Location: PreparedDeltaFileIndex [&lt;path&gt;/event_date=2023-..-.., ... 1,1xx entries]<br>PartitionFilters: [isnotnull(event_date#31)]<br>PushedFilters: [IsNotNull(status_code), In(status_code, [...])]<br>ReadSchema: struct&lt;entity_key:bigint,attr_key:bigint,status_code:string,...&gt;</pre><p>PartitionFilters contains an isnotnull check and nothing else. The Location line enumerates the full partition inventory. There is no date restriction at the scan, which is exactly consistent with the 1,100 partitions from §3.2 — the two pieces of evidence corroborate each other, one from the UI and one from the plan.</p><p>Note what <em>did</em> work: the status_code predicate reached PushedFilters and made it to the Parquet reader. Predicate pushdown was functioning normally. This is a useful discrimination — the problem was specific to the partition column, not to pushdown in general.</p><p>The date restriction in this pipeline was never a literal. It came from joining the fact table against the small control table that held the eligible dates. That pattern only prunes efficiently if the engine can derive the date values at runtime and push them into the scan — the family of optimizations that includes Dynamic Partition Pruning in open-source Spark and Dynamic File Pruning on Databricks Runtime.</p><p><strong>One plausible explanation was that the pipeline had been depending on runtime pruning, and had stopped qualifying for it.</strong></p><p>Configuration review pointed toward the join strategy as the deciding factor. In Spark 3.x, spark.sql.optimizer.dynamicPartitionPruning.reuseBroadcastOnly defaults to true, which means the pruning subquery is planted by reusing an existing broadcast exchange rather than computing the values twice — so in practice the filtering side generally needs to be broadcast. Databricks&#39; Dynamic File Pruning was documented at introduction with a comparable requirement: the probe side in Delta format, an INNER or LEFT-SEMI join, a <strong>broadcast hash join</strong> strategy, and a file count above spark.databricks.optimizer.deltaTableFilesThreshold. Both families of runtime pruning, on this reading, lean on the same precondition.</p><p>The control table had been accumulating rows since the pipeline went live — a few hundred rows a day of retained history that nobody had ever pruned, because it was, in everyone’s mental model, “the small table.” The execution plan suggested it had stopped being treated as one: that join was now a SortMergeJoin, where the archived healthy plan had shown a BroadcastHashJoin.</p><p>A candidate chain, then: the control table crossed spark.sql.autoBroadcastJoinThreshold, the planner switched the join to sort-merge, and the runtime pruning that the date restriction depended on stopped being applicable. No error, no warning, no log line — identical results, produced by reading 1,100 partitions instead of 30.</p><p>Two honest caveats on this section, because they matter more than the tidiness of the story.</p><p>First, this is a <strong>hypothesis that the evidence is consistent with, not a directly observed causal event.</strong> What was observed is unambiguous: the partition count, the absent partition filter, and the join strategy change between the archived and current plans. The inference from “join strategy changed” to “therefore pruning was lost” is supported by configuration semantics and documentation, not by a captured before-and-after of the pruning expression itself. When this pattern was reconstructed in a controlled environment, the expected dynamicpruningexpression did not consistently appear in the plan even under conditions that appeared to satisfy the preconditions — runtime pruning is gated by internal cost heuristics as well as by join strategy, and those heuristics are not something you can reason about from the outside.</p><p>Second, Dynamic File Pruning specifically is a weaker candidate here than it might first appear, and it is worth saying so before a reader says it for you. DFP prunes at <em>file</em> granularity and is documented as being especially efficient for non-partitioned tables, or for joins on non-partitioned columns. This fact table is partitioned by the join column, which is DPP’s territory rather than DFP’s. Databricks’ current documentation has also softened the criteria considerably from the original list, noting that for SELECT statements Photon provides broader and more reliable dynamic file pruning, and that without Photon, DFP may still apply depending on query shape and execution plan. &quot;Depending on query shape and execution plan&quot; is not a contract you should build a daily SLA on.</p><p>Which is, in the end, the actionable conclusion regardless of which mechanism was operating: the pipeline’s correctness of <em>runtime</em> was resting on a planner inference nobody had written down.</p><h3>3.6 The code</h3><p>With the plan understood, the code finally became readable in the right way.</p><pre># BEFORE</pre><pre>fact_df  = spark.read.format(&quot;delta&quot;).load(FACT_PATH)<br>ctrl_df  = spark.read.format(&quot;delta&quot;).load(CTRL_PATH)<br>dim_a_df = spark.read.format(&quot;delta&quot;).load(DIM_A_PATH)<br>dim_b_df = spark.read.format(&quot;delta&quot;).load(DIM_B_PATH)</pre><pre>result = (<br>    fact_df<br>        .join(ctrl_df,  &quot;event_date&quot;)<br>        .repartition(200)<br>        .join(dim_a_df, &quot;entity_key&quot;)<br>        .join(dim_b_df, &quot;attr_key&quot;)<br>        .filter(F.col(&quot;status_code&quot;).isin(ACTIVE_STATUSES))<br>        .select(*OUTPUT_COLS)<br>)</pre><pre>(result.write<br>       .format(&quot;delta&quot;)<br>       .mode(&quot;overwrite&quot;)<br>       .partitionBy(&quot;event_date&quot;)<br>       .save(TARGET_PATH))</pre><p>The repartition(200) had been in the code since the first release. Its origin was archaeology: at some point the job had produced too many small output files, someone added a repartition, the file count improved, and it was never revisited. It sat in the middle of the join chain rather than immediately before the write, which is the position where it would have actually addressed the problem it was added for.</p><p>For a year it cost something, but not enough to notice. Then the scan stopped being bounded, the row count flowing through that fixed-width shuffle went up by roughly an order of magnitude, and the same line of code became a 500 GB shuffle executed 200 tasks at a time.</p><h3>4. Root cause</h3><p>Three contributing factors, one of which is a hypothesis rather than a measurement. None of them alone would have breached the SLA. The interaction between them is the story.</p><h3>4.1 Fixed parallelism: the villain hiding in plain sight</h3><p>repartition(n) without column arguments produces RoundRobinPartitioning. It performs a full shuffle and distributes rows round-robin across n partitions, deliberately ignoring any key structure in the data. In the physical plan it carries a REPARTITION_BY_NUM tag, and that tag is the important part.</p><p>Three consequences here, in increasing order of damage:</p><p><strong>It cost a full shuffle of the intermediate result.</strong> One extra Exchange. Worth noting that this is <em>one</em>, not several — the downstream joins in this pipeline used different keys (event_date, then entity_key, then attr_key), so each of them required its own hash exchange whether or not the repartition was present. It is tempting to blame a mid-chain repartition for every shuffle beneath it; in a chain of joins on <em>different</em> keys, that blame is misplaced. Where it does compound is a chain of joins on the <em>same</em> key, where a well-placed hash partitioning can be reused and a round-robin destroys the chance.</p><p><strong>It pinned the stage at 200 tasks, permanently.</strong> This is the one that mattered. AQE’s shuffle partition coalescing operates on shuffles the planner introduced; a user-specified repartition(n) is an explicit instruction, tagged as such in the plan, and Spark honours it rather than coalescing it away. Whatever volume flowed through that point in the pipeline — three gigabytes or three hundred — it flowed through exactly 200 tasks. The pipeline had a hardcoded ceiling on its own parallelism, and that ceiling was invisible in every dashboard anybody was looking at.</p><p>This is why the cluster hypothesis failed. It was not that the cluster was adequately sized; it was that cluster size had been made irrelevant. Nothing purchasable would have fixed this job.</p><p><strong>It acted as a barrier to join reordering.</strong> Catalyst’s join reordering operates on contiguous trees of inner joins. A Repartition node in the middle of the chain splits that tree into two, and no join can move across the boundary.</p><p>This one is easy to state and easy to overstate, so here it is as a plan diff rather than an assertion. Same four tables, same statistics, CBO and join reordering both enabled, autoBroadcastJoinThreshold set to -1 to force sort-merge joins and expose the structure. The only difference between the two runs is a single line of code. Reading the optimized logical plan top-down, the <em>last</em> join listed is the one that executes first:</p><pre>PLAN A — no repartition              PLAN B — repartition(200) mid-chain<br>-------------------------------      ------------------------------------<br>Join Inner (entity_key)              Join Inner (attr_key)<br>Join Inner (attr_key)                Join Inner (event_date)<br>Join Inner (event_date)   &lt;-- runs   Repartition 200, true<br>                              first  Join Inner (entity_key)  &lt;-- runs first</pre><p>In Plan A the optimizer pulled the selective control-table join to the bottom of the tree, so it executes first and everything above it processes fewer rows. In Plan B it could not: the dimension join is trapped below the Repartition node and executes first regardless, and the selective join cannot be moved down past the fence.</p><p>The precise claim, which is narrower than the folklore version: reordering still happens freely <em>within</em> each sub-tree. What it cannot do is cross the boundary. repartition() is not just a shuffle. It is an optimization fence, and the plan will show you exactly where the fence is.</p><h3>4.2 Seven Exchange operators</h3><p>Accounting for the seven, excluding the write:</p><ol><li>RoundRobinPartitioning(200) — the explicit repartition. 2-3. HashPartitioning(event_date) on both sides of the fact-to-control sort-merge join, which the archived plan showed as a broadcast join. 4-5. HashPartitioning(entity_key) on both sides of the dim_a join. 6-7. HashPartitioning(attr_key) on both sides of the dim_b join.</li></ol><p>Not all seven moved the same volume — the dimension sides were small. The fact-side exchanges are where the cost lived, and each of them was moving an intermediate result inflated by the scan behaviour, through a fixed 200-way width.</p><p>The count itself is a supporting metric rather than the diagnosis. A four-table sort-merge join chain on three different keys is <em>expected</em> to produce six exchanges. The seventh is the one that was chosen by a human, and it is the only one worth an argument.</p><h3>4.3 Scan behaviour and join ordering</h3><p>Covered in §3.2 and §3.5. The scan reading ~1,100 partitions instead of ~30 is the observed fact; the loss of runtime pruning following a join strategy change is the leading hypothesis for why.</p><p>Compounding it, the join order in the code was, in effect, the order somebody typed it in: largest table first, then progressively join smaller things onto it. The most selective operation in the entire query was the status_code filter, and it was written after all three joins.</p><p>Catalyst’s PushDownPredicate rule did push that filter down to the fact-side scan, and the plan confirms it in PushedFilters. But the filter is on a non-partition column with no relevant file-level statistics clustering, so pushing it down bought a row-level filter, not a file-level skip. The rows still had to be read — and the ordering of the <em>joins themselves</em> could not be improved, because of the fence described above.</p><h3>4.4 How they interacted</h3><p>The honest summary:</p><ul><li>The unbounded scan increased the rows entering the join chain by roughly 25–30x.</li><li>The fixed 200-way parallelism guaranteed that increase would be absorbed by making each task longer rather than by making more tasks.</li><li>The reorder fence guaranteed the selective work could not be moved earlier.</li><li>Additional hardware could not touch any of the three.</li></ul><p>For fourteen months the repartition was present and the job ran in 22 minutes, because the scan was still bounded and 200 tasks was a perfectly reasonable width for the volume. Remove the scan bound and the pre-existing constraint stopped being a rounding error and became a ceiling.</p><p>This is worth internalizing as a general pattern: most production Spark regressions are not caused by the thing that changed. They are caused by pre-existing constraints that the change stopped hiding.</p><p>One more note on AQE, because it comes up immediately. Adaptive Query Execution was enabled throughout. It did not save this job, for two reasons worth knowing:</p><ul><li>AQE can convert a sort-merge join to a broadcast hash join at runtime, but only <em>after</em> the relevant shuffle stage has materialized. The shuffle write cost is already paid by the time AQE makes that decision.</li><li>AQE’s shuffle partition coalescing applies to shuffles the planner introduced. The REPARTITION_BY_NUM tag on an explicit repartition(200) marks it as a user instruction, and it is honoured rather than coalesced.</li></ul><p>AQE is a safety net for plans that are mostly correct. It is not a substitute for a plan that isn’t.</p><h3>5. Solution</h3><p>Four changes, in order of impact.</p><h3>5.1 Bound the scan deterministically</h3><p>The tempting fix is to raise spark.sql.autoBroadcastJoinThreshold so the control table becomes broadcastable again and runtime pruning becomes applicable. That may work, it is a one-line change, and it is fragile — you have re-armed the same trap at a higher threshold, and you are still depending on a planner inference and its internal cost heuristics.</p><p>The durable fix is to stop depending on inference for something the pipeline knows explicitly. The eligible date window is small and cheap to compute, so compute it and inject it as a literal predicate:</p><pre># AFTER — pruning as an explicit contract, not an inference</pre><pre>window_dates = [<br>    r.event_date<br>    for r in (spark.read.format(&quot;delta&quot;).load(CTRL_PATH)<br>                   .select(&quot;event_date&quot;)<br>                   .distinct()<br>                   .collect())<br>]</pre><pre>fact_df = (spark.read.format(&quot;delta&quot;).load(FACT_PATH)<br>                .filter(F.col(&quot;event_date&quot;).isin(window_dates)))</pre><p>The control table is small enough that the collect() is trivial. The literal IN list lands directly in PartitionFilters at the scan, which means pruning happens at file-listing time and does not depend on join strategy, table sizes, cost heuristics, or config defaults.</p><p>The trade-off is honest: you have added a driver-side action and a second pass over the control table, and you have coupled the fact read to a Python variable. In exchange, the pruning behaviour is now visible in EXPLAIN and cannot silently disappear.</p><p>If you prefer to keep it declarative, the SQL equivalent with an explicit broadcast hint is:</p><pre>SELECT /*+ BROADCAST(c) */<br>       f.entity_key,<br>       f.attr_key,<br>       f.event_date,<br>       a.attr_1,<br>       b.attr_2<br>FROM   fact f<br>JOIN   ctrl c  ON f.event_date = c.event_date<br>JOIN   dim_a a ON f.entity_key = a.entity_key<br>JOIN   dim_b b ON f.attr_key   = b.attr_key<br>WHERE  f.status_code IN (...)</pre><p>The hint forces the broadcast, restoring the precondition that runtime pruning depends on. It is more idiomatic, but it still leaves the actual pruning decision to the optimizer, and it depends on the control table staying small enough to broadcast without destabilising the driver.</p><h3>5.2 Delete the mid-chain repartition</h3><p>Removing it does three things at once: eliminates one full shuffle, returns partition-count control to AQE, and removes the barrier to join reordering.</p><p>The original small-file problem it was written to solve is real, and it is solved at the write, not in the middle of the join:</p><pre>(result<br>    .repartition(&quot;event_date&quot;)      # align shuffle partitioning with the write key<br>    .write<br>    .format(&quot;delta&quot;)<br>    .mode(&quot;overwrite&quot;)<br>    .partitionBy(&quot;event_date&quot;)<br>    .save(TARGET_PATH))</pre><p>On Databricks, optimizeWrite on the target table handles this at the engine level and is generally the better answer, since it adapts bin-packing to actual data size rather than a hardcoded number.</p><p>Note the distinction: repartitioning by event_date aligns the shuffle partitioning with the write key instead of imposing an arbitrary round-robin partition count, and it is placed where it does its job. repartition(200) is a round-robin over a constant, sitting in the middle of the computation. They are not the same operation despite the shared method name. Note also what the column form does <em>not</em> guarantee — hash partitioning distributes by hash across the configured partition count, so keys can share a partition and a directory can still receive more than one file. It aligns the layout; it does not promise a one-to-one mapping.</p><h3>5.3 Reorder the joins and broadcast what is small</h3><pre># AFTER — full version</pre><pre>window_dates = [...]  # as above</pre><pre>fact_df = (spark.read.format(&quot;delta&quot;).load(FACT_PATH)<br>                .filter(F.col(&quot;event_date&quot;).isin(window_dates))<br>                .filter(F.col(&quot;status_code&quot;).isin(ACTIVE_STATUSES)))</pre><pre>dim_a_df = spark.read.format(&quot;delta&quot;).load(DIM_A_PATH)<br>dim_b_df = spark.read.format(&quot;delta&quot;).load(DIM_B_PATH)</pre><pre>result = (<br>    fact_df<br>        .join(F.broadcast(dim_b_df), &quot;attr_key&quot;)     # smallest dim, no shuffle<br>        .join(dim_a_df,              &quot;entity_key&quot;)   # the only shuffle join<br>        .select(*OUTPUT_COLS)<br>)</pre><p>Three deliberate choices:</p><ul><li>The status_code filter now runs at the scan, before any join, and with no fence to prevent the optimizer from keeping it there.</li><li>dim_b_df is explicitly broadcast. It is comfortably under the threshold, but &quot;comfortably under the threshold&quot; is precisely the assumption that broke this pipeline, so the hint makes it explicit and turns a future size regression into a loud failure rather than a quiet slowdown.</li><li>dim_a_df remains a sort-merge join. It genuinely is large. One shuffle join in a four-table query is a reasonable outcome, not a failure.</li></ul><h3>5.4 Verify against the plan, not the stopwatch</h3><p>The last step is the one that gets skipped. Before running the optimized version at scale, EXPLAIN FORMATTED on the new query and check four things:</p><ul><li>PartitionFilters on the fact scan contains the date restriction as a literal.</li><li>The Location line lists the expected number of partition entries, not the full inventory.</li><li>The Exchange count matches expectation, and no REPARTITION_BY_NUM node remains.</li><li>The join strategies are what you intended (BroadcastHashJoin where you asked for it, SortMergeJoin where you accepted it).</li></ul><p>The optimized plan’s scan node:</p><pre>(1) Scan parquet <br>Output [5]: [event_date#31, entity_key#32, attr_key#33, status_code#34, ...]<br>Batched: true<br>Location: PreparedDeltaFileIndex [&lt;path&gt;/event_date=2024-..-.., ... 30 entries]<br>PartitionFilters: [isnotnull(event_date#31), event_date#31 IN (2024-..-.., ...)]<br>PushedFilters: [IsNotNull(status_code), In(status_code, [...])]<br>ReadSchema: struct&lt;entity_key:bigint,attr_key:bigint,status_code:string,...&gt;</pre><p>Both the partition filter and the pushed data filter are present, and the partition inventory is bounded. That is the confirmation — not the runtime.</p><h3>6. Results</h3><p>Measured over five consecutive production runs, on the <strong>original</strong> cluster configuration (the extra nodes added during the initial hypothesis were removed before any of these measurements).</p><p>Metric Baseline Degraded Fixed Wall-clock runtime ~22 min ~55 min ~11 min Longest stage duration ~12 min ~35 min ~6 min Shuffle write (job total) — ~500 GB ~120 GB Exchange operators (excl. write) 7 7 3 Date partitions scanned ~30 ~1,100 ~30 Tasks in dominant stage 200 (fixed) 200 (fixed) AQE-coalesced</p><p>The historical healthy baseline was ~22 minutes. The optimized pipeline is roughly twice as fast as the job had <em>ever</em> been, because the fix addressed a constraint that had been present since the first release, not just the regression that exposed it.</p><p>Two secondary outcomes worth recording:</p><ul><li>The cluster was left at its original size, so the compute cost per run dropped in proportion to the runtime.</li><li>A plan-level assertion was added as a pre-flight check: the job now fails fast if EXPLAIN FORMATTED on the main query does not contain a literal partition filter on event_date, or if a REPARTITION_BY_NUM node reappears in the join chain. This is the actual regression protection. Runtime alerting would have caught this eight weeks late; a plan assertion catches it on the first run.</li></ul><h3>7. Key takeaways</h3><p><strong>1. More compute does not solve a parallelism ceiling.</strong></p><p>Doubling the cluster changed nothing because the dominant stage ran 200 tasks before and 200 tasks after. The width of that stage was set by a constant in the source code, not by the hardware. Before you size a cluster, check whether the job is capable of using it: if the task count in your dominant stage is a suspiciously round number that never varies with data volume, no amount of hardware is going to help you.</p><p><strong>2. Read the scan node before you read anything else.</strong></p><p>The single most decisive number in this investigation was the count of partitions listed on the fact scan: ~1,100 observed against ~30 expected. It required no interpretation, no derived ratio, and no comparison between incompatible units. Make “how much is this job actually opening, versus how much does it need?” the first question you ask, and check it in both the SQL tab and PartitionFilters — the two should agree, and when they do, you have a fact rather than an inference.</p><p><strong>3. Never let pruning be an inference.</strong></p><p>Runtime pruning — Dynamic Partition Pruning in open-source Spark, Dynamic File Pruning on Databricks — is a genuine and substantial optimization, and it is also conditional on join strategy, table sizes, engine version, and internal cost heuristics that are not visible from your code. A pipeline whose SLA depends on it therefore has an implicit dependency on optimizer decisions and runtime heuristics. Where the values are knowable in advance, push them in as literals and assert on the plan.</p><p><strong>A fourth, which is really the whole story:</strong> the code that broke this pipeline had not changed in five months. Plans are a function of code <em>and</em> data statistics <em>and</em> configuration defaults. Two of those three move on their own. Treat a stable codebase as no guarantee whatsoever of a stable execution plan, and archive the plans of your critical pipelines — a plan diff between a healthy run and a degraded run is the fastest root-cause tool Spark gives you, and it costs nothing to capture.</p><h3>8. Interview corner</h3><p>Senior-level questions on this material, with the answers an interviewer is actually listening for.</p><p><strong>1. What is an Exchange operator, and what determines when Spark inserts one?</strong></p><p>Exchange is the physical operator representing a shuffle — a redistribution of data across partitions. Insertion is handled by the EnsureRequirements rule during physical planning: each operator declares a requiredChildDistribution, and each reports its outputPartitioning. If a child&#39;s output partitioning does not satisfy the parent&#39;s required distribution, an Exchange is inserted. A SortMergeJoin requires ClusteredDistribution on the join keys, so if the child is not already hash-partitioned on those keys, you get a shuffle. This is also why two consecutive joins on the <em>same</em> key need only one shuffle per side — the first join&#39;s output partitioning already satisfies the second&#39;s requirement. Joins on <em>different</em> keys get their own exchange regardless.</p><p><strong>2. </strong><strong>repartition() vs </strong><strong>coalesce() — beyond &quot;one shuffles and one doesn&#39;t.&quot;</strong></p><p>repartition(n) triggers a full shuffle with round-robin distribution; repartition(cols) triggers a full shuffle with hash partitioning on those columns. It can increase or decrease partition count and produces even distribution. coalesce(n) merges existing partitions using a narrow dependency — no shuffle, no network cost — but can only reduce partition count, may produce uneven partitions, and critically it propagates its parallelism limit <em>upstream</em>. coalesce(1) before a write does not just make one output file; it can force the entire preceding computation to run on one task. When you need to reduce output files without collapsing upstream parallelism, repartition is often correct despite the shuffle, or use the engine&#39;s optimized-write capability.</p><p><strong>3. A stage runs exactly 200 tasks in every run, at every cluster size, regardless of data volume. What does that tell you, and where do you confirm it?</strong></p><p>A constant task count is a strong signal that shuffle partitioning is being constrained explicitly rather than being coalesced adaptively. Under AQE, a post-shuffle stage’s task count should vary with the actual size of the shuffle output, and AQE declines to coalesce user-specified redistributions. But the signal is not the proof — the physical plan is. Confirm it there: look for an Exchange RoundRobinPartitioning(n) node carrying a REPARTITION_BY_NUM tag. The trap is that 200 is also the default of spark.sql.shuffle.partitions, so the number looks unremarkable — the tell is that it does not move when it should.</p><p><strong>4. Why might AQE fail to rescue a badly written query?</strong></p><p>AQE re-optimizes based on runtime statistics collected from <em>completed</em> shuffle stages. Its main capabilities — coalescing shuffle partitions, converting sort-merge to broadcast hash joins, splitting skewed partitions — all operate after a shuffle has materialized, so the write cost of that shuffle is already sunk. AQE also respects user-specified operations: an explicit repartition(n) is honoured rather than coalesced away. AQE reduces the cost of imperfect plans; it does not remove shuffles that shouldn&#39;t exist, and it will not override an instruction you gave it.</p><p><strong>5. Explain runtime pruning and its main precondition.</strong></p><p>Dynamic Partition Pruning pushes a filter onto a partitioned fact table derived from the values on the other side of a join, so the scan only opens matching partitions; it appears in the plan as dynamicpruningexpression(...) inside PartitionFilters. Databricks adds Dynamic File Pruning, which does the analogous thing at file granularity using Delta statistics and is aimed particularly at non-partitioned tables and joins on non-partition columns. The shared precondition worth knowing is the broadcast dependency: spark.sql.optimizer.dynamicPartitionPruning.reuseBroadcastOnly defaults to true, and DFP was introduced with an explicit broadcast-hash-join criterion. The practical consequence is that a dimension outgrowing the broadcast threshold can cost you runtime pruning with no error and no log line. Both are also subject to internal cost heuristics, so treat their presence as something to verify in the plan rather than assume.</p><p><strong>6. How do you tell the difference between a skewed stage and an oversized stage in the Spark UI?</strong></p><p>Look at the task duration distribution in the stage’s summary metrics. Skew shows a large gap between the median and the max — most tasks finish quickly, a few run for many multiples of the median. An oversized or under-parallelised stage shows a tight distribution where every task is slow. The fixes are unrelated: skew calls for AQE skew handling, salting, or a different join strategy; the other calls for reducing the data being processed or increasing the width. Applying a skew remedy to a volume problem wastes time and can make things worse.</p><p><strong>7. What does </strong><strong>EXPLAIN FORMATTED give you over plain </strong><strong>EXPLAIN?</strong></p><p>It prints a compact numbered operator tree followed by a per-operator detail block, rather than one dense nested tree. For plans with dozens of nodes that is the difference between readable and unreadable. It surfaces the fields that matter for diagnosis — PartitionFilters, PushedFilters, Location, ReadSchema, join keys, and the specific partitioning and tag of each Exchange. EXPLAIN COST adds statistics, and EXPLAIN EXTENDED shows the parsed, analyzed, and optimized logical plans, which is what you want when investigating whether a rule fired.</p><p><strong>8. Does Catalyst reorder joins automatically?</strong></p><p>Only under conditions many teams do not meet. Cost-based join reordering requires spark.sql.cbo.enabled and spark.sql.cbo.joinReorder.enabled, both off by default in open-source Spark, and it depends on statistics gathered via ANALYZE TABLE ... COMPUTE STATISTICS. Without those, Catalyst applies rule-based transformations — predicate pushdown, column pruning, constant folding — but largely preserves the join order you wrote. It also only reorders contiguous inner-join trees, so a non-join node in the chain splits the tree and no join can move across the split. Reordering still happens freely on either side of that boundary, which is why the effect is easy to miss unless the optimal plan specifically requires crossing it.</p><p><strong>9. Why would a filter that appears in the plan still not improve performance?</strong></p><p>Because pushdown has levels. A filter at the PartitionFilters level eliminates whole partition directories at file-listing time — the files are never opened. A filter at PushedFilters reaches the Parquet reader and can skip row groups using min/max statistics, but only if the data is physically clustered such that the statistics are selective. A filter that appears only as a Filter node above the scan evaluates row by row after everything has been read. Same predicate, three completely different costs. Always check <em>where</em> in the plan the filter landed, and check the Location line to see how many partitions actually survived.</p><p><strong>10. A job’s runtime doubles with no code change and no source volume growth. Where do you look first?</strong></p><p>The physical plan, compared against a plan from a healthy run. Plans depend on code, data statistics, and configuration — the last two change on their own. Common causes: a table crossing the broadcast threshold and flipping a join strategy, which can also cost you runtime pruning; statistics going stale after a large write; small-file accumulation increasing task count and listing time; a runtime upgrade changing a default; or partition-count growth making file listing itself expensive. Cluster metrics will show you that the job is busy; only the plan will tell you what it is busy doing.</p><p><strong>11. When is a broadcast hint the right call, and when is it dangerous?</strong></p><p>Correct when the side is genuinely small, its size is bounded and predictable, and you want the join strategy to be explicit rather than heuristic — particularly when runtime pruning depends on it. Dangerous because a hint overrides the size check: if the “small” table grows, you get driver memory pressure or a broadcast timeout rather than a graceful fallback to sort-merge. That failure is loud, which is usually preferable to the silent degradation of losing pruning, but it must be a conscious trade and the table should be size-monitored.</p><p><strong>12. What would you add to a pipeline to prevent this specific regression from recurring?</strong></p><p>A plan-level assertion as a pre-flight check: run EXPLAIN FORMATTED on the critical query and fail if the expected literal PartitionFilters are absent, if the scan&#39;s partition inventory exceeds a bound, or if a REPARTITION_BY_NUM node appears in the join chain. Complement it with the dominant stage&#39;s task count captured per run from the Spark listener — a constant that never varies is the signal — plus size monitoring on any table a broadcast decision depends on. Runtime-based SLA alerting is a lagging indicator: it fires after the business has been affected, and in a gradual degradation it may not fire for weeks.</p><p>If you have debugged something with this shape — a stable pipeline that quietly stopped pruning, or a repartition() that turned out to be load-bearing in the worst way — the details are always different and the pattern rarely is.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee08a9d6659c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why a MERGE INTO Pipeline on Databricks Became Slower Every Week (And It Wasn’t the Cluster)]]></title>
            <link>https://medium.com/@mridusingh1991/why-a-merge-into-pipeline-on-databricks-became-slower-every-week-and-it-wasnt-the-cluster-2637513676a3?source=rss-0d9ade9052ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/2637513676a3</guid>
            <dc:creator><![CDATA[Mridusingh]]></dc:creator>
            <pubDate>Tue, 28 Jul 2026 14:04:30 GMT</pubDate>
            <atom:updated>2026-07-28T14:04:30.601Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why a MERGE INTO Pipeline on Databricks Became Slower Every Week (And It Wasn’t the Cluster)</h3><p><em>Note: This article is based on a representative production-style scenario that combines patterns commonly encountered while working with Delta Lake on Databricks. Implementation details, timelines, and metrics have been generalized for educational purposes.</em></p><h3>1. Background</h3><p>The pipeline in this scenario ran on Databricks and applied inserts and updates into a Delta table using MERGE INTO — a standard change-data pattern. Source records land in a staging location, get deduplicated, and get merged into a target table keyed on a business identifier plus an effective date.</p><p>For the first stretch in production, this ran in about 8 minutes on a mid-sized job cluster. Then, over the following months, the runtime crept up. Not in a dramatic single-day jump — in a slow staircase. Early on it was single digits. A couple of months in, it had drifted into the mid-teens. By several months in, it was pushing 45–50 minutes and starting to threaten the downstream SLA.</p><p>No code had changed. No cluster configuration had changed. This is the part that makes this kind of incident annoying to triage — there’s no diff to point at. Something about the <em>state</em> of the system was degrading, not the logic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*4yLA9pQrH8cOmQzX2eEJqQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*YBAd0eFiUuIj3Ug789mKqw.png" /></figure><h3>2. Initial Assumptions</h3><p>Three suspects came up immediately, in roughly this order.</p><p><strong>Cluster sizing.</strong> The easiest thing to blame. Maybe autoscaling was settling on fewer workers than it used to, or a shared pool was under contention. Reviewing cluster metrics history ruled this out fast — worker counts during the job were consistent with, if anything, slightly <em>more</em> average parallelism than in the early runs. Not a compute starvation problem.</p><p><strong>Data volume growth.</strong> The table was genuinely growing — more history, more daily change records. But the growth in row count was linear and modest, nowhere near the growth curve in runtime. If volume were the driver, you’d expect something closer to proportional scaling. That hypothesis didn’t survive the data: a table that had grown perhaps 40% in row count over the period didn’t fit a runtime increase of 5–6x.</p><p><strong>Cloud storage throttling.</strong> Worth checking given this was a MERGE hitting the same table repeatedly, but request metrics on the storage layer showed nothing close to throttling thresholds.</p><p>All three got ruled out early. Which meant the answer wasn’t external load — it was internal to the table’s own state.</p><h3>3. Investigation</h3><p>This is where the actual diagnostic work happened, and it’s worth walking through in the order it was done, because each step ruled something in or out.</p><h3>Step 1: Spark UI — where is the time actually going?</h3><p>First stop was the Spark UI for a recent slow run, compared against an early run’s saved metrics (kept from the first few weeks, which turned out to matter a lot later).</p><p>The early run had a shuffle write of roughly 200 GB feeding the join stage. The recent slow run showed close to 1.5 TB of shuffle for the same logical operation. This metric immediately stood out — the <em>shuffle</em>, not the total data volume, had exploded disproportionately to row count growth.</p><pre>Early run:  Shuffle Write ~200 GB | Stage duration ~2 min<br>Later run:  Shuffle Write ~1.5 TB | Stage duration ~30 min</pre><p>Stage details also showed a skew pattern: a small number of tasks running far longer than the rest. Not data skew from the business data itself — file-layout-driven skew, which took another step to confirm.</p><h3>Step 2: Reading the execution plan</h3><p>Running EXPLAIN (FORMAT COST) on the MERGE&#39;s underlying join showed the physical plan doing considerably more file scanning than the row count involved would justify.</p><pre>EXPLAIN FORMAT COST<br>SELECT t.id, t.eff_date<br>FROM target_table t<br>JOIN staging_source s<br>  ON t.id = s.id AND t.eff_date = s.eff_date</pre><p>The physical plan’s FileScan node reported minimal reduction in files considered even after partition and file-level filters were applied. In a healthy table, the FileScan node&#39;s stats should shrink noticeably once Catalyst can apply data skipping based on file-level min/max statistics. Here, the file count being scanned barely dropped after filtering — a sign data skipping wasn&#39;t doing its job.</p><h3>Step 3: Delta history and file-level stats</h3><p>DESCRIBE HISTORY target_table, and specifically the numTargetFilesAdded / numTargetFilesRemoved metrics on each MERGE operation, were the next stop.</p><pre>DESCRIBE HISTORY target_table</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*NN92qscJNfMbHQJ8BD0Nkg.png" /></figure><p>That was the clearest signal in the whole investigation. In the early period, MERGE touched (rewrote) around 40 files. Months later, it was touching around 3,000 files for what was still a comparable-sized batch of daily changes — roughly a 75x increase in file rewrite work for a similar logical volume of new data.</p><h3>Step 4: File layout audit</h3><p>Listing the table’s underlying files and reviewing DESCRIBE DETAIL confirmed it: file count had grown from a few hundred to nearly 500,000, with a large share sitting well under 10 MB — classic small-file accumulation. Average file size had dropped to a small fraction of any reasonable target size.</p><pre>DESCRIBE DETAIL target_table<br>-- numFiles: ~480,000 (approximate)<br>-- average file size well below a healthy target</pre><p>Cross-referencing this against the table’s operational history showed no compaction had run on it regularly, and optimized writes / auto compaction (or the runtime’s equivalent mechanism) had never been enabled. Every load was landing as its own small batch of files, with nothing consolidating them over time.</p><h3>Step 5: Confirming pruning was broken, not just file count</h3><p>One more check before concluding: was growing file count <em>alone</em> enough to explain the shuffle blow-up, or was poor clustering compounding it? A controlled test — clustering a copy of the table on the merge key and re-running the same join — dropped the scanned file count by over 90%, even without addressing the small-file problem at all. That confirmed both mechanisms were contributing independently.</p><h3>4. Root Cause</h3><p>Two independent problems were compounding each other.</p><p><strong>Problem A: Small file accumulation.</strong> Delta’s MERGE INTO is a copy-on-write operation. When Catalyst determines a physical file contains even one row that could match the join condition, Delta doesn&#39;t patch that row — it rewrites the entire file with the merged result. This is fundamental to how Delta maintains snapshot isolation and time travel; it&#39;s not a defect. But it means the <em>cost of a MERGE scales with the number of files touched</em>, not the number of rows changed. With no compaction running, every load added its own batch of small files, and total file count grew roughly with time — and because more files meant more candidate files per MERGE, the number of files actually touched and rewritten per run grew too.</p><p><strong>Problem B: Ineffective data skipping.</strong> Delta tracks min/max statistics per file for a subset of indexed columns, and Catalyst’s data skipping layer uses these stats to exclude files from a scan given a filter or join predicate — separate from partition pruning, and effective within partitions too. Without clustering on the merge key (via Z-Ordering, or on newer Databricks Runtime versions, Liquid Clustering), rows with similar key values weren’t physically co-located, so file-level min/max ranges were wide and overlapping. Almost every file’s stats said “this file might contain a matching row,” so almost nothing got pruned, and the MERGE’s join scanned — and for matches, rewrote — far more files than the actual change volume warranted.</p><p>Neither problem alone would have been this severe. Small files with good clustering would still prune reasonably well within a partition. Poor clustering on a small, well-compacted table wouldn’t generate this much shuffle. Together, they created a feedback loop: poor pruning meant more files got touched per MERGE, touched files got rewritten as new (still small, since nothing was consolidating them) files, file count kept climbing, the next run had even more low-value files to consider, and pruning got worse again. That’s why the runtime chart was a smooth accelerating curve rather than a step change — a compounding process, not a discrete event.</p><p>There’s a smaller secondary cost worth a brief mention: transaction log growth. Each MERGE commit is an entry in _delta_log, and the growing number of file adds/removes per commit meant each commit&#39;s log entry, and the periodic checkpoint files summarizing history, grew proportionally larger too — adding some overhead to reconstructing table state before a query even starts. In this scenario it was a minor contributor next to the shuffle and rewrite cost, and not the main story — worth monitoring on very high-churn tables, but not the thing to chase first.</p><h3>5. Solution</h3><p>Three changes, applied in this order, with no changes to the MERGE logic itself.</p><p><strong>Step 1 — stop the bleeding.</strong></p><pre>ALTER TABLE target_table SET TBLPROPERTIES (<br>  &#39;delta.autoOptimize.optimizeWrite&#39; = &#39;true&#39;,<br>  &#39;delta.autoOptimize.autoCompact&#39; = &#39;true&#39;<br>)</pre><p>Optimized writes shuffle data before writing so each write produces fewer, better-sized files instead of one small file per task. Auto compaction runs a lightweight compaction pass after writes when files are undersized. Note that the exact property names and defaults have evolved across Databricks Runtime versions, and on newer runtimes some of this behavior may be handled automatically or via Predictive Optimization rather than manual table properties — worth checking current documentation for the runtime in use rather than assuming these exact settings apply everywhere.</p><p><strong>Step 2 — clean up the existing file layout.</strong></p><pre>OPTIMIZE target_table<br>ZORDER BY (id, eff_date)</pre><p>OPTIMIZE performs bin-packing compaction, consolidating small files into files closer to a target size. ZORDER BY additionally co-locates rows with similar values of the given columns into the same files, tightening the min/max statistic ranges per file — which is what restores effective data skipping for the MERGE&#39;s join predicate. On newer Databricks Runtime versions, Liquid Clustering is worth evaluating as an alternative to Z-Ordering for tables like this: it maintains clustering incrementally as data is written, rather than requiring periodic re-clustering, though the right choice depends on workload and runtime version.</p><p><strong>Step 3 — set a reasonable target file size and schedule recurring maintenance.</strong></p><pre>ALTER TABLE target_table SET TBLPROPERTIES (<br>  &#39;delta.targetFileSize&#39; = &#39;134217728&#39; -- 128MB, illustrative — tune to your workload rather than treating as a universal default<br>)</pre><p>And recurring maintenance on this table rather than relying on it happening ad hoc. On Unity Catalog-enabled workspaces, Predictive Optimization can also handle scheduling OPTIMIZE (and for Liquid Clustering tables, re-clustering) automatically based on table usage patterns, which reduces the need to hand-maintain a maintenance schedule for tables like this one.</p><p>For update/delete-heavy MERGE workloads, it’s also worth evaluating deletion vectors where supported. Deletion vectors let Delta record that specific rows in a file are logically deleted or superseded, without immediately rewriting the whole file — reducing write amplification for merges that touch a small fraction of rows per file. This is a Delta-specific mechanism for reducing rewrite cost; it’s a different design than merge-on-read implementations in other open table formats, and the tradeoffs (when compaction eventually reconciles the deletion vectors, read-path overhead) are worth understanding before enabling it rather than assuming it behaves identically to similar-sounding features elsewhere. We didn’t need it in this scenario once compaction and clustering were fixed, but it’s a relevant lever for tables with very frequent row-level updates relative to file size.</p><h3>6. Results</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*_iTHC16ArYeAUmmmtEZ0Gw.png" /></figure><p>Runtime dropped roughly 5x. Shuffle dropped by about 4x — directly attributable to restored data skipping meaning far fewer files needed to be read to find matches. Files touched per MERGE dropped by an order of magnitude because compaction reduced the raw file count, and clustering meant the files that <em>were</em> touched were the ones that actually mattered.</p><p>These numbers move together for a reason: shuffle volume and files-touched are two views of the same underlying fix. Once file-level stats became selective again, Catalyst’s data skipping layer could correctly exclude the vast majority of files from the scan before the join even ran, which is what shrank both the shuffle input and the number of files eligible for rewrite.</p><h3>7. Key Takeaways</h3><ul><li><strong>A MERGE that gets slower over weeks with no code changes is usually a file-layout problem, not a logic problem.</strong> Look at DESCRIBE HISTORY&#39;s file-added/removed trend before touching anything else.</li><li><strong>File count growth and clustering quality are two separate levers — check both.</strong> Compaction alone fixes file count; it doesn’t fix poor key locality. Clustering (Z-Order or Liquid Clustering) fixes locality; it doesn’t stop new small files from accumulating on its own. Most cases need both.</li><li><strong>Automated write optimization prevents the problem; scheduled maintenance (or Predictive Optimization) fixes drift.</strong> Auto compaction alone can keep files a reasonable size but won’t proactively re-cluster as key distribution shifts over time.</li><li><strong>Shuffle volume disproportionate to row-count growth is an early, reliable warning sign.</strong> Row count growth is usually linear; if shuffle growth is outpacing it, something structural is degrading, not just scaling.</li><li><strong>Keep early metrics baselines for critical pipelines.</strong> Having an early Spark UI snapshot to diff against a later one turned this investigation from a multi-day guessing exercise into a fast, evidence-driven one.</li></ul><h3>8. Interview Corner</h3><p><strong>What interview questions could be asked from this scenario?</strong></p><ol><li><strong>Why does </strong><strong>MERGE INTO rewrite entire files instead of updating individual rows?</strong> Delta Lake files are immutable Parquet files; MERGE achieves snapshot isolation and time travel by writing new files and atomically updating the table&#39;s metadata to point to them, rather than mutating existing files in place. Any file containing a matched row must be rewritten in full, unless deletion vectors are in use.</li><li><strong>What’s the difference between partition pruning and data skipping in Delta Lake?</strong> Partition pruning eliminates entire partitions based on partition column filters before any file is listed. Data skipping operates within (or across) partitions, using per-file min/max statistics to exclude individual files from a scan even without partition columns being involved.</li><li><strong>How does clustering (Z-Order or Liquid Clustering) improve data skipping?</strong> It physically co-locates rows with similar values across the specified columns into the same files, tightening the min/max range recorded per file. Tighter ranges let a given filter/join predicate correctly exclude more files as “definitely not matching.”</li><li><strong>What’s the practical difference between OPTIMIZE, OPTIMIZE with ZORDER BY, and Liquid Clustering?</strong> Plain OPTIMIZE performs bin-packing compaction — combining small files into fewer, larger ones — with no guarantee about clustering inside those files. ZORDER BY additionally clusters rows during that same compaction pass, but requires periodic re-runs as new data lands. Liquid Clustering maintains clustering incrementally as part of normal writes, reducing the need for scheduled re-clustering, on runtimes that support it.</li><li><strong>What do optimized writes and auto compaction do, and why are they described as “or their runtime equivalent” here?</strong> Optimized writes shuffle data before writing so files land at a healthier size immediately; auto compaction runs a follow-up compaction pass on undersized files after a write. The exact configuration surface for this has evolved across Databricks Runtime versions and is increasingly handled by Predictive Optimization on newer, Unity Catalog-enabled setups, so the specific property names shouldn’t be assumed to be identical across every environment.</li><li><strong>Why would MERGE performance degrade over time even if underlying business data growth is linear?</strong> Because MERGE cost is a function of files touched, not rows changed. If file count grows via small-file accumulation and/or clustering degrades as new key ranges land, the number of files that must be scanned and rewritten per MERGE can grow faster than the underlying row count, producing non-linear degradation.</li><li><strong>How would you diagnose whether a slow MERGE is a shuffle problem versus a metadata/file-listing problem?</strong> Compare the Spark UI’s shuffle read/write metrics and stage durations against DESCRIBE HISTORY&#39;s file-touched counts and DESCRIBE DETAIL&#39;s file count/average size. Disproportionate shuffle growth relative to row-count growth points to poor pruning; unusually large time spent before query stages even start can point toward transaction log or metadata overhead, though this is typically a secondary factor.</li><li><strong>What are deletion vectors, and how do they change MERGE’s cost profile?</strong> They let Delta mark specific rows within a file as logically deleted or superseded without immediately rewriting the whole file, reducing write amplification for update/delete-heavy MERGE workloads on supporting Delta/Databricks Runtime versions — at the cost of some read-path overhead to reconcile them until a later compaction.</li><li><strong>Why can’t you just increase cluster size to fix a MERGE slowed down by small files and poor clustering?</strong> More compute can mask the symptom by absorbing more shuffle with more parallelism, but doesn’t address the root cause — the number of files being touched keeps growing over time, so the same problem returns at a larger scale, at higher cost, with no ceiling.</li><li><strong>What’s the risk of running compaction/clustering maintenance too frequently on a high-write-volume table?</strong> Compaction and clustering are themselves compute-intensive rewrite operations; running them too often relative to write volume can create contention, unnecessary cost, and additional versions in the transaction log. Predictive Optimization is designed to help balance this automatically based on observed usage, but the underlying tradeoff — maintenance cost versus query/merge benefit — still applies.</li><li><strong>How would you decide which columns to cluster a MERGE target table on?</strong> Prioritize columns used in the MERGE’s join/match condition and any high-selectivity columns used in downstream filtering. For Z-Ordering specifically, effectiveness typically drops off after a small number of columns due to how the underlying space-filling curve interleaves values; Liquid Clustering has different tradeoffs worth checking against current documentation.</li><li><strong>What’s a proactive way to prevent this class of problem instead of discovering it via an SLA breach?</strong> Track file-added/removed counts per MERGE run and average file size over time as pipeline health metrics, not just runtime — runtime is a lagging indicator, file layout metrics are a leading one.</li></ol><p><strong>Tags:</strong> Databricks, Delta Lake, Apache Spark, Data Engineering, Big Data</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2637513676a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>