<?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 Manomita Dey on Medium]]></title>
        <description><![CDATA[Stories by Manomita Dey on Medium]]></description>
        <link>https://medium.com/@manomita.dey?source=rss-1e9fba1aa067------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*bPKlZDB1Vuq0tZM5</url>
            <title>Stories by Manomita Dey on Medium</title>
            <link>https://medium.com/@manomita.dey?source=rss-1e9fba1aa067------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 00:56:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@manomita.dey/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[Your Lakehouse Is a Binder: Modelling a Medallion Architecture on Databricks, End to End]]></title>
            <link>https://medium.com/@manomita.dey/your-lakehouse-is-a-binder-modelling-a-medallion-architecture-on-databricks-end-to-end-2369da375a4a?source=rss-1e9fba1aa067------2</link>
            <guid isPermaLink="false">https://medium.com/p/2369da375a4a</guid>
            <dc:creator><![CDATA[Manomita Dey]]></dc:creator>
            <pubDate>Fri, 23 Oct 2026 11:39:33 GMT</pubDate>
            <atom:updated>2026-10-23T11:39:33.018Z</atom:updated>
            <content:encoded><![CDATA[<h3>Catalogs, schemas and tables finally clicked for me when I stopped thinking about storage and started thinking about stationery. Here is the full design of a small retail lakehouse, from business questions to Delta DDL to deployable code.</h3><p><em>Tags: Databricks, Data Engineering, Data Modeling, Delta Lake, Unity Catalog</em></p><p>While studying for the Databricks Data Engineer Associate exam, I kept hitting the same wall. I could recite “bronze is raw, silver is clean, gold is aggregated,” but I couldn’t tell you where the tables actually <em>live</em>, how many catalogs a project should have, or what a gold table should look like column by column.</p><p>So I built a made-up company, <strong>ShopLake</strong>, and modelled it properly. This post walks through the whole thing: the mental model, the architecture, the three levels of data modelling, the physical tables, the repo, and the code for each layer.</p><p>If you only remember one thing, make it this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*fT7uTV89kY3vHrk7wYMdog.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gl7zNsY2eVkpJ9UEYpRkjg.png" /></figure><h3>1. The binder analogy</h3><p>Unity Catalog uses a three-level namespace: catalog.schema.table. That maps neatly onto office stationery.</p><ul><li><strong>Binder → Catalog</strong>, one per environment: dev_shoplake, test_shoplake, prod_shoplake</li><li><strong>Folder → Schema</strong>, one per layer: bronze, silver, gold</li><li><strong>Page → Table or view</strong>: gold.fact_order_line</li><li><strong>Plastic sleeve for loose papers → Volume</strong> for raw, non-tabular files: bronze.landing</li></ul><p>So a fully qualified page looks like prod_shoplake.gold.fact_order_line, and a raw file sits at /Volumes/prod_shoplake/bronze/landing/orders/.</p><p>The key design choice: <strong>one binder per environment, and identical folders in every binder.</strong> The same code runs in dev, test and prod, and the only thing that changes is the catalog name. Promotion moves code between binders. It never copies data.</p><pre>-- Run once per environment, :env = dev | test | prod<br>CREATE CATALOG IF NOT EXISTS IDENTIFIER(:env || &#39;_shoplake&#39;);<br>USE CATALOG IDENTIFIER(:env || &#39;_shoplake&#39;);</pre><pre>CREATE SCHEMA IF NOT EXISTS bronze COMMENT &#39;Raw, source-shaped, append-only&#39;;<br>CREATE SCHEMA IF NOT EXISTS silver COMMENT &#39;Cleaned, deduplicated, conformed&#39;;<br>CREATE SCHEMA IF NOT EXISTS gold   COMMENT &#39;Star schema for BI and ML&#39;;</pre><pre>CREATE VOLUME IF NOT EXISTS bronze.landing COMMENT &#39;Files dropped by source systems&#39;;</pre><h3>2. The use case: start from the questions</h3><p>ShopLake is an online retailer with three sources:</p><ul><li><strong>Order events</strong> from the web and app, as JSON with a nested lines array, arriving continuously.</li><li><strong>Customer changes</strong> from a Postgres database, as CDC JSON with op = I / U / D and an updated_at timestamp, every 15 minutes.</li><li><strong>Product catalogue</strong> as a full CSV snapshot, once a day.</li></ul><p>And the business wants to answer:</p><ol><li>Daily net revenue and units by category, region and channel.</li><li>Revenue by the customer’s segment <em>at the time of the order</em>.</li><li>Top products and average order value per week.</li><li>Repeat-purchase rate per signup cohort.</li></ol><p>Write these down before you write any code. <strong>The questions decide the gold layer, and the gold layer decides what silver must provide.</strong> Question 2 alone tells us we will need history on customers, which is a modelling decision we would otherwise discover far too late.</p><h3>3. The architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RaBhu1Hjpb8veeBqOqpLkw.png" /></figure><p>What each folder is responsible for:</p><p><strong>Bronze: keep everything, change nothing.</strong> One table per source feed, shaped exactly like the source. Append-only, duplicates and bad rows included, because bronze is your replay button. The only things you add are lineage columns like _ingested_at and _source_file.</p><p><strong>Silver: one clean table per business entity.</strong> Typed, deduplicated, nested arrays exploded into rows, close to third normal form. Customers and products hold their current state (SCD Type 1). Rows that fail quality checks go to a quarantine table instead of flowing downstream.</p><p><strong>Gold: shaped for reading.</strong> A star schema with facts and dimensions joined on surrogate keys, plus aggregate materialized views on top. This is the only layer modelled for consumers rather than for correctness.</p><p>A single Lakeflow Job runs bronze tasks, then silver, then gold, with the catalog name passed in as a job parameter. Unity Catalog sits over all of it, providing grants, lineage, and audit logs.</p><h3>4. Model in three passes</h3><p>I used to jump straight from “we need a sales table” to CREATE TABLE. Splitting it into three passes made every decision easier.</p><p><strong>Conceptual: what exists and how it relates.</strong> No columns, no types. Something you could draw on a whiteboard with a business stakeholder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GLmGRRPjlS4Rh1-ZeNCnLA.png" /></figure><p><strong>Logical: attributes, keys and grain.</strong> Still independent of Databricks. An order line is identified by order_id + line_number and has product_id, quantity, unit_price and discount. A customer&#39;s segment and city change over time and we need their history.</p><p><strong>Physical: how it is stored in Delta.</strong> Catalog and schema names, data types, nullability, constraints, clustering keys, table properties. This is the DDL.</p><h3>Picking the grain</h3><p>The single most important gold decision is the grain of the fact table. The recipe:</p><ol><li><strong>Pick the business process:</strong> selling a product in an order.</li><li><strong>Declare the grain:</strong> one row per order line. Go as fine as the source allows, because you can always roll up, but you can never drill down.</li><li><strong>Pick the dimensions</strong> that describe that row: who (customer), what (product), when (date).</li><li><strong>Pick the facts</strong> that are true at that grain: quantity, gross amount, discount, net amount.</li></ol><p>A classic mistake: putting an order-level value such as a shipping fee onto every line, then summing it. Three lines, one shipping fee, three times the revenue. Either allocate it across lines or keep a separate order-grain fact.</p><h3>Slowly changing dimensions</h3><ul><li><strong>SCD Type 1</strong> overwrites in place and keeps no history. ShopLake uses it for silver.customers and dim_product.</li><li><strong>SCD Type 2</strong> closes the old row and inserts a new version with valid_from, valid_to and is_current. ShopLake uses it for gold.dim_customer.</li></ul><p>Why SCD 2 for customers? A customer who moved from Standard to VIP in June should not turn their March orders into VIP revenue. The fact row stores the surrogate key of the customer <em>version</em> that was current on the order date, which is exactly what business question 2 needs.</p><p>Products, on the other hand, use SCD 1: if someone fixes a typo in a product name, you want old sales to show the corrected name too.</p><h3>5. The gold star schema</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H4xNykbePuIe6AjWZTplKA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3iE-3NC8kTkzqmIHvtHtIw.png" /></figure><p>A few conventions that keep it fast and predictable:</p><ul><li>Joins always go fact → dimension on a <strong>surrogate key</strong> (_sk), never on a business key.</li><li>Dates are stored in facts as INT keys like 20261022, joined to a generated dim_date.</li><li>Money is DECIMAL(12,2). Never DOUBLE.</li></ul><h3>6. Physical design: where the model becomes Delta</h3><pre>CREATE TABLE IF NOT EXISTS gold.fact_order_line (<br>  order_id      STRING        NOT NULL,<br>  line_number   INT           NOT NULL,<br>  date_key      INT           NOT NULL,<br>  customer_sk   BIGINT        NOT NULL,<br>  product_sk    BIGINT        NOT NULL,<br>  order_ts      TIMESTAMP     NOT NULL,<br>  channel       STRING,<br>  order_status  STRING,<br>  quantity      INT           NOT NULL,<br>  gross_amount  DECIMAL(12,2) NOT NULL,<br>  discount_amt  DECIMAL(12,2) NOT NULL,<br>  net_amount    DECIMAL(12,2) GENERATED ALWAYS AS (gross_amount - discount_amt),<br>  CONSTRAINT pk_fact_order_line PRIMARY KEY (order_id, line_number),<br>  CONSTRAINT fk_customer FOREIGN KEY (customer_sk) REFERENCES gold.dim_customer,<br>  CONSTRAINT fk_product  FOREIGN KEY (product_sk)  REFERENCES gold.dim_product,<br>  CONSTRAINT qty_positive CHECK (quantity &gt; 0)<br>)<br>CLUSTER BY (date_key, product_sk)<br>COMMENT &#39;One row per order line.&#39;<br>TBLPROPERTIES (<br>  &#39;delta.enableChangeDataFeed&#39;   = &#39;true&#39;,<br>  &#39;delta.enableDeletionVectors&#39;  = &#39;true&#39;<br>);</pre><p>And the SCD 2 dimension gets an identity column for its surrogate key:</p><pre>CREATE TABLE IF NOT EXISTS gold.dim_customer (<br>  customer_sk  BIGINT GENERATED ALWAYS AS IDENTITY,<br>  customer_id  STRING NOT NULL,<br>  full_name STRING, email STRING, city STRING, country STRING, segment STRING,<br>  row_hash     STRING NOT NULL,      -- sha2 of tracked columns<br>  valid_from   TIMESTAMP NOT NULL,<br>  valid_to     TIMESTAMP,            -- NULL means still current<br>  is_current   BOOLEAN NOT NULL,<br>  CONSTRAINT pk_dim_customer PRIMARY KEY (customer_sk)<br>) CLUSTER BY (customer_id);</pre><p>Things in that DDL that surprised me:</p><ul><li><strong>Not every constraint is enforced.</strong> NOT NULL and CHECK are enforced, and a bad row fails the whole write. PRIMARY KEY and FOREIGN KEY are <em>informational</em>: they document the model and help BI tools, but they will happily accept duplicates.</li><li><strong>Liquid clustering is the new default.</strong> CLUSTER BY replaces PARTITIONED BY plus ZORDER for new tables, takes up to four keys, and lets you change keys later. You can&#39;t combine it with partitioning or Z-ordering on the same table. Classic partitioning is now only for very large tables on a low-cardinality column.</li><li><strong>Identity columns are unique but not gap-free.</strong> Don’t build logic that expects consecutive surrogate keys.</li></ul><h3>7. The repo mirrors the binder</h3><pre>shoplake/<br>├── databricks.yml              # bundle + dev/test/prod targets<br>├── resources/<br>│   └── shoplake_daily.job.yml  # task graph<br>├── src/<br>│   ├── setup/                  # catalog, schemas, grants<br>│   ├── common/                 # config, shared quality checks<br>│   ├── bronze/                 # one file per source feed<br>│   ├── silver/                 # one file per entity<br>│   └── gold/                   # DDL, dims, fact, MV<br>└── tests/</pre><p>A Databricks Asset Bundle defines one target per environment, and each target sets a single variable:</p><pre>bundle:<br>  name: shoplake</pre><pre>variables:<br>  catalog:<br>    description: Environment catalog</pre><pre>targets:<br>  dev:<br>    mode: development<br>    default: true<br>    variables: { catalog: dev_shoplake }<br>  test:<br>    variables: { catalog: test_shoplake }<br>  prod:<br>    mode: production<br>    variables: { catalog: prod_shoplake }<br>    run_as:<br>      service_principal_name: shoplake-ci</pre><p>CI runs databricks bundle deploy -t prod after a merged pull request. Nobody copies tables by hand.</p><h3>8. Code for each layer</h3><p>Every script reads the catalog from a parameter and never hardcodes prod_.</p><h3>Bronze: Auto Loader, append-only</h3><pre>from pyspark.sql import functions as F</pre><pre>catalog = dbutils.widgets.get(&quot;catalog&quot;)<br>landing = f&quot;/Volumes/{catalog}/bronze/landing/orders/&quot;<br>checkpoint = f&quot;/Volumes/{catalog}/bronze/landing/_checkpoints/orders_raw&quot;</pre><pre>(spark.readStream.format(&quot;cloudFiles&quot;)<br>    .option(&quot;cloudFiles.format&quot;, &quot;json&quot;)<br>    .option(&quot;cloudFiles.schemaLocation&quot;, checkpoint)<br>    .option(&quot;cloudFiles.inferColumnTypes&quot;, &quot;true&quot;)<br>    .load(landing)<br>    .withColumn(&quot;_ingested_at&quot;, F.current_timestamp())<br>    .withColumn(&quot;_source_file&quot;, F.col(&quot;_metadata.file_path&quot;))<br>  .writeStream<br>    .option(&quot;checkpointLocation&quot;, checkpoint)<br>    .trigger(availableNow=True)          # batch-style run inside the daily job<br>    .toTable(f&quot;{catalog}.bronze.orders_raw&quot;))</pre><h3>Silver: deduplicate, quarantine, explode</h3><pre>from pyspark.sql import Window, functions as F</pre><pre>raw = spark.read.table(f&quot;{catalog}.bronze.orders_raw&quot;)</pre><pre># One row per order: keep the latest event<br>w = Window.partitionBy(&quot;order_id&quot;).orderBy(F.col(&quot;event_ts&quot;).desc())<br>orders = (raw.withColumn(&quot;rn&quot;, F.row_number().over(w)).filter(&quot;rn = 1&quot;))</pre><pre>good = orders.filter(&quot;order_id IS NOT NULL AND customer_id IS NOT NULL&quot;)<br>bad  = orders.filter(&quot;order_id IS NULL OR customer_id IS NULL&quot;)<br>bad.write.mode(&quot;append&quot;).saveAsTable(f&quot;{catalog}.silver.orders_quarantine&quot;)</pre><pre># One row per order line<br>lines = (good<br>    .select(&quot;order_id&quot;, F.posexplode(&quot;lines&quot;).alias(&quot;pos&quot;, &quot;l&quot;))<br>    .select(&quot;order_id&quot;,<br>            (F.col(&quot;pos&quot;) + 1).alias(&quot;line_number&quot;),<br>            F.col(&quot;l.product_id&quot;).alias(&quot;product_id&quot;),<br>            F.col(&quot;l.qty&quot;).cast(&quot;int&quot;).alias(&quot;quantity&quot;),<br>            F.col(&quot;l.price&quot;).cast(&quot;decimal(12,2)&quot;).alias(&quot;unit_price&quot;)))</pre><p>Customers come in as CDC, so silver applies them with a MERGE that handles deletes:</p><pre>MERGE INTO silver.customers t<br>USING (<br>  SELECT * FROM bronze.customers_cdc_raw<br>  QUALIFY row_number() OVER (PARTITION BY customer_id ORDER BY updated_at DESC) = 1<br>) s<br>ON t.customer_id = s.customer_id<br>WHEN MATCHED AND s.op = &#39;D&#39; THEN DELETE<br>WHEN MATCHED THEN UPDATE SET<br>  full_name = s.full_name, email = s.email, city = s.city,<br>  country = s.country, segment = s.segment, updated_at = s.updated_at<br>WHEN NOT MATCHED AND s.op &lt;&gt; &#39;D&#39; THEN<br>  INSERT (customer_id, full_name, email, city, country, segment, updated_at)<br>  VALUES (s.customer_id, s.full_name, s.email, s.city, s.country, s.segment, s.updated_at);</pre><h3>Gold: SCD 2 with a MERGE trick</h3><p>The classic SCD 2 MERGE feeds each changed customer in twice. One copy matches the current row so it can be closed. The other copy has a NULL merge key, which can never match, so it gets inserted as the new version.</p><pre>MERGE INTO gold.dim_customer t<br>USING (<br>  SELECT customer_id AS merge_key, * FROM src<br>  UNION ALL<br>  SELECT NULL AS merge_key, s.*<br>  FROM src s JOIN gold.dim_customer d<br>    ON s.customer_id = d.customer_id<br>   AND d.is_current AND s.row_hash &lt;&gt; d.row_hash<br>) s<br>ON t.customer_id = s.merge_key AND t.is_current<br>WHEN MATCHED AND t.row_hash &lt;&gt; s.row_hash THEN<br>  UPDATE SET is_current = false, valid_to = s.change_ts<br>WHEN NOT MATCHED THEN<br>  INSERT (customer_id, full_name, email, city, country, segment,<br>          row_hash, valid_from, valid_to, is_current)<br>  VALUES (s.customer_id, s.full_name, s.email, s.city, s.country, s.segment,<br>          s.row_hash, s.change_ts, NULL, true);</pre><h3>Gold: the fact, with a point-in-time join</h3><p>This is where SCD 2 pays off. Each order line joins to the customer version that was valid when the order was placed:</p><pre>JOIN gold.dim_customer c<br>  ON  c.customer_id = o.customer_id<br>  AND o.order_ts &gt;= c.valid_from<br>  AND (o.order_ts &lt; c.valid_to OR c.valid_to IS NULL)</pre><p>In a real build, use a LEFT JOIN and map unmatched customers or products to an &quot;Unknown&quot; row with sk = -1, so no sales silently disappear.</p><h3>Or skip the hand-written MERGE entirely</h3><p>Lakeflow Declarative Pipelines (formerly Delta Live Tables) can do the SCD 2 work for you:</p><pre>CREATE OR REFRESH STREAMING TABLE gold.dim_customer_hist;</pre><pre>CREATE FLOW customers_scd2 AS AUTO CDC INTO gold.dim_customer_hist<br>FROM STREAM(bronze.customers_cdc_raw)<br>KEYS (customer_id)<br>APPLY AS DELETE WHEN op = &#39;D&#39;<br>SEQUENCE BY updated_at<br>COLUMNS * EXCEPT (op, _ingested_at, _rescued_data)<br>STORED AS SCD TYPE 2;</pre><p>SEQUENCE BY sorts out-of-order events, KEYS is the natural key, and if you leave out STORED AS, you get SCD Type 1.</p><h3>And the aggregate on top</h3><pre>CREATE OR REPLACE MATERIALIZED VIEW gold.mv_daily_sales AS<br>SELECT f.date_key, p.category, c.segment, f.channel,<br>       count(DISTINCT f.order_id) AS orders,<br>       sum(f.quantity)            AS units,<br>       sum(f.net_amount)          AS net_revenue<br>FROM gold.fact_order_line f<br>JOIN gold.dim_product  p USING (product_sk)<br>JOIN gold.dim_customer c USING (customer_sk)<br>GROUP BY ALL;</pre><h3>9. Who gets which binder</h3><pre>GRANT USE CATALOG ON CATALOG prod_shoplake TO `analysts`;<br>GRANT USE SCHEMA, SELECT ON SCHEMA prod_shoplake.gold TO `analysts`;</pre><p>Analysts see only the gold folder of the prod binder. Engineers have full rights in dev and read-only access elsewhere. A CI service principal owns test and prod.</p><p>One gotcha: SELECT on a table is not enough on its own. A reader also needs USE CATALOG on the binder and USE SCHEMA on the folder.</p><h3>10. Build it yourself</h3><p>You can do all of this in a free Databricks workspace, one small step per evening:</p><ol><li>Write the business questions and sketch the conceptual model.</li><li>Declare the gold grain, list facts and dimensions, choose SCD types.</li><li>Write the logical model for each silver and gold table.</li><li>Create the dev catalog, schemas, volume and grants.</li><li>Write the gold DDL.</li><li>Drop sample JSON and CSV into the volume and build bronze with Auto Loader.</li><li>Build silver: dedupe, explode, quarantine, MERGE.</li><li>Build gold: dim_date, dim_product, SCD 2 dim_customer, then the fact, then the materialized view.</li><li>Wire it into a Lakeflow Job with a catalog parameter and put a dashboard on top.</li><li>Deploy to test with an Asset Bundle and check lineage in Catalog Explorer.</li></ol><h3>Quick reference</h3><ul><li><strong>Raw data kept unchanged for replay?</strong> Bronze.</li><li><strong>Cleaned and conformed, not aggregated?</strong> Silver.</li><li><strong>Star schemas and business aggregates?</strong> Gold.</li><li><strong>Isolate dev from prod?</strong> A separate catalog per environment.</li><li><strong>Governed home for raw files?</strong> A Unity Catalog volume.</li><li><strong>Keep the full history of an attribute?</strong> SCD Type 2.</li><li><strong>Out-of-order CDC events in Lakeflow?</strong> SEQUENCE BY.</li><li><strong>Are primary keys enforced?</strong> No. NOT NULL and CHECK are.</li><li><strong>New table, unknown query patterns?</strong> Liquid clustering.</li><li><strong>Read only rows that changed?</strong> Change Data Feed.</li><li><strong>Drop a managed table?</strong> The data files go too.</li></ul><h3>Wrapping up</h3><p>The medallion architecture stopped feeling abstract once I gave every piece a physical home: one binder per environment, three folders per binder, one page per dataset. From there, the modelling follows a clear chain. Business questions set the gold grain, the gold grain sets what silver must provide, and bronze simply keeps a faithful copy of everything that arrived.</p><p>If you’re preparing for the Databricks Data Engineer Associate exam, try building ShopLake yourself. Writing the SCD 2 MERGE once by hand teaches you more than reading about it ten times.</p><p><em>ShopLake is a made-up example company. All code is illustrative and written for Unity Catalog-enabled Databricks workspaces.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2369da375a4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced SQL Window Functions for Analytics Engineering]]></title>
            <link>https://medium.com/@manomita.dey/advanced-sql-window-functions-for-analytics-engineering-0780cf4849a7?source=rss-1e9fba1aa067------2</link>
            <guid isPermaLink="false">https://medium.com/p/0780cf4849a7</guid>
            <dc:creator><![CDATA[Manomita Dey]]></dc:creator>
            <pubDate>Thu, 15 Oct 2026 22:16:33 GMT</pubDate>
            <atom:updated>2026-10-15T22:16:33.235Z</atom:updated>
            <content:encoded><![CDATA[<p>Every analytics engineer has a moment where GROUP BY stops being enough. You need the running total <em>and</em> the individual row. You need &quot;rank within customer&quot; without collapsing the customer&#39;s other columns. You need to compare this row to the one before it, or to the first row in its group, or to a 7-day trailing average — all while keeping every row intact.</p><p>That moment is where window functions stop being a nice-to-have and become the backbone of your SQL. If you’re still reaching for self-joins or correlated subqueries to solve these problems, you’re writing more code, running slower queries, and making your future self debug a mess. This week, let’s go past ROW_NUMBER() OVER (PARTITION BY x ORDER BY y) — the one window function pattern everyone memorizes — and into the ones that actually separate competent SQL from analytics-engineering-grade SQL.</p><h3>Why GROUP BY Isn’t Enough</h3><p>GROUP BY answers &quot;what&#39;s the aggregate for this bucket?&quot; It collapses rows. Window functions answer &quot;what&#39;s the aggregate <em>relative to</em> this row?&quot; and keep every row alive. That distinction is the whole point.</p><p>Say you want each order’s amount alongside the customer’s total spend. With GROUP BY you&#39;d aggregate into one row per customer and lose the order-level grain, then join back to get it. With a window function, you do it in one pass:</p><pre>select<br>    order_id,<br>    customer_id,<br>    order_amount,<br>    sum(order_amount) over (partition by customer_id) as customer_lifetime_spend<br>from orders</pre><p>No join, no subquery, no second pass over the table. This is the first mental shift: window functions are for when you need the detail row <em>and</em> a derived aggregate in the same result set.</p><h3>The Anatomy Nobody Reads Carefully</h3><p>The OVER() clause has three parts, and most people only ever use two:</p><pre>&lt;function&gt;() over (<br>    partition by &lt;grouping columns&gt;<br>    order by &lt;sort columns&gt;<br>    rows between &lt;frame start&gt; and &lt;frame end&gt;<br>)</pre><p>PARTITION BY is your &quot;GROUP BY, but don&#39;t collapse.&quot; ORDER BY defines sequence within the partition — essential for ranking, LAG/LEAD, and running totals. The frame clause is the part everyone skips, and it&#39;s exactly where the default behavior bites you.</p><p>Here’s the trap: when you write sum(x) over (partition by y order by z) with no explicit frame, most engines default to RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. That gives you a running total — which is often what you want, but it&#39;s a default, not a guarantee, and RANGE vs ROWS behave differently on tied values in the ORDER BY column. If two rows share the same order_date, RANGE will sum them together as if they were one row (lumping ties into the same frame), while ROWS treats each physically distinct row on its own. If you want a precise, row-by-row running total, be explicit:</p><pre>sum(order_amount) over (<br>    partition by customer_id<br>    order by order_date<br>    rows between unbounded preceding and current row<br>) as running_total</pre><p>Don’t rely on the default. Write the frame clause. It costs you one line and saves you a debugging session three months from now when someone asks why two same-day orders got summed into a single running-total step.</p><h3>Ranking Functions: Know Which One You Actually Want</h3><p>ROW_NUMBER(), RANK(), and DENSE_RANK() get used interchangeably by people who haven&#39;t been burned yet. They diverge the moment you have ties:</p><pre>select<br>    customer_id,<br>    order_date,<br>    order_amount,<br>    row_number() over (partition by customer_id order by order_date desc) as rn,<br>    rank()       over (partition by customer_id order by order_date desc) as rnk,<br>    dense_rank() over (partition by customer_id order by order_date desc) as drnk<br>from orders</pre><p>ROW_NUMBER() never ties — it breaks ties arbitrarily (or by whatever secondary order you give it), which makes it the right choice for deduplication. RANK() gives tied rows the same rank but leaves gaps afterward (1, 1, 3). DENSE_RANK() gives tied rows the same rank with no gaps (1, 1, 2). Use RANK() when you&#39;re reporting a leaderboard and gaps are meaningful information; use DENSE_RANK() when you want a clean ordinal without caring how many rows tied for a spot.</p><p>The single most common production use of ROW_NUMBER() is deduplication — picking the latest record per key out of a raw, append-only source:</p><pre>with ranked as (<br>    select<br>        *,<br>        row_number() over (<br>            partition by order_id<br>            order by _loaded_at desc<br>        ) as rn<br>    from raw_orders<br>)<br>select * from ranked where rn = 1</pre><p>This single pattern replaces a huge amount of hand-rolled “find the max timestamp then join back” logic, and it’s the foundation of nearly every staging model you’ll write in dbt against a CDC or event-sourced raw table.</p><h3>LAG and LEAD: Comparing a Row to Its Neighbors</h3><p>LAG() and LEAD() let you reach into the previous or next row within a partition without a self-join. The classic use case is period-over-period comparison:</p><pre>select<br>    customer_id,<br>    order_date,<br>    order_amount,<br>    lag(order_amount) over (<br>        partition by customer_id order by order_date<br>    ) as prior_order_amount,<br>    order_amount - lag(order_amount) over (<br>        partition by customer_id order by order_date<br>    ) as change_vs_prior_order<br>from orders</pre><p>Less obvious, but just as valuable: using LAG/LEAD to detect gaps and sessionize events. If you&#39;re building a sessionization model — grouping raw clickstream or login events into sessions with a 30-minute idle cutoff — this is the workhorse:</p><pre>with gaps as (<br>    select<br>        user_id,<br>        event_time,<br>        event_time - lag(event_time) over (<br>            partition by user_id order by event_time<br>        ) as gap_to_prior<br>    from events<br>),<br>session_flags as (<br>    select<br>        *,<br>        case when gap_to_prior is null or gap_to_prior &gt; interval &#39;30 minutes&#39;<br>             then 1 else 0 end as is_new_session<br>    from gaps<br>),<br>sessions as (<br>    select<br>        *,<br>        sum(is_new_session) over (<br>            partition by user_id order by event_time<br>        ) as session_id<br>    from session_flags<br>)<br>select * from sessions</pre><p>That nested sum() over a flag column is a pattern worth memorizing on its own: a running sum of a 0/1 indicator is how you turn &quot;is this a new group?&quot; into a stable group ID, in pure SQL, with no procedural looping.</p><h3>A Concrete Use Case: Cohort Retention</h3><p>Pulling this together, here’s a cohort retention query — the kind of thing a product analytics stakeholder will ask for eventually, and the kind of query that’s painful without window functions and fairly clean with them:</p><pre>with first_order as (<br>    select<br>        customer_id,<br>        min(order_date) as cohort_date<br>    from orders<br>    group by customer_id<br>),<br>monthly_activity as (<br>    select distinct<br>        o.customer_id,<br>        date_trunc(&#39;month&#39;, o.order_date) as activity_month,<br>        f.cohort_date<br>    from orders o<br>    join first_order f on o.customer_id = f.customer_id<br>),<br>cohort_sizes as (<br>    select<br>        cohort_date,<br>        count(distinct customer_id) as cohort_size<br>    from first_order<br>    group by cohort_date<br>)<br>select<br>    m.cohort_date,<br>    datediff(&#39;month&#39;, m.cohort_date, m.activity_month) as months_since_cohort,<br>    count(distinct m.customer_id) as active_customers,<br>    c.cohort_size,<br>    count(distinct m.customer_id)::float / c.cohort_size as retention_rate<br>from monthly_activity m<br>join cohort_sizes c on m.cohort_date = c.cohort_date<br>group by 1, 2, 4<br>order by 1, 2</pre><p>No window function in the final select, but notice how the groundwork — min() per customer to establish a cohort, the join back to a per-group constant — is exactly the same relative-to-the-group thinking that window functions formalize. Once you&#39;re comfortable with windows, you start seeing this pattern everywhere, whether or not OVER() ends up in the final line.</p><h3>Pitfalls Worth Knowing Before Production</h3><p>A few things that will cost you time if you learn them the hard way instead of now. Nested window functions aren’t allowed directly — you can’t call rank() on the result of another window function in the same select without a subquery or CTE wrapping it first. Window functions run after WHERE and GROUP BY but before the final ORDER BY and LIMIT, which means you can&#39;t filter on a window function&#39;s result in the same SELECT — you need a CTE or subquery and a WHERE clause one level up, exactly like the dedup pattern above. And on both Snowflake and Databricks, a window function with a wide PARTITION BY on a huge table can force a large shuffle or spill — if you&#39;re running this over billions of rows, check the query profile and consider whether you actually need the full partition or whether a pre-aggregation can shrink it first.</p><h3>Takeaway</h3><p>Window functions are the difference between SQL that fights your grain and SQL that respects it — you keep every row and still get group-relative answers, without a single self-join. Learn the frame clause, know the difference between your ranking functions, and LAG/SUM-of-flags will solve more &quot;hard&quot; analytics problems than you&#39;d expect.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0780cf4849a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Databricks ABAC — step-by-step notes]]></title>
            <link>https://medium.com/@manomita.dey/databricks-abac-step-by-step-notes-5d390132ec94?source=rss-1e9fba1aa067------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d390132ec94</guid>
            <dc:creator><![CDATA[Manomita Dey]]></dc:creator>
            <pubDate>Thu, 08 Oct 2026 22:49:28 GMT</pubDate>
            <atom:updated>2026-10-08T22:49:28.995Z</atom:updated>
            <content:encoded><![CDATA[<p>ABAC means Attribute-Based Access Control. In Unity Catalog, governed tags describe data objects, policies discover matching objects, and row-filter or masking functions control query results. Checked against Databricks documentation on 3 October 2026. This is a learning example, not a change to your workspace.</p><h3>Mind map</h3><pre>```mermaid<br>mindmap<br>  root((Unity Catalog ABAC))<br>    Attributes<br>      Governed tags<br>      Controlled keys and values<br>      Direct column tags<br>    Policies<br>      Scope<br>      Principals and exemptions<br>      Tag conditions<br>    Data protection<br>      Row filter returns boolean<br>      Column mask returns replacement<br>      UDF implements logic<br>    Operations<br>      Test different identities<br>      Audit tag changes<br>      Check policy conflicts<br>```</pre><h3>Worked example</h3><p>An account group called uk_analysts can query a customer table. Members should see UK customers only, with email addresses replaced by REDACTED. The group must already exist. Use a fresh demo catalog; do not rerun the INSERT unless you want duplicate sample rows.</p><h3>1. Prepare Unity Catalog and compute</h3><p>Use a Unity Catalog workspace and supported compute. Databricks’ tutorial specifies Runtime 16.4+ or serverless; verify your compute access mode and operation-specific requirements before deployment.</p><p>You need creation privileges for the demo objects. Creating policies requires ownership or MANAGE on their scope and EXECUTE on the UDF. Assigning governed tags requires ASSIGN on the tag and APPLY TAG on the target object.</p><h3>2. Create governed tags</h3><p>In Catalog → Govern → Governed Tags → Create governed tag, define:</p><p>KeyAllowed valuesApplied toabac_demo_piiemailEmail columnabac_demo_fieldcountryCountry-code column</p><p>You need governed-tag CREATE permission. Check whether these keys already exist and reuse only if their meanings match. Creating an ordinary tag with SET TAGS alone is not equivalent to defining a governed tag.</p><h3>3. Create demo data</h3><pre>CREATE CATALOG IF NOT EXISTS abac_demo;<br>CREATE SCHEMA IF NOT EXISTS abac_demo.customer_data;<br>CREATE SCHEMA IF NOT EXISTS abac_demo.governance;</pre><pre>CREATE TABLE IF NOT EXISTS abac_demo.customer_data.customers (<br>  customer_id INT,<br>  country_code STRING,<br>  email STRING<br>) USING DELTA;</pre><pre>INSERT INTO abac_demo.customer_data.customers VALUES<br>  (1, &#39;GB&#39;, &#39;alice@example.com&#39;),<br>  (2, &#39;US&#39;, &#39;bob@example.com&#39;),<br>  (3, &#39;GB&#39;, &#39;carol@example.com&#39;),<br>  (4, NULL, &#39;dana@example.com&#39;);</pre><h3>4. Assign column tags</h3><pre>ALTER TABLE abac_demo.customer_data.customers<br>ALTER COLUMN email SET TAGS (&#39;abac_demo_pii&#39; = &#39;email&#39;);</pre><pre>ALTER TABLE abac_demo.customer_data.customers<br>ALTER COLUMN country_code SET TAGS (&#39;abac_demo_field&#39; = &#39;country&#39;);</pre><p>The tag value country describes the column&#39;s meaning. It is not the country value for each row. Tags identify the column; the function examines its actual row values.</p><h3>5. Define the functions</h3><pre>CREATE OR REPLACE FUNCTION abac_demo.governance.uk_only(c STRING)<br>RETURNS BOOLEAN<br>RETURN COALESCE(UPPER(TRIM(c)) = &#39;GB&#39;, FALSE);</pre><pre>CREATE OR REPLACE FUNCTION abac_demo.governance.redact_email(v STRING)<br>RETURNS STRING<br>RETURN CASE WHEN v IS NULL THEN NULL ELSE &#39;REDACTED&#39; END;</pre><p>The row function admits only GB and explicitly rejects NULL. The masking function replaces the result value, preserving NULL. It does not overwrite stored emails.</p><h3>6. Create the row policy</h3><pre>CREATE POLICY uk_customer_rows<br>ON SCHEMA abac_demo.customer_data<br>ROW FILTER abac_demo.governance.uk_only<br>TO `uk_analysts`<br>FOR TABLES<br>MATCH COLUMNS has_tag_value(&#39;abac_demo_field&#39;, &#39;country&#39;) AS country_col<br>USING COLUMNS (country_col);</pre><p>The policy discovers the country column from its tag and passes its values into the function. All members of this group are restricted; identities outside the group are not restricted by this particular policy.</p><h3>7. Create the masking policy</h3><pre>CREATE POLICY redact_customer_email<br>ON SCHEMA abac_demo.customer_data<br>COLUMN MASK abac_demo.governance.redact_email<br>TO `uk_analysts`<br>FOR TABLES<br>MATCH COLUMNS has_tag_value(&#39;abac_demo_pii&#39;, &#39;email&#39;) AS email_col<br>ON COLUMN email_col;</pre><p>The policy can find a matching column even when another table calls it contact_email. Compatible types and correct tags still matter.</p><h3>8. Grant normal query access</h3><p>Run as an authorized grantor:</p><pre>GRANT USE CATALOG ON CATALOG abac_demo TO `uk_analysts`;<br>GRANT USE SCHEMA ON SCHEMA abac_demo.customer_data TO `uk_analysts`;<br>GRANT SELECT ON TABLE abac_demo.customer_data.customers TO `uk_analysts`;</pre><p>Row-filter and column-mask policies do not themselves grant SELECT. UDF EXECUTE is required for the policy creator; these notes do not assume every querying user needs an explicit EXECUTE grant merely to query the protected table.</p><h3>9. Test as an actual group member</h3><pre>SELECT current_user();<br>SELECT customer_id, country_code, email<br>FROM abac_demo.customer_data.customers<br>ORDER BY customer_id;</pre><p>Expected result for a member of uk_analysts:</p><p>customer_idcountry_codeemail1GBREDACTED3GBREDACTED</p><p>The US and NULL-country rows are absent. This is an expected result, not output executed in your Databricks account.</p><h3>Query-time diagram</h3><pre>```mermaid<br>flowchart TD<br>  Q[Querying identity] --&gt; A{Has query privileges?}<br>  A --&gt;|No| D[Access denied]<br>  A --&gt;|Yes| P[Evaluate in-scope policies]<br>  T[Governed tags on columns] --&gt; P<br>  P --&gt; R[Apply matching row filter]<br>  R --&gt; M[Apply matching column mask]<br>  M --&gt; O[Return protected results]<br>```</pre><p>This is a conceptual sequence, not a claim about physical execution order.</p><h3>SQL clauses to remember</h3><p>ClauseMeaningON SCHEMA / ON CATALOGWhere the policy appliesTOPrincipals subject to the policyEXCEPTPrincipals excluded from this policyFOR TABLESTarget resource typeWHENOptional table-tag conditionMATCH COLUMNSFind columns using tag expressionsUSING COLUMNSSupply matched columns as function argumentsON COLUMNSelect the column being masked</p><h3>Validation and common mistakes</h3><ol><li>Test with a real restricted identity, a different identity with SELECT, and an identity without SELECT. An admin-only test is insufficient.</li><li>In a disposable test table, verify that missing tags do not silently leave data exposed. A tag-conditioned policy does not automatically protect untagged data.</li><li>Column tags do not inherit from their table. Apply them directly.</li><li>A policy exemption does not grant SELECT, and it does not cancel another applicable policy.</li><li>Multiple distinct row filters for the same user/table or masks for the same user/column can cause query failure; do not assume they combine as AND or OR.</li><li>Protect tag assignment/removal and UDF modification. These changes affect enforcement.</li><li>Add another correctly tagged demo table within the same schema to test reuse. Grant its SELECT separately if needed.</li><li>Test workload-specific support, including writes, clones, time travel and downstream copies. Protection on a source is not proof that every copied destination is protected.</li><li>Benchmark representative queries. Keep functions simple and deterministic where practical.</li></ol><h3>Interview answer</h3><p>“I use Unity Catalog governed tags to classify columns, then attach reusable policies at schema or catalog scope. Policies match the tags and apply SQL UDFs for row filtering and masking. I validate with different identities, control tag changes, and check untagged assets and policy conflicts.”</p><h3>Broader ABAC features</h3><p>Current documentation also describes GRANT policies for supported resource types and DENY policies in Beta. This guide concentrates on table row filtering and column masking; their semantics should not be confused with privilege-grant policies.</p><h3>Official references</h3><ul><li><a href="https://docs.databricks.com/aws/en/data-governance/unity-catalog/abac/core-concepts">https://docs.databricks.com/aws/en/data-governance/unity-catalog/abac/core-concepts</a></li><li><a href="https://docs.databricks.com/aws/en/data-governance/unity-catalog/abac/tutorial">https://docs.databricks.com/aws/en/data-governance/unity-catalog/abac/tutorial</a></li><li><a href="https://docs.databricks.com/aws/en/data-governance/unity-catalog/abac/tutorial-sql">https://docs.databricks.com/aws/en/data-governance/unity-catalog/abac/tutorial-sql</a></li><li><a href="https://docs.databricks.com/aws/en/data-governance/unity-catalog/abac/policies">https://docs.databricks.com/aws/en/data-governance/unity-catalog/abac/policies</a></li><li><a href="https://docs.databricks.com/aws/en/data-governance/unity-catalog/abac/limitations">https://docs.databricks.com/aws/en/data-governance/unity-catalog/abac/limitations</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d390132ec94" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS vs. Azure for Data Engineering: Glue/EMR vs. ADF/Synapse, Picked Apart]]></title>
            <link>https://medium.com/@manomita.dey/aws-vs-azure-for-data-engineering-glue-emr-vs-adf-synapse-picked-apart-b46fa36150ea?source=rss-1e9fba1aa067------2</link>
            <guid isPermaLink="false">https://medium.com/p/b46fa36150ea</guid>
            <dc:creator><![CDATA[Manomita Dey]]></dc:creator>
            <pubDate>Thu, 01 Oct 2026 21:39:28 GMT</pubDate>
            <atom:updated>2026-10-01T21:39:28.362Z</atom:updated>
            <content:encoded><![CDATA[<p>Every few months someone asks me the same question in a different costume: “Should we build our data platform on AWS or Azure?” It’s usually the wrong question. The right question is “what are we actually trying to do, and which cloud makes that less annoying?” Because once you’re past the marketing slides, AWS and Azure data engineering stacks solve the same problems with noticeably different philosophies — and those philosophies leak into every pipeline you write for years afterward.</p><p>I’ve shipped production pipelines on both. Neither is “better” in the abstract. But they are better at different things, and pretending otherwise just means you discover the gaps in production instead of in the design doc. Let’s get specific.</p><h3>The Core Matchup</h3><p>At a high level, the comparison usually collapses to four services:</p><ul><li><strong>AWS Glue</strong> (serverless Spark + a managed metastore/catalog) vs. <strong>Azure Data Factory</strong> (ADF, a managed orchestration and mapping-dataflow tool)</li><li><strong>AWS EMR</strong> (you-manage-more Spark/Hadoop clusters) vs. <strong>Azure Synapse Analytics</strong> (a unified analytics workspace bundling Spark pools, SQL pools, and pipelines)</li></ul><p>That pairing is a little unfair to both sides, because Glue and ADF aren’t quite peers, and neither are EMR and Synapse. Glue is a compute engine with orchestration bolted on; ADF is an orchestration engine with compute (mapping dataflows, or delegated Spark/Databricks) bolted on. EMR is raw clusters you tune yourself; Synapse is a platform trying to be your whole warehouse and lake at once. Keeping that distinction straight is half the battle when you’re evaluating either stack.</p><h3>AWS: Composable, Opinionated About Nothing</h3><p>AWS’s data engineering story is “here are primitives, go build.” Glue gives you serverless Spark jobs with a built-in Data Catalog that doubles as a Hive metastore for Athena, Redshift Spectrum, and EMR. EMR gives you full control over cluster sizing, bootstrap actions, and the exact Spark/Hadoop version you want. Step Functions or MWAA (managed Airflow) stitch it together. S3 is the lake. Nothing about this is integrated by default — you integrate it.</p><p>A typical Glue job looks like this:</p><pre>import sys<br>from awsglue.transforms import *<br>from awsglue.utils import getResolvedOptions<br>from awsglue.context import GlueContext<br>from awsglue.job import Job<br>from pyspark.context import SparkContext</pre><pre>args = getResolvedOptions(sys.argv, [&quot;JOB_NAME&quot;, &quot;source_path&quot;, &quot;target_path&quot;])<br>sc = SparkContext()<br>glueContext = GlueContext(sc)<br>spark = glueContext.spark_session<br>job = Job(glueContext)<br>job.init(args[&quot;JOB_NAME&quot;], args)</pre><pre>df = spark.read.format(&quot;parquet&quot;).load(args[&quot;source_path&quot;])</pre><pre>cleaned = (<br>    df.dropDuplicates([&quot;order_id&quot;])<br>      .filter(&quot;order_amount &gt; 0&quot;)<br>      .withColumn(&quot;ingest_date&quot;, spark.sql(&quot;select current_date()&quot;).collect()[0][0])<br>)</pre><pre>cleaned.write.mode(&quot;overwrite&quot;).partitionBy(&quot;ingest_date&quot;).parquet(args[&quot;target_path&quot;])</pre><pre>job.commit()</pre><p>That’s plain PySpark with a thin Glue wrapper. The upside: your Glue skills transfer almost 1:1 to EMR, Databricks, or open-source Spark — there’s no proprietary dialect to unlearn. The downside: Glue’s cold start (job startup latency, often 30–90 seconds even for trivial jobs) and its DPU-based pricing can make small, frequent jobs surprisingly expensive if you’re not batching work sensibly.</p><p>EMR, by contrast, gives up the “serverless” pretense entirely. You pick instance types, you tune spark.sql.shuffle.partitions, you decide whether to use EMR Serverless (a real option now, and worth defaulting to) or persistent/transient clusters. It&#39;s more work, but it&#39;s also where you go when Glue&#39;s opinions about environment and dependencies start fighting you — custom JARs, GPU instances, or Spark versions Glue hasn&#39;t caught up to yet.</p><h3>Azure: Integrated, Opinionated About Everything</h3><p>Azure Data Factory takes the opposite bet: minimize the code you write, maximize the drag-and-drop. Pipelines are JSON definitions of activities — copy data, run a mapping dataflow, call a stored procedure, trigger a Databricks notebook. For straightforward ELT (lift data from a SaaS source into a landing zone, then hand off to something smarter for transformation), ADF is genuinely fast to build in, and its native connector library (100+ sources) usually means you’re not writing a custom extractor at all.</p><p>A simple ADF pipeline definition — note how much of the logic is declarative rather than code:</p><pre>{<br>  &quot;name&quot;: &quot;IngestOrdersPipeline&quot;,<br>  &quot;properties&quot;: {<br>    &quot;activities&quot;: [<br>      {<br>        &quot;name&quot;: &quot;CopyOrdersToLake&quot;,<br>        &quot;type&quot;: &quot;Copy&quot;,<br>        &quot;inputs&quot;: [{ &quot;referenceName&quot;: &quot;SourceOrdersSql&quot;, &quot;type&quot;: &quot;DatasetReference&quot; }],<br>        &quot;outputs&quot;: [{ &quot;referenceName&quot;: &quot;SinkOrdersParquet&quot;, &quot;type&quot;: &quot;DatasetReference&quot; }],<br>        &quot;typeProperties&quot;: {<br>          &quot;source&quot;: { &quot;type&quot;: &quot;AzureSqlSource&quot; },<br>          &quot;sink&quot;: { &quot;type&quot;: &quot;ParquetSink&quot; }<br>        }<br>      },<br>      {<br>        &quot;name&quot;: &quot;RunCleaningDataflow&quot;,<br>        &quot;type&quot;: &quot;ExecuteDataFlow&quot;,<br>        &quot;dependsOn&quot;: [{ &quot;activity&quot;: &quot;CopyOrdersToLake&quot; }],<br>        &quot;typeProperties&quot;: { &quot;dataflow&quot;: { &quot;referenceName&quot;: &quot;CleanOrdersFlow&quot; } }<br>      }<br>    ]<br>  }<br>}</pre><p>The catch is that mapping dataflows compile down to Spark under the hood, but you’re a layer removed from it — debugging a slow dataflow means reasoning about a visual graph instead of a Spark UI, which is a real loss of visibility when things go sideways at 2 AM.</p><p>Synapse tries to collapse the lake/warehouse divide by giving you serverless SQL pools (query files in the lake directly), dedicated SQL pools (a provisioned MPP warehouse), and Spark pools, all inside one workspace with shared metadata via Synapse’s “lake database.” When it works, it’s genuinely convenient — one pane of glass, one billing surface, one security model. When it doesn’t, the seams show: dedicated SQL pools have their own scaling model (DWUs) that’s easy to over- or under-provision, and the “unified” workspace experience can feel like three products wearing a trenchcoat, because that’s close to what it is.</p><h3>A Concrete Case: Daily Batch Ingestion</h3><p>Say the job is: pull yesterday’s orders from a transactional source, dedupe, apply light cleansing, land it as curated Parquet, partitioned by date, ready for downstream dbt models.</p><p>On AWS, you’d likely wire: EventBridge (schedule) → Step Functions (orchestration) → Glue job (the PySpark above) → S3 (curated zone) → Glue Catalog (so Athena/dbt-on-Athena/Redshift Spectrum can see it immediately. Every piece is a separate, inspectable AWS resource, which is great for granular IAM but means more Terraform.</p><p>On Azure, you’d wire: ADF trigger (schedule) → Copy activity (source → landing) → Mapping Dataflow or Synapse Spark notebook (cleansing) → ADLS Gen2 (curated zone) → Synapse serverless SQL view or lake database (so downstream consumers can query it). Fewer distinct service boundaries, more of the logic living inside ADF’s own JSON/visual authoring surface.</p><p>Functionally equivalent. Operationally, the AWS version is more composable and more portable (less lock-in to any one orchestrator); the Azure version ships faster if your team is already fluent in the Microsoft ecosystem, especially if Power BI is the eventual consumption layer — the ADLS-to-Synapse-to-Power BI path is noticeably less friction than wiring Redshift or Athena into BI tooling that wasn’t built with AWS in mind.</p><h3>Where This Actually Tips the Decision</h3><p>Ignore the services for a second and ask three questions instead:</p><p><strong>Where does your data already live?</strong> If you’re already deep in Microsoft 365, Dynamics, or on-prem SQL Server with existing Azure AD identity, ADF’s connector-first model and Azure’s identity integration save real time. If you’re AWS-native with data already in S3 and services talking to each other via IAM roles, Glue/EMR is the path of least resistance.</p><p><strong>How much do you want to own vs. delegate?</strong> AWS wants you to assemble; Azure wants you to configure. If your team has strong Spark/infra chops and wants control over every knob, AWS rewards that. If you want a smaller team shipping pipelines without deep Spark tuning knowledge, Synapse/ADF’s guardrails are a feature, not a limitation.</p><p><strong>What’s downstream?</strong> Heavy BI-on-Power-BI shops lean Azure. Heavy custom-application or ML-platform shops with existing AWS footprints (SageMaker, Bedrock) lean AWS. Don’t let the ingestion layer decide this in isolation from where the data ends up being consumed.</p><h3>The Honest Takeaway</h3><p>Neither stack is a bad choice, and “just pick the one your org already pays for” is underrated advice — multi-cloud data platforms are expensive in ways that rarely show up in the initial architecture diagram. What I’d push back on is choosing based on which console looks friendlier in a demo. Glue and EMR will ask more of your engineers up front and pay it back in portability and control. ADF and Synapse will ask less up front and quietly expect you to live inside their abstractions for the life of the platform. Know which trade you’re making before you make it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b46fa36150ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Snowflake Performance Tuning: Micro-Partitions, Clustering, and Dynamic Tables]]></title>
            <link>https://medium.com/@manomita.dey/snowflake-performance-tuning-micro-partitions-clustering-and-dynamic-tables-b5e63635c195?source=rss-1e9fba1aa067------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5e63635c195</guid>
            <dc:creator><![CDATA[Manomita Dey]]></dc:creator>
            <pubDate>Mon, 28 Sep 2026 23:05:52 GMT</pubDate>
            <atom:updated>2026-09-28T23:05:52.606Z</atom:updated>
            <content:encoded><![CDATA[<h3>Your query is scanning ten times more data than it needs to, and Snowflake will never tell you</h3><p>Here’s the uncomfortable truth about Snowflake performance: the platform is so good at hiding complexity that most teams never learn how storage actually works underneath it, right up until a query that used to run in eight seconds is taking ninety and nobody can explain why. There’s no EXPLAIN ANALYZE moment that screams &quot;your clustering is wrong.&quot; There&#39;s just a warehouse that quietly gets bigger, a credit bill that quietly climbs, and an engineer quietly assuming the answer is &quot;throw an XL at it.&quot;</p><p>Sometimes that is the answer. Usually it isn’t. Snowflake performance problems are, more often than not, storage-layout problems wearing a compute costume. If you understand micro-partitions and how pruning actually works, you can fix most slow queries without touching warehouse size at all. And if you’re still writing nightly INSERT OVERWRITE jobs to keep a summary table fresh, Dynamic Tables will make you feel like you&#39;ve been doing extra work for no reason — because you have.</p><p>This post covers the three things that matter most for real-world Snowflake performance: how micro-partitions and pruning actually work, when clustering keys earn their cost, and how Dynamic Tables change the incremental-refresh conversation entirely.</p><h3>Micro-partitions: the thing everyone assumes they understand</h3><p>Snowflake automatically slices every table into micro-partitions — contiguous units of storage, typically 50–500MB of uncompressed data each, stored in a columnar format. Every micro-partition carries metadata: min/max values for every column, distinct counts, and null counts. That metadata lives in the cloud services layer, and it’s the entire reason Snowflake can be fast without you managing indexes.</p><p>When you run a query with a filter, Snowflake doesn’t scan every micro-partition. It checks the metadata first and skips any partition whose min/max range can’t possibly contain a match. This is called <strong>pruning</strong>, and it’s the single biggest lever on your query cost and latency. A query that prunes 95% of partitions and a query that prunes 5% can differ by two orders of magnitude in execution time, on the exact same warehouse size.</p><p>The catch: pruning only works well when the data is naturally or deliberately <strong>clustered</strong> — meaning rows with similar values in your filter columns tend to land in the same micro-partitions. Data loaded in arrival order is naturally clustered on load time or an auto-incrementing ID. If your queries filter on load time, great, pruning works for free. If your queries filter on customer_id or region and your data isn&#39;t loaded in that order, every micro-partition might contain a little bit of everything — and pruning does nothing.</p><p>You can check this yourself:</p><pre>SELECT *<br>FROM TABLE(INFORMATION_SCHEMA.CLUSTERING_INFORMATION(<br>  &#39;analytics.fct_orders&#39;,<br>  &#39;(customer_region, order_date)&#39;<br>));</pre><p>Look at average_depth. A low number (close to 1) means partitions are well-organized around those columns — a query filtering on them will prune aggressively. A high number means the values are scattered across many partitions, and every query touching that column is scanning far more than it should.</p><h3>Clustering keys: powerful, and easy to misuse</h3><p>A clustering key tells Snowflake to actively reorganize a table’s micro-partitions so rows with similar key values sit together. This sounds like something you should do to every large table. It is not.</p><p>Clustering has a real, ongoing cost. Snowflake runs automatic background reclustering whenever a clustered table’s organization degrades past a threshold, and that reclustering consumes credits — separate from your warehouse compute, billed under “Automatic Clustering.” For a table that’s append-only and rarely updated, this cost is modest. For a table with constant backfills, late-arriving updates, or streaming upserts, reclustering can run continuously and quietly become one of your largest line items.</p><p>The rule I actually use: only cluster a table when all three of these are true — it’s large enough that pruning meaningfully matters (rule of thumb, above a few hundred GB, since smaller tables are fast regardless of layout), queries consistently filter on the same one or two columns, and the natural insert order doesn’t already align with those filters.</p><pre>ALTER TABLE analytics.fct_orders<br>CLUSTER BY (customer_region, order_date);</pre><p>Pick clustering keys with <strong>low-to-medium cardinality first</strong>, then higher cardinality — (region, order_date) works better than (order_id, region) because it groups broad buckets before narrow ones, which is exactly how the underlying partition pruning wants to eliminate data.</p><p>A pattern I’d actively discourage: clustering a table just because a single slow dashboard query filters on some column once a day. Check whether a <strong>materialized view</strong> or a properly scoped <strong>search optimization</strong> on that column solves it more cheaply first. Clustering is for tables that are foundational to many queries, not a patch for one report.</p><h3>Dynamic Tables: the end of hand-rolled incremental logic</h3><p>This is the part of modern Snowflake that most teams are still underusing. Before Dynamic Tables, keeping a derived table fresh meant one of two bad options: a full CREATE OR REPLACE TABLE AS SELECT that reprocesses everything every time, or a hand-built incremental MERGE with watermark tracking, late-arriving-data logic, and a Task to schedule it — all of which someone has to write, test, and maintain.</p><p>Dynamic Tables let you declare the end state and a target freshness, and Snowflake figures out the incremental refresh plan itself:</p><pre>CREATE OR REPLACE DYNAMIC TABLE analytics.customer_daily_summary<br>TARGET_LAG = &#39;15 minutes&#39;<br>WAREHOUSE = transform_wh<br>AS<br>SELECT<br>    customer_id,<br>    DATE_TRUNC(&#39;day&#39;, order_ts) AS order_date,<br>    COUNT(*) AS order_count,<br>    SUM(order_amount) AS total_amount,<br>    SUM(order_amount) / COUNT(*) AS avg_order_value<br>FROM analytics.stg_orders<br>GROUP BY 1, 2;</pre><p>TARGET_LAG is the interesting knob. Snowflake tracks the freshness of upstream tables and automatically schedules refreshes to hit your target — including chaining across multiple Dynamic Tables, where it computes a global refresh graph rather than treating each one as an isolated cron job. Set it to DOWNSTREAM on an intermediate table and it inherits the tightest lag requirement of whatever consumes it, so you&#39;re not guessing at schedules by hand.</p><p>This matters for dbt shops specifically. A lot of teams reach for dbt’s incremental materialization with a manually maintained is_incremental() block, unique keys, and merge strategy — and that&#39;s still the right call for complex transformation logic with real business rules. But for straightforward rollups and aggregations sitting between raw and mart layers, Dynamic Tables replace both the SQL logic and the orchestration in one object, and they refresh incrementally by default rather than requiring you to opt into it correctly.</p><p>The honest tradeoff: Dynamic Tables are still less flexible than a full dbt model for complex multi-source logic with heavy business rules, and debugging a refresh graph across many chained Dynamic Tables is a newer muscle than debugging a dbt DAG with lineage graphs and tests you already know how to write. Use them where the transformation is genuinely simple and freshness matters — not as a wholesale replacement for your transformation layer.</p><h3>A worked example: fixing a slow dashboard query</h3><p>Say a fct_orders table is 2TB, loaded continuously via Snowpipe, and a dashboard filtering on customer_region and a rolling 30-day order_date window takes 40 seconds on a Medium warehouse. First step isn&#39;t resizing the warehouse — it&#39;s checking clustering depth on those two columns. If depth is high (say, 40+), the query is scanning most of the table&#39;s micro-partitions regardless of the 30-day filter, because region values are scattered evenly across load time.</p><p>Adding CLUSTER BY (customer_region, order_date) and letting automatic reclustering catch up (monitor via AUTOMATIC_CLUSTERING_HISTORY) typically drops that same query to low single-digit seconds on the same warehouse size, because pruning is now doing real work. If the dashboard also depends on a daily rollup instead of querying the fact table directly, converting that rollup to a Dynamic Table with a sensible TARGET_LAG removes both the manual refresh Task and the risk of the rollup silently going stale.</p><h3>The takeaway</h3><p>Before you resize a warehouse, check your clustering depth. Before you build another incremental MERGE, check whether a Dynamic Table can do it declaratively. Snowflake’s compute layer gets the attention because it’s the line item on the bill, but the storage layer is where most of the actual performance problems — and most of the actual fixes — live.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5e63635c195" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PySpark Performance Tuning: Catalyst, AQE, Shuffles, and Broadcast Joins]]></title>
            <link>https://medium.com/@manomita.dey/pyspark-performance-tuning-catalyst-aqe-shuffles-and-broadcast-joins-b3f7ac3579da?source=rss-1e9fba1aa067------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3f7ac3579da</guid>
            <dc:creator><![CDATA[Manomita Dey]]></dc:creator>
            <pubDate>Mon, 21 Sep 2026 22:59:01 GMT</pubDate>
            <atom:updated>2026-09-21T22:59:01.502Z</atom:updated>
            <content:encoded><![CDATA[<p>All PySpark jobs that “just work” in dev and fall apart at scale share a similar origin story: someone wrote correct code and never looked at the plan. The transformation logic was fine. The join keys were fine. What broke it? A shuffle that was never considered. A broadcast that never happened. Or perhaps a skewed partition quietly doing 40x the work of its peers, while eleven executors were sitting idle.</p><p>Performance tuning in Spark is not about writing “faster code” — the API is declarative, so there is nothing in your control. It is about understanding what happens between your DataFrame calls and a cluster: the Catalyst optimizer, its physical plan, and the runtime adjustments Adaptive Query Execution makes once the actual data is involved. Learn how to read explain() output and guesswork goes away.</p><p>What happens behind the scenes in .join()</p><p>Calling a DataFrame operation does not execute anything. A logical plan is built — a tree of relational operations (filters, projects, joins, aggregates), with no execution strategy yet attached. Then Catalyst executes a pipeline of rule-based and cost-based transformations:</p><p>Analysis — resolves column references and types against the catalog.<br>Logical optimization — predicate pushdown, constant folding, column pruning, redundant filter elimination.<br>Physical planning — generates multiple physical plans (for example, broadcast hash join or sort-merge join) and selects one based on cost estimates.<br>Code generation — Spark compiles the selected plan down to JVM bytecode via whole-stage codegen. This is why your hand-written loops in Python UDFs are unlikely to beat native DataFrame operations.</p><p>You can observe this process directly:</p><p>python<br>df_joined = fact_orders.join(dim_customers, “customer_id”)<br>df_joined.explain(mode=”formatted”)</p><p>Start reading physical plan from the bottom. Exchange nodes are shuffles — this is almost always the biggest performance cost in your queries. Also check BroadcastHashJoin vs. SortMergeJoin — this indicates which strategy Spark selected for your join: whether it was able to broadcast one of the sides.</p><p>Shuffles: the unavoidable tax of correctness</p><p>A shuffle happens every time your data has to be sorted by key and redistributed across partitions. This includes joins on non-broadcast tables, groupBy, distinct, repartition. It means writing intermediate data to disk, sending it across the network, and loading back in the final step. It is impossible to avoid shuffles in large-to-large joins and wide aggregations. The goal is to minimize how much data you are shuffling, and how often.</p><p>Common shuffle killers:</p><p>Joining before filtering. Apply filters as early as possible, to reduce data volume entering the shuffle. Spark does this automatically in some cases via predicate pushdown, but it cannot push a filter past a UDF or any other non-deterministic function.<br>Excessive repartitioning. repartition(n) forces a full shuffle. Do it only when you have a specific reason (e.g., fixing a downstream skew or controlling output file counts before writing).<br>Wide groupBys with high-cardinality keys. Use partial aggregation strategies and consider pre-aggregating data upstream in dbt/SQL.</p><p>Spill in the Spark UI (Shuffle spill (memory) / Shuffle spill (disk)) indicates that partitions became too large for executor memory, and they are being spilled to disk during the shuffle. The fix is in increasing spark.sql.shuffle.partitions, fixing skew or executor memory allocation — in this order of costs.</p><p>Adaptive Query Execution: giving Spark a chance to optimize itself</p><p>AQE (enabled by default in Spark 3.2) is a mechanism that reoptimizes the physical plan during the query execution. Instead of static cost estimates used by Catalyst, it uses actual runtime statistics collected along the way. The following features are especially important in practice:</p><p>Coalescing shuffle partitions. No need to guess a proper value for spark.sql.shuffle.partitions (the default of 200 is almost never correct). AQE uses post-shuffle partition size information to merge small partitions and reduce the number of very small tasks.</p><p>Switching between join strategies dynamically. In case if Catalyst’s cost estimate says that a particular table is too big to broadcast, but after the filter the actual table size became small enough, AQE switches the sort-merge join to the broadcast hash join.</p><p>Skew join handling. This is the one worth remembering by heart. AQE can detect that some partition in sort-merge join became drastically bigger than the others (a customer_id of NULL holding 30% of your fact table, for example) and split this oversized partition into smaller pieces, performing the join against each of them and unioning the results. Otherwise, you get one straggler task that takes disproportionately long to complete compared to all other tasks, making the overall job slow even though most executors are done in seconds.</p><p>Turn it on explicitly if you’re running an older version of Spark, and tune the skew thresholds if defaults don’t fit your data:</p><p>python<br>spark.conf.set(“spark.sql.adaptive.enabled”, “true”)<br>spark.conf.set(“spark.sql.adaptive.skewJoin.enabled”, “true”)<br>spark.conf.set(“spark.sql.adaptive.skewJoin.skewedPartitionFactor”, “5”)<br>spark.conf.set(“spark.sql.adaptive.skewJoin.skewedPartitionThresholdInBytes”, “256MB”)<br>Broadcast joins: the fastest join you’re probably not using enough</p><p>In case if one side of the join is small enough to fit in executor memory, Spark can save the shuffle cost by sending the copy of this table to every executor. Each partition of the large table joins locally with this copy — the large table is not being shuffled anymore.</p><p>The default broadcast threshold is set to 10MB, which is quite conservative for most modern clusters:</p><p>python<br>spark.conf.set(“spark.sql.autoBroadcastJoinThreshold”, “100MB”)</p><p>You can also force the broadcast explicitly rather than rely on the size estimate made by the optimizer, which can be wrong after some complex transformations upstream:</p><p>python<br>from pyspark.sql.functions import broadcast</p><p>result = fact_orders.join(broadcast(dim_customers), “customer_id”)</p><p>Example: joining a 400-million-row order fact table with a 50-thousand-row customer dimension. Even in case if you leave the join to a default one, Catalyst might select a sort-merge strategy if its size estimate for the dimension table was wrong (very common after several transformations due to degraded cardinality estimates). Explicitly forcing the broadcast converts two expensive shuffles into a single-sided broadcast join and a local join — resulting in a 5–10x wall-clock performance boost in such typical fact-to-dimension scenario.</p><p>Failure modes of broadcast joins are the following: broadcasting a table that appears to be bigger than you expected (executor OOM or BroadcastTimeout exception if the driver-side collect takes too long), and broadcasting a table inside a loop or repeated join, when Spark rebuilds and re-sends the broadcast variable every time. Check the actual size in Spark UI -&gt; SQL tab, not just the row count, because a “small” table with a wide array or map column can be significantly bigger in bytes than you expect.</p><p>How it all fits together: a diagnostic checklist</p><p>When a job is slow, start from analyzing the plan before changing the cluster configuration:</p><p>python<br>df.explain(mode=”formatted”) # look for Exchange nodes and join strategy<br># Spark UI → SQL tab → check actual rows/bytes per stage vs. estimated<br># Spark UI → Stages tab → check for task duration skew (max vs. median)</p><p>Sort-merge join, where one side is small? Force a broadcast. Shuffle spill? Increase partitions or fix skew, not the executor memory. One task that is 10x slower than others? It’s skew again, and AQE skew join handling should be your first choice before resorting to manual salting techniques. None of that explains slowness? Consider Python UDFs — they prevent whole-stage codegen and make Spark serialize and deserialize data between JVM and Python, which is quite likely to be the actual bottleneck.</p><p>None of this is a substitute to good data modeling upstream — a well-partitioned Delta table with reasonable file sizes will improve all of these techniques. But once the storage layer is good, the plan becomes the core of performance tuning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3f7ac3579da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Palantir Foundry for Data Engineers: Ontology, Transforms, and AIP Without the Mystique]]></title>
            <link>https://medium.com/@manomita.dey/palantir-foundry-for-data-engineers-ontology-transforms-and-aip-without-the-mystique-8955bc6a06de?source=rss-1e9fba1aa067------2</link>
            <guid isPermaLink="false">https://medium.com/p/8955bc6a06de</guid>
            <dc:creator><![CDATA[Manomita Dey]]></dc:creator>
            <pubDate>Wed, 16 Sep 2026 23:01:09 GMT</pubDate>
            <atom:updated>2026-09-16T23:01:09.478Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve spent your career in Snowflake, dbt, and Databricks, your first week in Palantir Foundry will feel like landing in a country where everyone drives on the other side of the road. The traffic laws still make sense once you learn them — but nothing about the layout matches what you’re used to, and the marketing material doesn’t help. Foundry gets described in vague, almost mystical terms (“the ontology,” “operational AI,” “decision velocity”) that tell you nothing about what you’ll actually be doing on a Tuesday afternoon: writing transforms, debugging a build graph, and arguing about whether a column belongs on an object type or a link.</p><p>This post is the practical orientation I wish I’d had: what Foundry actually is architecturally, how its transform layer compares to what you already know, what the ontology is really for, and where AIP fits into a normal data engineering workflow.</p><h3>Foundry Is a Platform, Not a Warehouse</h3><p>The first mental shift: Foundry isn’t a data warehouse with a nice UI bolted on. It’s closer to a unified platform that bundles ingestion, a Spark-based transformation engine, a catalog, a semantic layer (the ontology), and an application layer, all wired together with strict lineage tracking. Underneath the transform layer, it’s Spark — which means if you know PySpark, you already know most of the syntax you need. What’s different is everything around it: how datasets are versioned, how pipelines are built and scheduled, and how outputs get exposed to end users.</p><p>Think of the rough equivalent mapping if you’re coming from the modern data stack:</p><ul><li>Raw ingestion ≈ Fivetran/Airbyte, but built into the platform as “sync” jobs</li><li>Transform layer ≈ dbt + Spark combined, but authored in actual Python/PySpark or SQL, not templated SQL alone</li><li>Dataset catalog ≈ a beefed-up version of a dbt docs site with full column-level lineage baked in by default</li><li>Ontology ≈ nothing you have in the modern data stack — this is the genuinely novel piece</li><li>AIP ≈ LLM tooling wired directly into the ontology and transforms, not a bolt-on chatbot</li></ul><h3>Writing Transforms: Familiar Syntax, Different Contract</h3><p>A basic Foundry transform looks almost like a PySpark job with decorators on top:</p><pre>from transforms.api import transform, Input, Output<br>from pyspark.sql import functions as F</pre><pre>@transform(<br>    output=Output(&quot;/project/datasets/orders_cleaned&quot;),<br>    orders=Input(&quot;/project/datasets/orders_raw&quot;),<br>)<br>def compute(orders, output):<br>    df = orders.dataframe()<br>    cleaned = (<br>        df.filter(F.col(&quot;order_status&quot;).isNotNull())<br>        .withColumn(&quot;order_amount&quot;, F.col(&quot;order_amount&quot;).cast(&quot;double&quot;))<br>        .withColumn(&quot;order_date&quot;, F.to_date(&quot;order_timestamp&quot;))<br>        .dropDuplicates([&quot;order_id&quot;])<br>    )<br>    output.write_dataframe(cleaned)</pre><p>If you’ve written a dbt model or a Databricks notebook job, none of this syntax surprises you. The Input/Output decorators are doing something dbt&#39;s ref() does implicitly: declaring the dependency graph explicitly, in code, so the platform can build the DAG without you writing any orchestration YAML.</p><p>The contract that’s different from dbt is incrementality. In dbt you reach for incremental models and manage merge logic yourself with is_incremental() blocks. In Foundry, incremental transforms are a first-class primitive:</p><pre>from transforms.api import transform, Input, Output, incremental</pre><pre>@incremental()<br>@transform(<br>    output=Output(&quot;/project/datasets/orders_incremental&quot;),<br>    orders=Input(&quot;/project/datasets/orders_raw&quot;),<br>)<br>def compute(orders, output):<br>    new_rows = orders.dataframe(&quot;added&quot;)<br>    output.write_dataframe(new_rows)</pre><p>The platform tracks which rows are new, deleted, or modified between builds, and hands you the delta directly. It’s a genuinely nice abstraction once you trust it — the catch is that trusting it requires understanding how Foundry’s build system reasons about dataset transactions, which takes longer to internalize than a SQL merge statement does.</p><h3>The Build Graph Is the Real Unit of Work</h3><p>In dbt, your unit of work is a model; in Databricks, a notebook or job. In Foundry, it’s the build — a materialization of one or more datasets in the dependency graph, with every build producing an immutable transaction. This matters practically in two ways.</p><p>First, debugging is lineage-first. When a downstream dataset looks wrong, you don’t grep through logs — you click backward through the dataset graph, inspect the transaction history of each upstream dataset, and diff schemas between transactions. It’s slower to learn than dbt run --select +my_model but arguably more rigorous once you&#39;re fluent, because every dataset&#39;s full history is queryable, not just its current state.</p><p>Second, builds are expensive to trigger carelessly. Foundry’s scheduler will happily rebuild everything downstream of a change if you don’t scope your build correctly, and on a large ontology-backed pipeline that can mean cascading Spark jobs across dozens of datasets. The equivalent mistake in dbt is running dbt run with no selector on a 500-model project — annoying, but rarely as compute-expensive as an unscoped Foundry rebuild touching operational objects that downstream applications are actively reading from.</p><h3>The Ontology: The Part That Isn’t Just Rebranded dbt</h3><p>Here’s the concept that actually is new if you’re coming from Snowflake or Databricks: the ontology layer sits on top of your transformed datasets and turns rows into typed, semantic objects with defined properties, links, and actions.</p><p>Concretely: you might have a orders_cleaned dataset with columns like order_id, customer_id, order_amount. In the ontology, you define an Order object type, map order_id to its primary key, map columns to typed properties, and define a link type connecting Order to a Customer object type via customer_id. Once that mapping exists, every downstream consumer — a dashboard, an operational app, an AIP agent — interacts with &quot;orders that link to a customer&quot; as a first-class concept, not as a join you have to remember to write correctly every time.</p><p>The dbt-world analogy is a semantic layer (think dbt’s own semantic layer, or a metrics layer like Cube), but the ontology goes further: it supports <em>actions</em>, which are write-back operations with validation logic, not just read-only metric definitions. An action might let an operational user flag an order as disputed, and that action can trigger a transform, write to an audit dataset, and update the object’s state — all with permissions and validation enforced at the ontology layer.</p><p>For a data engineer, the practical implication is that your transform pipelines aren’t the end of the line the way they are in a warehouse — they’re feeding a semantic model that other people build applications on top of. That raises the bar on schema stability and naming discipline considerably, because a column rename in your transform can break an object type mapping that three different operational apps depend on.</p><h3>Where AIP Actually Fits</h3><p>AIP (Foundry’s AI platform layer) gets marketed heavily, but the useful part for a data engineer is narrow and concrete: AIP agents and logic functions can read and act on ontology objects directly, with the same permissioning and lineage guarantees as everything else in the platform. That means an LLM-backed agent answering “which orders are at risk of delay” isn’t hitting a vector database of unstructured dump text — it’s querying typed Order objects with real properties and real links, which drastically reduces the hallucination surface compared to a naive RAG-over-documents setup.</p><p>Practically, if you’re building for AIP, your job as the data engineer is upstream and unglamorous: make sure the ontology objects your agents will query are well-modeled, properly typed, and freshly built. A poorly maintained ontology makes AIP worse in the same way a poorly maintained dbt project makes a BI dashboard worse — garbage in, garbage out, just with a chat interface on top now.</p><h3>The Takeaway</h3><p>Foundry rewards data engineers who already think in DAGs and lineage — the Spark and dependency-graph instincts from PySpark and dbt transfer almost directly. What doesn’t transfer is the ontology mindset: treating your transformed data not as a table to be queried, but as a semantic object to be modeled, linked, and acted upon. If you’re evaluating Foundry for a team already comfortable with Databricks and dbt, the real onboarding cost isn’t the transform syntax — it’s learning to think one layer higher than the table.</p><p>Next week we’re going back to core PySpark territory: cracking open the Catalyst optimizer and Adaptive Query Execution to understand why two logically identical Spark jobs can have wildly different runtimes — and what you can actually control about it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8955bc6a06de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Production-Grade SCD2 Pipelines with PySpark on Databricks]]></title>
            <link>https://medium.com/@manomita.dey/building-production-grade-scd2-pipelines-with-pyspark-on-databricks-3c11db9c83e2?source=rss-1e9fba1aa067------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c11db9c83e2</guid>
            <dc:creator><![CDATA[Manomita Dey]]></dc:creator>
            <pubDate>Fri, 28 Aug 2026 11:24:49 GMT</pubDate>
            <atom:updated>2026-08-28T11:24:49.550Z</atom:updated>
            <content:encoded><![CDATA[<p>Every data engineer eventually hits the same wall: the business doesn’t just want to know what a customer’s address is <em>today</em> — they want to know what it was on the day an order shipped, a claim was filed, or a contract was signed. That’s the moment “just overwrite the row” stops being an option, and Slowly Changing Dimension Type 2 (SCD2) becomes a requirement instead of a nice-to-have.</p><p>SCD2 sounds like a solved problem — plenty of tutorials show you a toy MERGE statement and call it done. In production, on real data volumes, with real late-arriving records and real schema drift, it’s a different beast. Here’s how to build it properly on Databricks with PySpark and Delta Lake, and where most implementations quietly break.</p><h3>Why “just overwrite it” fails</h3><p>Picture a customers dimension feeding a claims-analytics warehouse. If you overwrite on every load, a customer’s plan tier changes, and suddenly every historical claim looks like it was filed under the <em>new</em> tier. Your trend lines lie. Your finance team’s reconciliation breaks. And nobody notices until an audit asks “why does this number not match last quarter’s report.”</p><p>SCD2 solves this by never overwriting — it closes out the old version of a row and inserts a new one, each tagged with a validity window:</p><p>customer_id | plan_tier | eff_start_date | eff_end_date | is_current</p><p>C-1001 | Silver | 2024–01–01 | 2025–06–14 | false</p><p>C-1001 | Gold | 2025–06–15 | 9999–12–31 | true</p><p>Now every downstream join can ask “what did this record look like as of date X” and get the historically correct answer.</p><h3>The medallion context</h3><p>In a medallion architecture, SCD2 belongs squarely in the <strong>silver layer</strong>. Bronze is the raw, append-only capture of source events (CDC feeds, Kafka topics, batch extracts). Silver is where you apply business keys, deduplicate, and build the conformed dimension with full history. Gold then reads only the is_current = true slice — or, when a report genuinely needs point-in-time correctness, joins on the validity window directly.</p><p>Keeping that boundary clean matters: if you let gold-layer consumers merge SCD2 logic themselves, you’ll end up with five slightly different interpretations of “current” across five dashboards.</p><h3>The core merge pattern</h3><p>Delta Lake’s MERGE INTO is built for exactly this. The pattern has three branches: close out changed records, insert new versions of those records, and insert brand-new business keys.</p><p>from pyspark.sql import functions as F</p><p>from delta.tables import DeltaTable</p><p>def scd2_merge(spark, source_df, target_table, business_key, tracked_cols):</p><p>target = DeltaTable.forName(spark, target_table)</p><p># 1. Build a change hash so we only touch rows that actually changed</p><p>source = source_df.withColumn(</p><p>“row_hash”, F.sha2(F.concat_ws(“||”, *tracked_cols), 256)</p><p>)</p><p># 2. Identify which current records changed</p><p>staged = (</p><p>source.alias(“s”)</p><p>.join(</p><p>target.toDF().filter(“is_current = true”).alias(“t”),</p><p>on=business_key,</p><p>how=”left”,</p><p>)</p><p>.withColumn(</p><p>“action”,</p><p>F.when(F.col(“t.” + business_key) .isNull(), “insert”)</p><p>.when(F.col(“s.row_hash”) != F.col(“t.row_hash”), “update”)</p><p>.otherwise(“noop”),</p><p>)</p><p>)</p><p>changed = staged.filter(“action != ‘noop’”)</p><p># 3. Close out the old current row for anything that changed</p><p>(</p><p>target.alias(“t”)</p><p>.merge(</p><p>changed.filter(“action = ‘update’”).alias(“s”),</p><p>f”t.{business_key} = s.{business_key} AND t.is_current = true”,</p><p>)</p><p>.whenMatchedUpdate(</p><p>set={</p><p>“is_current”: “false”,</p><p>“eff_end_date”: “s.eff_start_date”,</p><p>}</p><p>)</p><p>.execute()</p><p>)</p><p># 4. Insert new current versions + brand-new keys</p><p>to_insert = changed.filter(“action in (‘update’, ‘insert’)”)</p><p>to_insert.write.format(“delta”).mode(“append”).saveAsTable(target_table)</p><p>The two-pass structure (close, then insert) is deliberate — Delta’s MERGE can’t simultaneously update a matched row <em>and</em> insert a new version of the same key in one statement, so trying to be clever and do it in a single merge is where most homegrown implementations go wrong.</p><h3>Where it actually breaks in production</h3><p><strong>Change detection on the wrong columns.</strong> Hashing the entire row means a metadata column (like a source-system updated_at timestamp) that changes on every load will make <em>every</em> row look “changed,” destroying your history with noise. Hash only the business-meaningful tracked columns, and keep technical metadata out of that hash.</p><p><strong>Late-arriving and out-of-order data.</strong> If your source system can deliver a June 10th change after you’ve already processed June 15th, a naive “always close on ingestion order” approach corrupts your validity windows. You need eff_start_date driven by the source event’s business timestamp, not the pipeline’s run time — and a reconciliation job that can re-sequence a dimension’s history when a late record arrives.</p><p><strong>Concurrent writers.</strong> Two pipeline runs (a backfill and a scheduled job) hitting the same Delta table’s MERGE at once will conflict. Delta’s optimistic concurrency control will throw a ConcurrentAppendException — plan for retry logic, or better, serialize writes to a given dimension table through a single job.</p><p><strong>Unbounded history growth.</strong> SCD2 tables grow forever by design. Without partitioning on a coarse-grained column (like eff_start_year) and periodic OPTIMIZE + ZORDER BY (business_key), point-in-time queries against a multi-year dimension will scan far more data than they need to.</p><h3>Testing the merge logic, not just the pipeline</h3><p>The failure mode that costs the most time in code review is a merge that “runs successfully” but silently produces two is_current = true rows for the same business key — usually from a race between the close-out and insert steps, or a business key that isn’t actually unique in source. A minimal test suite should assert, after every merge: exactly one current row per business key, no overlapping validity windows, and no gaps in the timeline for keys with tracked-column changes. These are cheap groupBy/count assertions and they catch the bugs that a “the job finished” green check will never surface.</p><h3>The takeaway</h3><p>SCD2 isn’t a SQL pattern you memorize once — it’s a set of tradeoffs around change detection, ordering, and concurrency that only show up under real production load. Get the hash-based change detection right, keep bronze/silver/gold boundaries clean, and write tests that check invariants rather than just “did the job exit zero.” Do that, and your dimension tables become something the business can actually trust for historical reporting — which is the entire point of building them this way in the first place.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c11db9c83e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Azure Data Factory Control Flow Activities Guide]]></title>
            <link>https://medium.com/@manomita.dey/azure-data-factory-control-flow-activities-guide-69f632327139?source=rss-1e9fba1aa067------2</link>
            <guid isPermaLink="false">https://medium.com/p/69f632327139</guid>
            <dc:creator><![CDATA[Manomita Dey]]></dc:creator>
            <pubDate>Thu, 13 Aug 2026 11:07:45 GMT</pubDate>
            <atom:updated>2026-08-13T11:07:45.697Z</atom:updated>
            <content:encoded><![CDATA[<h3>Azure Blob Storage → Snowflake Pipeline</h3><h3>1. VALIDATION ACTIVITY</h3><p>Purpose: Validate that a dataset/container exists before proceeding.</p><h3>Use Case: Check if Azure Blob container has data</h3><pre>Validation Activity Config:<br>├── Dataset: blob_raw_container<br>├── Validation Type: &quot;Dataset must exist&quot;<br>├── Min records: 0 (or set minimum)<br>└── Timeout: 10 seconds</pre><h3>Flow in Your Pipeline</h3><pre>Start<br>  ↓<br>[Validation] Check if raw container exists<br>  ├─ Success → Continue to Get Metadata<br>  └─ Failure → Fail Activity (alert)</pre><h3>Example: Validate multiple containers</h3><pre>- Validation 1: Check raw/customers/ exists<br>- Validation 2: Check raw/products/ exists<br>- If both pass → Proceed to ingestion<br>- If either fails → Trigger alert</pre><h3>2. GET METADATA ACTIVITY</h3><p>Purpose: Retrieve metadata (existence, child items, column info) from a dataset without copying data.</p><h3>Common Metadata Fields</h3><p>FieldReturnsUse CaseExistsTrue/FalseCheck if file/folder existsChild itemsList of filesCount files, get file listItem nameStringGet single filenameItem typefile/folderDistinguish files from foldersLast modifiedDateTimeFind recently updated filesSizeBytesCheck file size</p><h3>Example: Check for new files in blob</h3><pre>{<br>  &quot;Activity&quot;: &quot;GetMetadata_NewFiles&quot;,<br>  &quot;Dataset&quot;: &quot;blob_raw_customers&quot;,<br>  &quot;Field to retrieve&quot;: [&quot;child items&quot;, &quot;exists&quot;, &quot;lastModified&quot;],<br>  &quot;Output variable&quot;: &quot;metadata_output&quot;<br>}</pre><h3>Accessing Results in Next Activity</h3><pre>@activity(&#39;GetMetadata_NewFiles&#39;).output.childItems<br>@activity(&#39;GetMetadata_NewFiles&#39;).output.exists<br>@activity(&#39;GetMetadata_NewFiles&#39;).output.lastModified</pre><h3>3. IF CONDITION ACTIVITY</h3><p>Purpose: Conditional branching based on true/false expressions.</p><h3>Structure</h3><pre>If Condition<br>├─ Expression: @equals(activity(&#39;GetMetadata&#39;).output.exists, true)<br>├─ True Branch: Execute Copy Activity<br>└─ False Branch: Execute Fail Activity</pre><h3>Common Expressions for Your Pipeline</h3><p>Check if files exist:</p><pre>@equals(activity(&#39;GetMetadata_Files&#39;).output.exists, true)</pre><p>Check if row count &gt; 0:</p><pre>@greater(activity(&#39;LookupRowCount&#39;).output.value, 0)</pre><p>Check if file modified today:</p><pre>@greaterOrEquals(activity(&#39;GetMetadata&#39;).output.lastModified, adddays(utcnow(), -1))</pre><p>Check if multiple conditions:</p><pre>@and(<br>  equals(activity(&#39;Validation_Customers&#39;).output.Result, &#39;Passed&#39;),<br>  equals(activity(&#39;Validation_Products&#39;).output.Result, &#39;Passed&#39;)<br>)</pre><h3>Example: Branch based on data freshness</h3><pre>If Condition: &quot;Is data fresh?&quot;<br>├─ Expression: @greaterOrEquals(activity(&#39;GetMetadata&#39;).output.lastModified, adddays(utcnow(), -1))<br>├─ True: Copy to Snowflake (new data)<br>└─ False: Log warning, skip copy</pre><h3>4. WEB ACTIVITY</h3><p>Purpose: Call external APIs/webhooks (Slack, Teams, custom APIs).</p><h3>Use Cases for Your Pipeline</h3><ul><li>Post pipeline status to Slack</li><li>Trigger webhooks on validation failure</li><li>Call external API for data quality scores</li></ul><h3>Example: Send Slack notification on failure</h3><pre>{<br>  &quot;Activity&quot;: &quot;NotifySlack_OnFailure&quot;,<br>  &quot;URL&quot;: &quot;https://hooks.slack.com/services/YOUR/WEBHOOK/URL&quot;,<br>  &quot;Method&quot;: &quot;POST&quot;,<br>  &quot;Body&quot;: {<br>    &quot;text&quot;: &quot;⚠️ ADF Pipeline Failed&quot;,<br>    &quot;blocks&quot;: [<br>      {<br>        &quot;type&quot;: &quot;section&quot;,<br>        &quot;text&quot;: {<br>          &quot;type&quot;: &quot;mrkdwn&quot;,<br>          &quot;text&quot;: &quot;*Pipeline*: @{pipeline().name}\n*Run ID*: @{pipeline().RunId}\n*Time*: @{utcnow()}&quot;<br>        }<br>      }<br>    ]<br>  }<br>}</pre><h3>Example: Call external data quality API</h3><pre>{<br>  &quot;Activity&quot;: &quot;DQ_CheckRowCounts&quot;,<br>  &quot;URL&quot;: &quot;https://dq-api.company.com/validate&quot;,<br>  &quot;Method&quot;: &quot;POST&quot;,<br>  &quot;Headers&quot;: {<br>    &quot;Authorization&quot;: &quot;Bearer @{linkedService().apiKey}&quot;,<br>    &quot;Content-Type&quot;: &quot;application/json&quot;<br>  },<br>  &quot;Body&quot;: {<br>    &quot;table&quot;: &quot;raw.customers&quot;,<br>    &quot;expected_rows&quot;: &quot;@{activity(&#39;GetMetadata&#39;).output.value}&quot;<br>  }<br>}</pre><h3>5. DELETE ACTIVITY</h3><p>Purpose: Delete files/folders from blob storage after successful ingestion.</p><h3>Use Case: Archive processed files</h3><pre>Successful Ingestion<br>  ↓<br>[Delete Activity] Remove processed file from raw container<br>  └─ Move to archive instead (recommended)</pre><h3>Safe Pattern: Move instead of delete</h3><pre>1. Copy raw file to Snowflake<br>2. Copy file to archive/2025-08-13/ (backup)<br>3. Delete from raw container (cleanup)</pre><h3>Example Configuration</h3><pre>{<br>  &quot;Activity&quot;: &quot;DeleteProcessedFile&quot;,<br>  &quot;Dataset&quot;: &quot;blob_raw_customers&quot;,<br>  &quot;Recursive&quot;: false,<br>  &quot;Include&quot;: &quot;customers_20250813.csv&quot;,<br>  &quot;Wild cards&quot;: &quot;customers_*.csv&quot;<br>}</pre><h3>6. FAIL ACTIVITY</h3><p>Purpose: Intentionally fail the pipeline with a custom message.</p><h3>Use Cases</h3><ul><li>Validation failed → Stop pipeline</li><li>Data quality check failed → Alert and stop</li><li>Critical error → Manual intervention needed</li></ul><h3>Example: Data validation failure</h3><pre>{<br>  &quot;Activity&quot;: &quot;FailOnBadData&quot;,<br>  &quot;Error code&quot;: &quot;INVALID_DATA&quot;,<br>  &quot;Message&quot;: &quot;Row count is 0 - no data to ingest from @{linkedService().accountName}/@{dataset().folderPath}&quot;<br>}</pre><h3>7. COMPLETE PIPELINE: Azure Blob → Snowflake with Control Flow</h3><pre>┌─────────────────────────────────────────────────────────────┐<br>│ PIPELINE: IngestRawToSnowflake                              │<br>└─────────────────────────────────────────────────────────────┘</pre><pre>Start<br>  ↓<br>[1. Validation] Blob container exists?<br>  ├─ Fail → [Fail Activity] &quot;Container not found&quot;<br>  └─ Pass ↓<br>[2. Get Metadata] List files in blob/raw/customers/<br>  ├─ Fail → [Fail Activity] &quot;Cannot read metadata&quot;<br>  └─ Pass ↓<br>[3. If Condition] @exists output = true?<br>  ├─ False → [Fail Activity] &quot;No files found&quot;<br>  └─ True ↓<br>[4. For Each] Iterate @activity(&#39;GetMetadata&#39;).output.childItems<br>  │<br>  ├─→ [5. Get Metadata] File size &amp; last modified<br>  │     ↓<br>  │   [6. If Condition] File size &gt; 0 AND modified today?<br>  │     ├─ False → Log &amp; skip<br>  │     └─ True ↓<br>  │     [7. Copy Activity] Copy file to Snowflake RAW.CUSTOMERS_RAW<br>  │       ├─ Fail → [Web Activity] Notify Slack<br>  │       └─ Pass ↓<br>  │     [8. Lookup] SELECT COUNT(*) FROM RAW.CUSTOMERS_RAW<br>  │       ├─ Fail → [Fail Activity] &quot;Load verification failed&quot;<br>  │       └─ Pass ↓<br>  │     [9. Delete Activity] Remove from blob/raw/ (archive first)<br>  │<br>End (Success)</pre><h3>8. TUMBLING WINDOW</h3><p>Purpose: Recurring pipeline execution at fixed intervals (daily, hourly, etc.).</p><h3>Configuration</h3><pre>{<br>  &quot;Trigger&quot;: &quot;TumblingWindowTrigger&quot;,<br>  &quot;Frequency&quot;: &quot;Daily&quot;,<br>  &quot;Interval&quot;: 1,<br>  &quot;Start time&quot;: &quot;2025-08-13T00:00:00Z&quot;,<br>  &quot;End time&quot;: &quot;2025-12-31T23:59:59Z&quot;,<br>  &quot;Delay&quot;: &quot;00:05:00&quot; (wait 5 min after window closes)<br>}</pre><h3>Window Variables Available in Pipeline</h3><pre>@trigger().outputs.windowStart    → 2025-08-13 00:00:00<br>@trigger().outputs.windowEnd      → 2025-08-14 00:00:00</pre><h3>Use in Dynamic Copy Activity</h3><pre>Source: blob://raw/customers/@{formatDateTime(trigger().outputs.windowStart, &#39;yyyy-MM-dd&#39;)}/*.csv<br>Sink: Snowflake RAW.CUSTOMERS_RAW</pre><h3>Your Use Case: Daily ingestion at 2 AM</h3><pre>{<br>  &quot;Trigger&quot;: &quot;DailyIngestionTrigger&quot;,<br>  &quot;Frequency&quot;: &quot;Day&quot;,<br>  &quot;Interval&quot;: 1,<br>  &quot;Start time&quot;: &quot;2025-08-13T02:00:00Z&quot;,<br>  &quot;Delay&quot;: &quot;00:10:00&quot;,<br>  &quot;Retry policy&quot;: &quot;3 retries, 1 min interval&quot;<br>}</pre><h3>9. TROUBLESHOOTING CHECKLIST</h3><h3>Validation Activity Fails</h3><ul><li>Dataset connection is correct</li><li>File/folder path is case-sensitive (blob storage)</li><li>Linked Service credentials are valid</li><li>Check firewall rules (if on private network)</li><li>Increase timeout if large dataset</li></ul><h3>Get Metadata Fails</h3><ul><li>Dataset type matches metadata field (e.g., “child items” for folder, not file)</li><li>Path exists and is accessible</li><li>Linked Service has read permissions</li><li>Try simpler field first (e.g., “exists” before “child items”)</li></ul><h3>If Condition Expression Errors</h3><ul><li>Use correct syntax: @equals(left, right)</li><li>Check activity names (case-sensitive in expressions)</li><li>Validate JSON output format with debug print</li><li>Use Web Activity to log expression results</li></ul><h3>Copy Activity to Snowflake Fails After Validation Pass</h3><ul><li>Snowflake linked service credentials correct</li><li>Target table/schema exists</li><li>Column order/types match source</li><li>File encoding is UTF-8</li><li>Check Snowflake error logs</li></ul><h3>Tumbling Window Not Triggering</h3><ul><li>Trigger status is “Active” (not disabled)</li><li>Current time &gt; start time</li><li>Pipeline is published</li><li>Check trigger run history for errors</li><li>Verify cron expression syntax</li></ul><h3>Delete Activity Leaves Files</h3><ul><li>Wildcard pattern is correct</li><li>Recursive flag set if deleting folders</li><li>Check case sensitivity</li><li>Verify Linked Service has delete permissions</li></ul><h3>10. RECOMMENDED PIPELINE PATTERN FOR YOUR PROJECT</h3><h3>Current State (Python)</h3><pre>Azure Blob → Python ingestion/main.py → Snowflake raw<br>                ↓<br>            dbt models → staging → marts (SCD2)</pre><h3>Enhanced with ADF (Hybrid Approach)</h3><pre>Azure Blob<br>  ↓<br>[ADF Pipeline: ValidateAndCopy]<br>  ├─ Validate blob container<br>  ├─ Get metadata (file list)<br>  ├─ Copy to Snowflake RAW layer<br>  ├─ Data quality checks<br>  └─ Log results<br>       ↓<br>[Snowflake RAW tables]<br>  ├─ raw.customers_raw<br>  ├─ raw.products_raw<br>  └─ raw.orders_raw<br>       ↓<br>[dbt: Staging + Marts]<br>  ├─ stg_customers → dim_customers_scd2<br>  ├─ stg_products → dim_products_scd2<br>  └─ fct_orders<br>       ↓<br>[Snowflake Analytics]</pre><h3>Benefits</h3><p>✅ ADF handles orchestration + error handling<br>✅ Keep dbt for transformations (its strength)<br>✅ Reduce Python maintenance<br>✅ Built-in retry + alerting<br>✅ Monitor in Azure Portal</p><h3>11. QUICK REFERENCE: ACTIVITY CHEAT SHEET</h3><p>ActivityInputOutputError HandlingValidationDatasetPass/Fail→ Fail ActivityGet MetadataDataset + fieldMetadata object→ Fail ActivityIf ConditionExpressionTrue/False branchBoth must be definedWebURL + methodHTTP responseRetry policy (optional)DeleteDataset + patternSuccess/FailCheck permissionsFailMessage + codeStops pipelineManual interventionCopySource + sinkRow countData quality checksLookupQueryResult setHandle empty result</p><h3>Next Steps</h3><ol><li>Decide: Keep Python ingestion OR switch to ADF Copy Activity?</li><li>Build: Create ADF pipeline with validation → copy → verify</li><li>Test: Run with sample data (e.g., 1 file from blob)</li><li>Monitor: Set up alerts in Azure Portal</li><li>Schedule: Add Tumbling Window trigger for daily runs</li><li>Integrate: Keep dbt for transformations (no changes needed)</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69f632327139" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Palantir Migration & Transformation Best Practices]]></title>
            <link>https://medium.com/@manomita.dey/palantir-migration-transformation-best-practices-0861dc500c89?source=rss-1e9fba1aa067------2</link>
            <guid isPermaLink="false">https://medium.com/p/0861dc500c89</guid>
            <dc:creator><![CDATA[Manomita Dey]]></dc:creator>
            <pubDate>Tue, 11 Aug 2026 23:35:12 GMT</pubDate>
            <atom:updated>2026-08-11T23:35:12.555Z</atom:updated>
            <content:encoded><![CDATA[<p>Strategic patterns for SQL and Python-based data transformations during platform migration</p><p>Published August 2026 • 12 min read</p><p>Migrating to Palantir Foundry represents a significant architectural shift for data teams. Success depends less on tool mastery than on systematic transformation patterns that survive the transition intact. This guide covers the core principles, anti-patterns to avoid, and concrete strategies for migrating SQL-based and Python-based transformations.</p><h3>Part 1: Planning Your Palantir Migration</h3><h3>Assess Your Transformation Landscape</h3><p>Before writing a single transform, catalog what you’re moving:</p><ul><li>Extraction patterns — how data enters your system (APIs, batch loads, streams, file ingestion)</li><li>Transformation types — SQL aggregations, Python feature engineering, cross-system joins, incremental loads</li><li>Data lineage — which datasets depend on which others (identifies critical paths)</li><li>SLA / latency requirements — batch vs. real-time expectations for each pipeline</li></ul><p>Key Principle</p><p>A successful migration preserves your existing data contracts (schema, freshness, accuracy) while unlocking Palantir’s integration and governance capabilities. Don’t redesign your data model just because you’re changing platforms.</p><h3>Choose Your Migration Strategy</h3><p>Three common approaches, each with tradeoffs:</p><ol><li>Strangler pattern (recommended) — Migrate one pipeline at a time, run dual systems in parallel for validation, cut over once confidence is high.</li><li>Big bang — Migrate everything at once. Fast if you have perfect test coverage; risky if you don’t.</li><li>Phased by domain — Migrate entire business units sequentially. Useful for large organizations where domains are independent.</li></ol><h3>Part 2: SQL Transformation Best Practices</h3><h3>Preserve SQL Intent During Migration</h3><p>Most SQL transforms port directly to Palantir’s SQL engine, but subtle dialect differences exist. The migration goal is zero behavior change — not cleanup or optimization.</p><p>❌ Don’t: Redesign for Foundry</p><pre>-- Tempting but risky<br>-- Old: Snowflake window functions<br>-- New: Rewrite as SQL native CTE<br>-- Risk: Logic bugs from refactoring</pre><p>✓ Do: Direct Port</p><pre>-- Old (Snowflake)<br>SELECT *, ROW_NUMBER() OVER (...)<br>-- New (Foundry SQL)<br>SELECT *, ROW_NUMBER() OVER (...)<br>-- Same query, same result</pre><h3>Use Staging Layers Consistently</h3><p>Structure your transforms in three tiers:</p><ul><li>Raw — Minimal processing, 1:1 with source data, no joins</li><li>Staging — Type casting, deduplication, filtering; still single-source-of-truth logic</li><li>Marts — Business logic, joins, aggregations; optimized for reporting/analytics</li></ul><pre>-- staging/stg_orders.sql (Foundry SQL)<br>-- Transforms raw data, no business logic<br>SELECT<br>    CAST(order_id AS BIGINT) AS order_id,<br>    CAST(order_date AS DATE) AS order_date,<br>    customer_id,<br>    COALESCE(status, &#39;UNKNOWN&#39;) AS status<br>FROM foundry.raw.orders_raw<br>WHERE order_id IS NOT NULL<br>  AND order_date &gt;= &#39;2020-01-01&#39;<br>  AND _fivetran_deleted = FALSE</pre><h3>Incremental Loads &amp; State Management</h3><p>Palantir Foundry excels at incremental updates. Define your merge strategy early:</p><p>Type 2 SCD Example</p><p>Track dimension changes with valid-from/valid-to dates and a current flag. Use MERGE statements to upsert efficiently. Test date-range queries (as-of queries) to ensure historical accuracy.</p><pre>-- marts/dim_customers_scd2.sql<br>MERGE INTO foundry.marts.dim_customers_scd2 AS tgt<br>USING (<br>    SELECT * FROM {{ ref(&#39;stg_customers&#39;) }}<br>) AS src<br>ON tgt.customer_id = src.customer_id<br>WHEN MATCHED AND tgt.is_current = TRUE<br>    AND tgt.attributes_hash != src.attributes_hash<br>    THEN UPDATE SET<br>        tgt.valid_to = CURRENT_DATE() - 1,<br>        tgt.is_current = FALSE<br>WHEN NOT MATCHED THEN INSERT<br>    (customer_id, attributes, valid_from, is_current, ...)</pre><h3>Testing &amp; Validation Queries</h3><p>After migration, validate with these checks:</p><ul><li>Row count matches old system (within tolerance for live data)</li><li>Aggregations (SUM, COUNT, AVG) match old system exactly</li><li>No null values in NOT NULL columns</li><li>No unexpected duplicates on unique keys</li><li>Date ranges are continuous (no gaps in incremental loads)</li><li>Joins produce expected row counts</li></ul><pre>-- Validation query<br>SELECT<br>    COUNT(*) AS total_rows,<br>    COUNT(DISTINCT order_id) AS distinct_orders,<br>    MIN(order_date) AS earliest,<br>    MAX(order_date) AS latest<br>FROM foundry.marts.fct_orders<br>GROUP BY 1;<br>-- Compare against old system output</pre><h3>Common SQL Migration Pitfalls</h3><ul><li>Date format mismatches — Ensure CAST behavior is consistent across platforms. Test edge cases (leap years, timezone conversions).</li><li>String case sensitivity — Foundry is case-sensitive; old system may have been case-insensitive. Document assumptions.</li><li>Null handling in aggregations — SUM(NULL) = NULL, not 0. Verify expected behavior matches old queries.</li><li>Precision loss in floating-point — Use DECIMAL(p, s) instead of FLOAT for financial data. Test rounding.</li></ul><h3>Part 3: Python Transformation Best Practices</h3><h3>Palantir Python Transforms vs. Standard Scripts</h3><p>Palantir’s Python transforms (using Spark/PySpark) differ from your local scripts. Plan accordingly:</p><p>Local Python</p><pre>import pandas as pd<br>df = pd.read_csv(&#39;data.csv&#39;)<br>df = df[df[&#39;x&#39;] &gt; 10]<br>df.to_csv(&#39;out.csv&#39;)</pre><p>Palantir Python Transform</p><pre>from pyspark.sql import functions as F<br>df = context.spark.read.parquet(...)<br>df = df.filter(F.col(&#39;x&#39;) &gt; 10)<br>context.spark.write.parquet(...)</pre><h3>Structure Python Transforms for Reusability</h3><p>In Foundry, write transforms as pure functions. Avoid dependencies on external files or environment state:</p><pre>from pyspark.sql import functions as F, types as T, SparkSession</pre><pre>def normalize_customer_data(df):<br>    &quot;&quot;&quot;<br>    Standardize customer records: trim whitespace,<br>    lowercase email, validate phone format.<br>    &quot;&quot;&quot;<br>    return (<br>        df<br>        .withColumn(&#39;email&#39;, F.lower(F.trim(F.col(&#39;email&#39;))))<br>        .withColumn(&#39;phone&#39;, F.regexp_replace(<br>            F.col(&#39;phone&#39;), r&#39;[^\d]&#39;, &#39;&#39;<br>        ))<br>        .filter(F.length(F.col(&#39;phone&#39;)) == 10)<br>    )</pre><pre># In your Foundry transform<br>output = normalize_customer_data(context.spark.read.parquet(...))<br>output.write.parquet(...)</pre><h3>Incremental Processing &amp; State</h3><p>Palantir Foundry supports incremental datasets. For large transformations, build incrementally:</p><ul><li>Partition by date — Process one day at a time, recompute only changed data</li><li>Deduplication — Use Spark window functions to de-dupe late-arriving records</li><li>Stateful operations — Store intermediate results (e.g., running balances) in separate datasets</li></ul><pre>from pyspark.sql import functions as F, Window</pre><pre>df = context.spark.read.parquet(...)</pre><pre># Deduplicate by taking latest record per key<br>window = Window.partitionBy(&#39;customer_id&#39;).orderBy(F.desc(&#39;updated_at&#39;))<br>deduped = df.withColumn(&#39;rn&#39;, F.row_number().over(window))\<br>    .filter(F.col(&#39;rn&#39;) == 1)\<br>    .drop(&#39;rn&#39;)</pre><pre># Incremental: only process new data<br>last_max = context.spark.read.parquet(&#39;path/to/checkpoint&#39;)<br>max_date = last_max.agg(F.max(&#39;processed_date&#39;)).collect()[0][0]</pre><pre>new_data = deduped.filter(F.col(&#39;created_date&#39;) &gt; max_date)</pre><h3>Error Handling &amp; Logging</h3><p>Palantir transforms run in distributed environments. Log early and often:</p><pre>import logging</pre><pre>logger = logging.getLogger(__name__)</pre><pre>try:<br>    df = context.spark.read.parquet(...)<br>    logger.info(f&quot;Loaded {df.count()} rows&quot;)</pre><pre>    df_transformed = (<br>        df<br>        .filter(F.col(&#39;quality_score&#39;) &gt; 0.8)<br>    )</pre><pre>    logger.info(f&quot;After filter: {df_transformed.count()} rows&quot;)<br>    context.spark.write.parquet(...)</pre><pre>except Exception as e:<br>    logger.error(f&quot;Transform failed: {str(e)}&quot;, exc_info=True)<br>    raise</pre><h3>Testing Python Transforms Locally</h3><p>Test transforms before deploying to Foundry:</p><ul><li>Mock input data using Spark DataFrames (not pandas)</li><li>Assert output schema matches expected types</li><li>Validate row counts increase/decrease as expected</li><li>Test edge cases: empty input, null columns, duplicates</li><li>Use PySpark testing best practices (avoid collect() in tests)</li></ul><pre>import pytest<br>from pyspark.sql import SparkSession<br>from pyspark.sql import types as T</pre><pre>@pytest.fixture<br>def spark():<br>    return SparkSession.builder\<br>        .master(&quot;local&quot;)\<br>        .appName(&quot;test&quot;)\<br>        .getOrCreate()</pre><pre>def test_normalize_email(spark):<br>    input_data = [<br>        (&quot;user@EXAMPLE.COM&quot;,),<br>        (&quot;  spaces@test.org  &quot;,),<br>    ]<br>    schema = T.StructType([<br>        T.StructField(&quot;email&quot;, T.StringType())<br>    ])<br>    df = spark.createDataFrame(input_data, schema)</pre><pre>    result = normalize_customer_data(df)<br>    emails = [row[0] for row in result.collect()]</pre><pre>    assert emails[0] == &quot;user@example.com&quot;<br>    assert emails[1] == &quot;spaces@test.org&quot;</pre><h3>Common Python Migration Pitfalls</h3><ul><li>Lazy evaluation gotchas — Spark is lazy; filter() doesn&#39;t run until count() or write(). Debug with .explain().</li><li>Memory pressure — Pandas-like `.collect()` loads entire dataset into memory. Use Spark aggregations instead.</li><li>Timezone awareness — Ensure timestamps are timezone-aware; Foundry may have different defaults than local Spark.</li><li>Schema inference — Explicit schema beats inferred. Always define types upfront.</li><li>Dependency bloat — Palantir limits external packages. Prefer native Spark SQL/PySpark for common operations.</li></ul><h3>Part 4: Integration &amp; Orchestration</h3><h3>SQL + Python in the Same Pipeline</h3><p>Foundry excels at mixing SQL and Python transforms. Choose the right tool for each step:</p><ul><li>SQL for — Joins, aggregations, window functions, bulk transformations (faster execution, better optimization)</li><li>Python for — Custom logic, ML feature engineering, complex validations, external API calls</li></ul><pre>-- SQL: Fast aggregation<br>CREATE VIEW staging.daily_summary AS<br>SELECT<br>    date,<br>    customer_id,<br>    SUM(amount) AS daily_total,<br>    COUNT(*) AS transaction_count<br>FROM raw.transactions<br>GROUP BY date, customer_id;</pre><pre>-- Python: Custom feature engineering<br>from pyspark.sql import functions as F</pre><pre>df = context.spark.read.parquet(&#39;staging/daily_summary&#39;)</pre><pre># Add ML features<br>output = df.withColumn(<br>    &#39;is_high_value&#39;,<br>    F.when(F.col(&#39;daily_total&#39;) &gt; 1000, True).otherwise(False)<br>).withColumn(<br>    &#39;days_since_first_transaction&#39;,<br>    F.datediff(F.current_date(), F.col(&#39;first_date&#39;))<br>)</pre><h3>Data Quality Checks</h3><p>Embed checks at each layer:</p><p>Quality Gate Pattern</p><p>After each major transform, run a validation query. If checks fail, halt the pipeline and alert. Don’t cascade bad data downstream.</p><ul><li>Raw layer: count matches expected, no unexpected nulls</li><li>Staging layer: no duplicates, schema is correct, referential integrity</li><li>Marts layer: aggregates match source of truth, drill-down values reconcile</li></ul><h3>Deployment &amp; Rollback Strategy</h3><p>Plan for failures before they happen:</p><ul><li>Keep old transforms running in parallel during initial rollout (dual-write strategy)</li><li>Version all transforms with clear naming (v1, v2, etc.)</li><li>Document rollback procedures (which datasets to restore from backup)</li><li>Monitor lineage — understand what breaks if a transform fails</li><li>Test disaster recovery regularly (restore from backup, rerun transforms)</li></ul><h3>Checklist: Before You Go Live</h3><ul><li>All SQL queries produce identical row counts and aggregates as old system</li><li>Python transforms tested locally and in staging with real data</li><li>Data lineage is documented and validated in Foundry</li><li>Quality checks pass at each layer (raw, staging, marts)</li><li>Date ranges are continuous (no gaps in incremental loads)</li><li>Incremental merge logic tested with duplicate and late-arriving data</li><li>Rollback procedure tested and documented</li><li>Monitoring and alerting configured for production</li><li>Stakeholders have signed off on data accuracy</li><li>Dual-run validation completed (old and new systems match for X days)</li></ul><h3>Key Takeaways</h3><ul><li>Preserve, don’t redesign. Migrate your logic as-is. Optimization comes later.</li><li>Test obsessively. Every transform needs validation queries. Automate them.</li><li>Layer your transforms. Raw → Staging → Marts. Each layer has a job; keep concerns separated.</li><li>Mix SQL and Python strategically. SQL for scale, Python for logic.</li><li>Document data contracts. Schema, freshness, accuracy. These don’t change because the platform changed.</li><li>Plan rollback from day one. Know what to restore if things go wrong.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0861dc500c89" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>