December 12, 2024

Amazon Athena and Apache Iceberg: ACID Claims Tables on S3

For a long time, the honest answer to "can I update a row in my S3 data lake?" was "sort of": rewrite the partition, overwrite the files, and hope nobody queries it at the same moment. That's a real problem for claims data. Claim transactions get corrected, reserves move every month, and claimant personal data has to be removable on request. Apache Iceberg changes that, and Amazon Athena (engine v3) supports it well. You get INSERT, UPDATE, DELETE, MERGE, time travel and schema evolution on plain files in S3, using SQL that feels close to a warehouse.

Athena is already my go-to for quick checks on data sitting in S3. With Iceberg, it becomes much more than that. And with AWS announcing S3 Tables at re:Invent last week, which is S3 storage built specifically for Iceberg, it's clear where AWS's lakehouse strategy is heading. Here's a practical introduction using Athena, the Glue Data Catalog and a claims bordereau.

Creating an Iceberg table

 1: CREATE TABLE lake.claims (
 2:   claim_ref            STRING,
 3:   umr                  STRING,
 4:   section_no           STRING,
 5:   coverholder_id       STRING,
 6:   certificate_ref      STRING,
 7:   bordereau_month      DATE,
 8:   date_of_loss         DATE,
 9:   claim_status         STRING,
10:   claimant_name        STRING,
11:   paid_this_month      DECIMAL(18,2),
12:   outstanding_reserve  DECIMAL(18,2),
13:   fees_paid            DECIMAL(18,2),
14:   original_ccy         STRING,
15:   transaction_ts       TIMESTAMP
16: )
17: PARTITIONED BY (month(transaction_ts))
18: LOCATION 's3://my-data-bucket/iceberg/claims/'
19: TBLPROPERTIES (
20:   'table_type'        = 'ICEBERG',
21:   'format'            = 'parquet',
22:   'write_compression' = 'zstd'
23: );

Two things worth noting:

  • 'table_type' = 'ICEBERG' is what makes it an Iceberg table rather than a classic Hive table. The table is registered in the Glue Data Catalog, so EMR, Glue jobs and Redshift Spectrum can use it too.
  • PARTITIONED BY (month(transaction_ts)) is hidden partitioning. You don't add a separate partition column and you don't have to remember to filter on it. Queries filtering on transaction_ts get partition pruning automatically. Anyone who has explained Hive's dt= partition columns to claims analysts will appreciate this.

Loading the monthly claims bordereau

 1: INSERT INTO lake.claims
 2: SELECT claim_ref, umr, section_no, coverholder_id, certificate_ref,
 3:        CAST(bordereau_month AS DATE),
 4:        CAST(date_of_loss AS DATE),
 5:        UPPER(claim_status),
 6:        claimant_name,
 7:        CAST(paid_this_month     AS DECIMAL(18,2)),
 8:        CAST(outstanding_reserve AS DECIMAL(18,2)),
 9:        CAST(fees_paid           AS DECIMAL(18,2)),
10:        original_ccy,
11:        CAST(transaction_ts AS TIMESTAMP)
12: FROM   raw.claims_csv
13: WHERE  bordereau_month = '2024-11-01';

Row-level changes

1: UPDATE lake.claims
2: SET    claim_status = 'CLOSED', outstanding_reserve = 0
3: WHERE  claim_ref = 'CLM-2024-004512'
4:   AND  bordereau_month = DATE '2024-11-01';
5: 
6: UPDATE lake.claims
7: SET    claimant_name = NULL
8: WHERE  claim_ref = 'CLM-2021-000193';

That second one is a big reason teams move to Iceberg. Removing one claimant's details across years of Parquet files used to be a project. Now it's a statement (plus a VACUUM to physically remove old files, covered below, since older snapshots still contain the original values).

MERGE for corrected bordereaux

When a TPA resubmits a month with corrections, MERGE applies it in one transaction:

 1: MERGE INTO lake.claims t
 2: USING raw.claims_updates s
 3:   ON  t.claim_ref = s.claim_ref
 4:   AND t.bordereau_month = s.bordereau_month
 5: WHEN MATCHED AND s.record_action = 'DELETE' THEN DELETE
 6: WHEN MATCHED THEN UPDATE SET
 7:      claim_status        = s.claim_status,
 8:      paid_this_month     = s.paid_this_month,
 9:      outstanding_reserve = s.outstanding_reserve,
10:      fees_paid           = s.fees_paid
11: WHEN NOT MATCHED THEN INSERT
12:      (claim_ref, umr, section_no, coverholder_id, certificate_ref, bordereau_month,
13:       date_of_loss, claim_status, claimant_name, paid_this_month, outstanding_reserve,
14:       fees_paid, original_ccy, transaction_ts)
15: VALUES (s.claim_ref, s.umr, s.section_no, s.coverholder_id, s.certificate_ref,
16:         s.bordereau_month, s.date_of_loss, s.claim_status, s.claimant_name,
17:         s.paid_this_month, s.outstanding_reserve, s.fees_paid, s.original_ccy,
18:         s.transaction_ts);

Time travel: reproduce a month-end

This is the feature I'd pick Iceberg for on its own. Reserving and finance teams regularly ask, "what did the claims position look like when we closed November, before the resubmission came in?"

 1: SELECT umr, section_no,
 2:        SUM(paid_this_month)     AS paid,
 3:        SUM(outstanding_reserve) AS outstanding
 4: FROM   lake.claims
 5: FOR TIMESTAMP AS OF TIMESTAMP '2024-12-06 18:00:00 UTC'
 6: WHERE  bordereau_month = DATE '2024-11-01'
 7: GROUP  BY umr, section_no;
 8: 
 9: SELECT * FROM lake.claims FOR VERSION AS OF 4348509271362591234;
10: 
11: SELECT * FROM "lake"."claims$snapshots" ORDER BY committed_at DESC;
12: 
13: SELECT * FROM "lake"."claims$partitions";

The $snapshots, $files, $partitions and $history metadata tables are great for debugging. When someone says "the outstanding figure changed overnight", you can see exactly which commit did it.

Maintenance: OPTIMIZE and VACUUM

Every UPDATE, DELETE or MERGE writes new files (Athena uses merge-on-read delete files), and monthly loads from dozens of coverholders create lots of small files. Over time reads slow down. Two commands keep a table healthy:

1: OPTIMIZE lake.claims REWRITE DATA USING BIN_PACK
2: WHERE transaction_ts >= TIMESTAMP '2024-11-01 00:00:00';
3: 
4: VACUUM lake.claims;

How long VACUUM keeps snapshots is controlled by table properties. Balance two needs here: reproducing month-ends (keep snapshots longer) and erasing personal data on request (old snapshots must eventually go).

1: ALTER TABLE lake.claims SET TBLPROPERTIES (
2:   'vacuum_max_snapshot_age_seconds' = '3456000'
3: );

Forty days covers the current month-end and the previous one. For longer-term reproducibility, it's safer to snapshot each month-end close into its own table rather than relying on time travel forever. Glue Data Catalog also now offers automatic compaction for Iceberg tables, which is worth turning on so you don't have to schedule OPTIMIZE yourself.

Schema evolution

1: ALTER TABLE lake.claims ADD COLUMNS (cause_of_loss STRING);
2: ALTER TABLE lake.claims
3:   CHANGE COLUMN outstanding_reserve outstanding_reserve DECIMAL(20,2);

Iceberg tracks columns by ID, not by name or position, so renames and reorders don't break existing data files. That's a real improvement on Hive tables, where renaming a column in a Parquet table could quietly return nulls, which is not what you want to discover in a claims report.

Cost and performance tips

  • Athena charges per TB scanned, so partition pruning and Parquet column pruning are your cost controls. Always filter on transaction_ts or another partition source column.
  • Run OPTIMIZE after each month's bordereaux and resubmissions are loaded. Too many delete files means you pay to scan rows that were already removed.
  • Don't over-partition. Claims volumes in DA are modest, so month() is usually right. day() would create tiny files.
  • Use Athena workgroups with per-query data scan limits. One unfiltered SELECT * on years of claims history is an expensive lesson.

Where this is heading

Iceberg has become the format the major vendors agree on. Snowflake, Databricks (after acquiring Tabular), Google, and now AWS with S3 Tables all support it. For a DA team on AWS, Athena plus Iceberg on S3 gives you a serverless claims and premium store with warehouse-style SQL and no cluster to run. I'll write more once I've had a chance to try S3 Tables.

September 12, 2024

Liquid Clustering vs Partitioning and Z-ORDER on Databricks

Choosing how to lay out a Delta table has always meant guessing how it will be queried. Partition by the wrong column and you get thousands of tiny folders. Z-ORDER by the wrong columns and OPTIMIZE spends hours rewriting data for little gain. When I worked on Databricks a few years ago, our standard was a date partition plus a weekly OPTIMIZE ... ZORDER BY on the main filter columns. It worked, but every new query pattern meant revisiting the design.

Liquid clustering, now generally available, replaces both partitioning and Z-ORDER for most tables. This post compares the three approaches using insurance transaction tables, and covers when to switch.

Partitioning: the old default

 1: CREATE TABLE prod.core.risks (
 2:   umr                STRING,
 3:   section_no         STRING,
 4:   coverholder_id     STRING,
 5:   certificate_ref    STRING,
 6:   bordereau_month    DATE,
 7:   year_of_account    INT,
 8:   sum_insured        DECIMAL(18,2),
 9:   gross_premium      DECIMAL(18,2)
10: )
11: PARTITIONED BY (bordereau_month);

Partitioning physically splits files into folders by value. Queries filtering on bordereau_month skip whole folders, which is fast. The problems:

  • Only one access pattern benefits. A query by coverholder or UMR across all months still reads everything.
  • Small files. Partition by something too granular, such as day or coverholder, and each folder holds a few small files. Reads get slower, not faster.
  • It's fixed. Changing the partition column means rewriting the whole table.

The usual guidance was to only partition tables over about a terabyte, with at least a gigabyte per partition. Most insurance tables, even years of risk transactions, are smaller than that.

Z-ORDER: better, but manual

1: OPTIMIZE prod.core.risks
2: ZORDER BY (coverholder_id, umr);

Z-ORDER sorts data within files so related values sit together, which makes file skipping work for several columns at once. But it has costs:

  • Every OPTIMIZE rewrites all the data in scope, even data that was already well organised.
  • New data isn't clustered until the next run.
  • It works within partitions, so a poor partition choice still hurts.

Liquid clustering

 1: CREATE TABLE prod.core.risks (
 2:   umr                STRING,
 3:   section_no         STRING,
 4:   coverholder_id     STRING,
 5:   certificate_ref    STRING,
 6:   bordereau_month    DATE,
 7:   year_of_account    INT,
 8:   sum_insured        DECIMAL(18,2),
 9:   gross_premium      DECIMAL(18,2)
10: )
11: CLUSTER BY (bordereau_month, coverholder_id);

With liquid clustering, you name up to four clustering keys and Databricks keeps the data organised by them. The differences that matter:

  • Incremental. OPTIMIZE only reorganises data that needs it, so regular runs are cheap.
  • Changeable. You can change the keys with ALTER TABLE. Existing data isn't rewritten immediately. New and optimised data follows the new keys.
  • No small-file trap. Clustering on a high-cardinality column like coverholder_id or umr is fine. It doesn't create a folder per value.
1: ALTER TABLE prod.core.risks
2: CLUSTER BY (bordereau_month, umr);
3: 
4: OPTIMIZE prod.core.risks;

Liquid clustering can't be combined with PARTITIONED BY or ZORDER on the same table. It replaces both.

Choosing clustering keys

Pick the columns that appear most in filters and join conditions, not the ones that seem most important. For insurance transaction tables, typical choices are:

TableCommon filtersSuggested keys
Risk transactionsBordereau month, coverholder, UMRbordereau_month, coverholder_id
Premium transactionsYear of account, UMR and sectionyear_of_account, umr
Claim transactionsClaim reference, bordereau monthbordereau_month, claim_ref
Small dimensions (broker, coverholder)AnyNone. They're too small to benefit.

Fewer keys usually works better than more. Each extra key dilutes how well the others are clustered. Start with one or two and check query profiles before adding more.

MERGE gets faster too

The benefit isn't only for reads. A MERGE has to find the target files that might contain matching keys. If the target is clustered on the merge key, far fewer files are candidates:

1: MERGE INTO prod.core.claims t
2: USING claims_updates s
3:   ON  t.claim_ref = s.claim_ref
4:   AND t.bordereau_month = s.bordereau_month
5: WHEN MATCHED THEN UPDATE SET *
6: WHEN NOT MATCHED THEN INSERT *;

With the claims table clustered on (bordereau_month, claim_ref), this MERGE touches a small set of files instead of scanning the table. On tables that receive regular corrections, that's often the bigger win.

Migrating an existing table

For an unpartitioned table, you can enable clustering in place:

1: ALTER TABLE prod.core.premium CLUSTER BY (year_of_account, umr);
2: OPTIMIZE prod.core.premium;

New data is clustered from then on. Existing data is reorganised over time as OPTIMIZE runs. If you need the whole table clustered straight away, rebuilding it is the quickest route.

A partitioned table needs to be rebuilt, for example with CREATE TABLE ... CLUSTER BY ... AS SELECT into a new table and a swap. Check the runtime too: liquid clustering needs a recent Databricks Runtime, and readers and writers on older runtimes can't use the table.

Let the platform run OPTIMIZE

For Unity Catalog managed tables, predictive optimization can run OPTIMIZE and VACUUM automatically when Databricks judges it worthwhile. If it's enabled for your account, it removes the need for a maintenance job altogether. If not, schedule OPTIMIZE after your main loads.

What I would do

  • For new tables, start with liquid clustering on one or two common filter columns.
  • Avoid partitioning unless a table is very large and always filtered on one low-cardinality column.
  • Retire weekly Z-ORDER jobs as you move tables across.
  • Cluster on merge keys for tables that receive frequent corrections.

June 20, 2024

Delta Lake MERGE on Databricks: SCD Type 2 for the Coverholder Dimension

Slowly Changing Dimensions were a staple of my SSIS years. The SCD wizard (which everyone eventually replaced with hand-written T-SQL MERGE), the hash comparisons, the IsCurrent flags. Since then I've written the same logic with Delta Lake in Azure Databricks and as Spark SQL history tables in AWS Glue. Moving to a lakehouse, I was glad to find that Delta Lake's MERGE INTO handles both Type 1 and Type 2 cleanly in Spark SQL. This post walks through both, including the "staged union" trick that does SCD2 in a single statement.

In delegated authority, the coverholder dimension is the classic SCD2 case. A coverholder's Lloyd's approval status, oversight rating, country or trading name can all change during a year of account, and when you analyse a risk or a claim you need to know what the coverholder looked like at that time. The broker dimension, on the other hand, is usually fine as Type 1.

Everything here works on Delta tables in Databricks, or in open-source Spark with Delta Lake.

Setup

 1: CREATE TABLE IF NOT EXISTS dim_coverholder (
 2:   coverholder_sk      BIGINT GENERATED ALWAYS AS IDENTITY,
 3:   coverholder_id      STRING,
 4:   coverholder_name    STRING,
 5:   country             STRING,
 6:   approval_status     STRING,
 7:   oversight_rating    STRING,
 8:   row_hash            STRING,
 9:   valid_from          TIMESTAMP,
10:   valid_to            TIMESTAMP,
11:   is_current          BOOLEAN
12: ) USING DELTA;

A note on GENERATED ALWAYS AS IDENTITY: it's supported on Databricks and in recent Delta Lake releases (3.x), but not every runtime supports it. If yours doesn't, generate surrogate keys with monotonically_increasing_id() plus the current max, or use a hash of the business key and valid_from. Identity columns also limit concurrent writes, so test that before relying on them.

The incoming batch from the coverholder register:

1: CREATE OR REPLACE TEMP VIEW stg_coverholder AS
2: SELECT coverholder_id, coverholder_name, country, approval_status, oversight_rating,
3:        sha2(concat_ws('||',
4:               coalesce(coverholder_name, '~'),
5:               coalesce(country, '~'),
6:               coalesce(approval_status, '~'),
7:               coalesce(oversight_rating, '~')), 256) AS row_hash
8: FROM   raw.coverholders;

I hash the tracked attributes once in staging, so the comparison is a single column rather than a long chain of OR a.x <> b.x conditions. The coalesce matters: concat_ws silently skips nulls, so without a placeholder, ('A', NULL, 'B') and (NULL, 'A', 'B') would hash the same. It also avoids the classic trap where NULL <> 'x' evaluates to unknown and a real change gets missed.

SCD Type 1: the broker dimension

For brokers we only care about current values. A corrected broker name should simply overwrite the old one.

 1: MERGE INTO dim_broker AS t
 2: USING stg_broker      AS s
 3: ON  t.broker_code = s.broker_code
 4: WHEN MATCHED AND t.row_hash <> s.row_hash THEN UPDATE SET
 5:   t.broker_name    = s.broker_name,
 6:   t.broker_group   = s.broker_group,
 7:   t.country        = s.country,
 8:   t.row_hash       = s.row_hash
 9: WHEN NOT MATCHED THEN INSERT
10:   (broker_code, broker_name, broker_group, country, row_hash)
11:   VALUES
12:   (s.broker_code, s.broker_name, s.broker_group, s.country, s.row_hash);

The AND t.row_hash <> s.row_hash on the matched branch matters. Without it, every matched row is rewritten, which in Delta means rewriting whole Parquet files and bloating the transaction log.

SCD Type 2: the problem

For a changed coverholder, say one that's been suspended, Type 2 needs two actions: close the current row (set valid_to and is_current = false) and insert a new current row with the new status. But a single source row can only fire one MERGE branch. That's why you often see SCD2 done as an UPDATE followed by an INSERT, with a window between them where the dimension is inconsistent.

The staged-union trick

Feed MERGE each changed row twice: once with its real key (to match and close the old row) and once with a NULL merge key (which can never match, so it falls through to INSERT).

 1: MERGE INTO dim_coverholder AS t
 2: USING (
 3:   SELECT s.coverholder_id AS merge_key, s.*
 4:   FROM   stg_coverholder s
 5: 
 6:   UNION ALL
 7: 
 8:   SELECT NULL AS merge_key, s.*
 9:   FROM   stg_coverholder s
10:   JOIN   dim_coverholder t
11:     ON   t.coverholder_id = s.coverholder_id
12:    AND   t.is_current = true
13:   WHERE  t.row_hash <> s.row_hash
14: ) AS src
15: ON  t.coverholder_id = src.merge_key
16: AND t.is_current     = true
17: 
18: WHEN MATCHED AND t.row_hash <> src.row_hash THEN UPDATE SET
19:   t.valid_to   = current_timestamp(),
20:   t.is_current = false
21: 
22: WHEN NOT MATCHED THEN INSERT
23:   (coverholder_id, coverholder_name, country, approval_status, oversight_rating,
24:    row_hash, valid_from, valid_to, is_current)
25:   VALUES
26:   (src.coverholder_id, src.coverholder_name, src.country, src.approval_status,
27:    src.oversight_rating, src.row_hash, current_timestamp(), NULL, true);

Here's what happens to each type of row:

  • Newly approved coverholder: appears once with its real key, finds no match, and is inserted.
  • Unchanged coverholder: matches, but the hash condition is false, so nothing happens.
  • Changed coverholder (suspended, re-rated, renamed): the keyed copy matches and closes the old row. The NULL-keyed copy inserts the new version.

Because it's one MERGE, it's one Delta transaction. Readers see either the old state or the new one, never something in between.

Using it from the facts

When loading risk, premium or claim transactions, look up the coverholder version that was valid on the transaction date, not just the current one:

1: SELECT r.*, c.coverholder_sk
2: FROM   core.risks r
3: JOIN   dim_coverholder c
4:   ON   c.coverholder_id = r.coverholder_id
5:  AND   r.risk_inception_date >= CAST(c.valid_from AS DATE)
6:  AND   (c.valid_to IS NULL OR r.risk_inception_date < CAST(c.valid_to AS DATE));

Now the question "how much premium did we write through coverholders while they were suspended?" has a straight answer.

One practical point: if you're loading history, set valid_from from the register's effective date rather than current_timestamp(), or every historical risk will fall before the first version of its coverholder.

The declarative alternative

If you use Delta Live Tables, APPLY CHANGES INTO ... STORED AS SCD TYPE 2 does all of the above for you, including the valid-from and valid-to columns. It's worth a look for new pipelines. Knowing how the MERGE version works still helps when you need to debug one or handle an edge case it doesn't cover.

Handling deletes

Delta Lake 2.3 and later support WHEN NOT MATCHED BY SOURCE, which is useful when you receive a full extract of the coverholder register and want to close coverholders that have disappeared:

1: WHEN NOT MATCHED BY SOURCE AND t.is_current = true THEN UPDATE SET
2:   t.valid_to   = current_timestamp(),
3:   t.is_current = false

Only use this with full extracts. With an incremental feed, every coverholder missing from today's batch would be closed. It's an easy mistake to make and an unpleasant one to discover.

Common errors

"Multiple source rows matched and attempted to modify the same target row." Your staging data has duplicate coverholder IDs, for example one coverholder trading under two names. Deduplicate first:

1: CREATE OR REPLACE TEMP VIEW stg_coverholder_dedup AS
2: SELECT * FROM (
3:   SELECT *, ROW_NUMBER() OVER (PARTITION BY coverholder_id ORDER BY extract_ts DESC) AS rn
4:   FROM raw.coverholders
5: ) WHERE rn = 1;

Slow merges on large dimensions. MERGE has to find candidate files in the target. Help it:

  • Add the is_current = true filter to the ON clause (done above) so history rows are skipped.
  • Cluster the target on the merge key: liquid clustering on newer Databricks runtimes, or Z-ORDER on older ones.
  • If the target is partitioned, add a partition predicate to ON so Spark can prune.

Checking the result

1: SELECT coverholder_id, COUNT(*) AS current_rows
2: FROM   dim_coverholder
3: WHERE  is_current = true
4: GROUP  BY coverholder_id
5: HAVING COUNT(*) <> 1;
6: 
7: DESCRIBE HISTORY dim_coverholder LIMIT 5;

DESCRIBE HISTORY shows numTargetRowsInserted, numTargetRowsUpdated and so on in operationMetrics. Logging those to an audit table after every load is well worth it. It's the lakehouse version of the row counts we used to capture in SSIS.

The patterns from the SQL Server years still apply. The staged-union MERGE just does SCD2 more cleanly than we ever managed with a wizard.

April 18, 2024

Delta Live Tables: Data Quality with Expectations

Most data pipelines I've worked on have the same shape. Read a feed, clean it, join it to reference data, and write a few tables. And around that core sits a lot of supporting code: checking what's already loaded, deciding run order, logging row counts, and recording which rows failed validation and why.

Delta Live Tables (DLT) takes a different approach. You declare the tables you want and the rules the data must meet, and Databricks works out the dependencies, runs them in order, handles incremental processing, and records data quality results. This post builds a small DLT pipeline for insurance premium data, with the focus on expectations, the part I find most useful.

The pipeline

Three tables:

  1. premium_raw: premium transactions as they arrive from the bordereaux feed, loaded with Auto Loader.
  2. premium: typed, validated transactions.
  3. premium_summary: monthly GWP by coverholder and year of account for reporting.

Step 1: The raw streaming table

A DLT pipeline is a notebook (Python or SQL) attached to a pipeline definition. In Python, each table is a function decorated with @dlt.table:

 1: import dlt
 2: from pyspark.sql import functions as F
 3: 
 4: FEED_PATH = "abfss://feeds@mystorage.dfs.core.windows.net/premium/"
 5: 
 6: @dlt.table(comment="Premium transactions as received from the bordereaux feed")
 7: def premium_raw():
 8:     return (spark.readStream
 9:               .format("cloudFiles")
10:               .option("cloudFiles.format", "csv")
11:               .option("header", True)
12:               .load(FEED_PATH)
13:               .withColumn("source_file", F.col("_metadata.file_path"))
14:               .withColumn("loaded_at", F.current_timestamp()))

There's no checkpoint path and no schema location to manage. DLT handles both.

Step 2: Typed transactions with expectations

Expectations are rules attached to a table. Each one has a name, a SQL condition, and an action for rows that fail:

DecoratorRows that failUse it for
@dlt.expectKept, and counted as failuresThings to monitor but not block
@dlt.expect_or_dropDropped from the table, and countedRows that must not reach reporting
@dlt.expect_or_failThe update failsProblems that mean the whole feed is wrong
 1: @dlt.table(comment="Typed and validated premium transactions")
 2: @dlt.expect_or_fail("umr_present",           "umr IS NOT NULL")
 3: @dlt.expect_or_drop("valid_premium",         "gross_premium IS NOT NULL")
 4: @dlt.expect_or_drop("valid_inception",       "inception_date IS NOT NULL")
 5: @dlt.expect("expiry_after_inception",        "expiry_date >= inception_date")
 6: @dlt.expect("commission_in_range",           "commission_pct BETWEEN 0 AND 50")
 7: @dlt.expect("known_transaction_type",
 8:             "transaction_type IN ('NEW','RENEWAL','MTA','CANCELLATION')")
 9: def premium():
10:     return (dlt.read_stream("premium_raw")
11:               .select(
12:                   "umr", "section_no", "certificate_ref",
13:                   F.upper(F.trim("transaction_type")).alias("transaction_type"),
14:                   F.to_date("bordereau_month", "yyyy-MM-dd").alias("bordereau_month"),
15:                   F.to_date("inception_date", "dd/MM/yyyy").alias("inception_date"),
16:                   F.to_date("expiry_date", "dd/MM/yyyy").alias("expiry_date"),
17:                   F.col("original_ccy"),
18:                   F.regexp_replace("gross_premium", ",", "").cast("decimal(18,2)").alias("gross_premium"),
19:                   F.col("commission_pct").cast("decimal(9,4)").alias("commission_pct"),
20:                   "source_file", "loaded_at"))

The choice of action is a business decision as much as a technical one. A missing UMR means the feed itself is broken, so the update fails and someone looks at it. A missing premium on one row shouldn't stop everything else, so that row is dropped and counted. A commission percentage outside the usual range might be valid, so it's only monitored.

Several rules can be grouped with @dlt.expect_all_or_drop({...}), which takes a dictionary of names and conditions. That's handy when the rules live in a config file instead of in code.

Step 3: The reporting table

1: @dlt.table(comment="Monthly GWP by coverholder and year of account")
2: def premium_summary():
3:     sections = spark.read.table("prod.core.dim_section")
4:     return (dlt.read("premium")
5:               .join(sections, ["umr", "section_no"])
6:               .groupBy("coverholder_id", "year_of_account", "bordereau_month")
7:               .agg(F.sum("gross_premium").alias("gwp"),
8:                    F.countDistinct("certificate_ref").alias("certificates")))

dlt.read reads a table from the same pipeline as a batch, which makes this a materialised view that DLT recomputes or updates as needed. The reference table comes from Unity Catalog with a normal spark.read.table.

The same thing in SQL

If your team prefers SQL, the whole pipeline can be written that way. Expectations become constraints:

 1: CREATE OR REFRESH STREAMING TABLE premium (
 2:   CONSTRAINT umr_present     EXPECT (umr IS NOT NULL)           ON VIOLATION FAIL UPDATE,
 3:   CONSTRAINT valid_premium   EXPECT (gross_premium IS NOT NULL) ON VIOLATION DROP ROW,
 4:   CONSTRAINT expiry_after_inception EXPECT (expiry_date >= inception_date)
 5: )
 6: COMMENT 'Typed and validated premium transactions'
 7: AS SELECT
 8:   umr, section_no, certificate_ref,
 9:   upper(trim(transaction_type))                              AS transaction_type,
10:   to_date(inception_date, 'dd/MM/yyyy')                      AS inception_date,
11:   to_date(expiry_date, 'dd/MM/yyyy')                         AS expiry_date,
12:   CAST(regexp_replace(gross_premium, ',', '') AS DECIMAL(18,2)) AS gross_premium
13: FROM STREAM(LIVE.premium_raw);

Seeing the results

The pipeline UI shows the dependency graph, and each table shows how many rows passed and failed each expectation. The same numbers are in the pipeline's event log, which you can query to build a data quality dashboard over time:

1: SELECT timestamp,
2:        details:flow_progress.data_quality.expectations AS expectations
3: FROM   event_log(TABLE(prod.core.premium))
4: WHERE  event_type = 'flow_progress'
5:   AND  details:flow_progress.data_quality IS NOT NULL
6: ORDER  BY timestamp DESC;

A chart of "rows dropped for invalid premium, per month" is a simple, useful way to show whether data quality from a feed is getting better or worse.

Keeping the dropped rows

One limitation: expect_or_drop discards failed rows. If you need to send them back to the provider, add a quarantine table with the opposite condition:

1: @dlt.table(comment="Premium rows that failed validation")
2: def premium_rejects():
3:     return (dlt.read_stream("premium_raw")
4:               .withColumn("gross_premium_num",
5:                           F.regexp_replace("gross_premium", ",", "").cast("decimal(18,2)"))
6:               .filter("gross_premium_num IS NULL OR inception_date IS NULL"))

When DLT fits, and when it doesn't

  • Good fit: steady pipelines from feeds to reporting tables, where you want built-in data quality metrics and don't want to manage checkpoints and run order yourself.
  • Less good: heavily procedural logic, complex reprocessing rules, or teams that already orchestrate everything with dbt or another tool. DLT is also Databricks-specific, so the code doesn't move to another platform easily.

Even if you don't adopt DLT for everything, the expectations model is worth borrowing. Naming each rule, deciding up front whether it warns, drops or fails, and tracking the counts over time is good practice in any pipeline.

February 15, 2024

Spark SQL Window Functions on Databricks: Bordereaux Examples for T-SQL Developers

If you know window functions in T-SQL, you already know most of Spark SQL's window functions. The syntax is nearly identical. The differences are in the defaults, a few missing conveniences, and how the work runs on a cluster. This post goes through the patterns I use most on delegated authority bordereaux, from Spark SQL transformations in AWS Glue and Databricks, with the T-SQL habits that need adjusting.

All examples run as-is in a Databricks notebook (a %sql cell), on a Databricks SQL warehouse, or through spark.sql().

Sample data: a premium bordereau

Each row is a premium transaction reported by a coverholder against a binding authority contract section (identified by UMR and section number). Coverholders resubmit corrected bordereaux, so the same transaction can arrive more than once.

 1: CREATE OR REPLACE TEMP VIEW premium_raw AS
 2: SELECT * FROM VALUES
 3:   ('B0999CH001', 'S1', 'CH001', 'CERT-1001', 'NEW',  DATE'2024-01-01', 1200.00, TIMESTAMP'2024-02-05 10:00:00'),
 4:   ('B0999CH001', 'S1', 'CH001', 'CERT-1001', 'NEW',  DATE'2024-01-01', 1250.00, TIMESTAMP'2024-02-12 09:30:00'),
 5:   ('B0999CH001', 'S1', 'CH001', 'CERT-1002', 'NEW',  DATE'2024-01-01',  800.00, TIMESTAMP'2024-02-05 10:00:00'),
 6:   ('B0999CH001', 'S1', 'CH001', 'CERT-1003', 'NEW',  DATE'2024-02-01', 2000.00, TIMESTAMP'2024-03-04 11:00:00'),
 7:   ('B0999CH001', 'S1', 'CH001', 'CERT-1001', 'MTA',  DATE'2024-02-01',  150.00, TIMESTAMP'2024-03-04 11:00:00'),
 8:   ('B0999CH002', 'S2', 'CH002', 'CERT-2001', 'NEW',  DATE'2024-01-01', 5000.00, TIMESTAMP'2024-02-20 15:00:00'),
 9:   ('B0999CH002', 'S2', 'CH002', 'CERT-2002', 'NEW',  DATE'2024-03-01', 3000.00, TIMESTAMP'2024-04-08 15:00:00')
10: AS t(umr, section_no, coverholder_id, certificate_ref, transaction_type,
11:      bordereau_month, gross_premium_gbp, submitted_at);

1. Deduplication: keep the latest submission

The classic bordereaux problem. A coverholder corrects a figure and resends the month, and we want only the latest version of each transaction.

 1: SELECT umr, section_no, coverholder_id, certificate_ref, transaction_type,
 2:        bordereau_month, gross_premium_gbp, submitted_at
 3: FROM (
 4:   SELECT *,
 5:          ROW_NUMBER() OVER (
 6:            PARTITION BY umr, section_no, certificate_ref, transaction_type, bordereau_month
 7:            ORDER BY submitted_at DESC) AS rn
 8:   FROM premium_raw
 9: ) x
10: WHERE rn = 1;

On Databricks you can write this more neatly with QUALIFY, which filters on a window function without a subquery:

1: SELECT *
2: FROM premium_raw
3: QUALIFY ROW_NUMBER() OVER (
4:           PARTITION BY umr, section_no, certificate_ref, transaction_type, bordereau_month
5:           ORDER BY submitted_at DESC) = 1;

Open-source Apache Spark SQL doesn't support QUALIFY, so on EMR or AWS Glue, stick with the subquery version. It's portable everywhere.

2. Running totals: GPI utilisation

Every binding authority section has a Gross Premium Income (GPI) limit. Oversight teams want to see cumulative written premium against that limit, month by month.

1: SELECT umr, section_no, bordereau_month,
2:        SUM(gross_premium_gbp) AS month_gwp,
3:        SUM(SUM(gross_premium_gbp)) OVER (
4:          PARTITION BY umr, section_no
5:          ORDER BY bordereau_month
6:          ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS cumulative_gwp
7: FROM premium_raw
8: GROUP BY umr, section_no, bordereau_month;

Join cumulative_gwp to the contract section's GPI limit and you have a utilisation percentage that can drive an alert at 80% and 100%.

Watch the default frame. As in T-SQL, if you put ORDER BY in the window but leave out the frame, the default is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. With RANGE, rows that tie on the ORDER BY value are treated as peers and all get the same total. Run it at transaction level, and every transaction in the same bordereau month shows the full month's total. Specify ROWS explicitly unless you really want peer behaviour.

3. Moving windows over a time range

Spark supports RANGE with intervals on date and timestamp columns, which is handy for "claims paid in the last 90 days" calculations where payments are irregular:

1: SELECT claim_ref, payment_date, paid_gbp,
2:        SUM(paid_gbp) OVER (
3:          PARTITION BY claim_ref
4:          ORDER BY payment_date
5:          RANGE BETWEEN INTERVAL 89 DAYS PRECEDING AND CURRENT ROW
6:        ) AS paid_last_90_days
7: FROM claim_payments;

T-SQL's RANGE only accepts UNBOUNDED and CURRENT ROW, with no value offsets, so in SQL Server you'd need a self-join or a calendar table for this. One area where Spark is ahead.

4. LAG/LEAD: late bordereaux

Binding authority contracts usually require bordereaux within a set number of days after month end. LAG makes it easy to see each coverholder's submission pattern:

1: WITH submissions AS (
2:   SELECT coverholder_id, bordereau_month, MIN(submitted_at) AS first_submitted
3:   FROM premium_raw
4:   GROUP BY coverholder_id, bordereau_month
5: )
6: SELECT coverholder_id, bordereau_month, first_submitted,
7:        DATEDIFF(CAST(first_submitted AS DATE), LAST_DAY(bordereau_month)) AS days_after_month_end,
8:        LAG(bordereau_month) OVER (PARTITION BY coverholder_id ORDER BY bordereau_month) AS prev_month_submitted
9: FROM submissions;

Note the argument order: Spark's DATEDIFF(end, start) returns days and takes the end date first, the opposite of T-SQL's DATEDIFF(day, start, end). I've lost more time to that than I want to admit. Newer Spark versions also accept a three-argument DATEDIFF(unit, start, end), but check your runtime before you rely on it.

5. Gaps and islands: missing bordereau months

Which coverholders have a run of consecutive monthly bordereaux, and where are the gaps? The trick is the same as in T-SQL: subtract a row number from the month, and consecutive months end up with the same "island" value.

 1: WITH months AS (
 2:   SELECT DISTINCT coverholder_id, bordereau_month FROM premium_raw
 3: ),
 4: grp AS (
 5:   SELECT coverholder_id, bordereau_month,
 6:          ADD_MONTHS(bordereau_month,
 7:                     -CAST(ROW_NUMBER() OVER (PARTITION BY coverholder_id
 8:                                              ORDER BY bordereau_month) AS INT)) AS island
 9:   FROM months
10: )
11: SELECT coverholder_id,
12:        MIN(bordereau_month) AS run_start,
13:        MAX(bordereau_month) AS run_end,
14:        COUNT(*)             AS months_in_run
15: FROM grp
16: GROUP BY coverholder_id, island
17: ORDER BY coverholder_id, run_start;

In the sample data, CH002 has two separate runs (January, then March), so February's bordereau is missing. That's exactly the kind of thing a DA oversight team wants flagged.

6. Top N per group: largest risks per section

1: SELECT * FROM (
2:   SELECT umr, section_no, certificate_ref, gross_premium_gbp,
3:          DENSE_RANK() OVER (PARTITION BY umr, section_no
4:                             ORDER BY gross_premium_gbp DESC) AS rnk
5:   FROM premium_raw
6: ) WHERE rnk <= 2;

Performance: what's different on a cluster

On SQL Server, a window function might use a sort or an index that's already ordered. On Spark, every PARTITION BY causes a shuffle: rows with the same key are moved to the same executor and then sorted. Some practical points:

  • A window without PARTITION BY puts all rows on a single executor. Spark warns you about this ("No Partition Defined for Window operation"). On years of risk transactions it will be slow or run out of memory.
  • Skewed keys hurt. If one large coverholder writes 40% of the premium, one task does 40% of the work. Adaptive Query Execution helps with skewed joins, but window skew is still on you. Consider partitioning by contract section rather than coverholder, or splitting out the heavy key.
  • Several windows with the same PARTITION BY and ORDER BY share one shuffle and sort. Windows with different specs each add one. Group your calculations by spec where you can.
  • Filter early. Restrict to the bordereau months or years of account you need in a CTE before the window, so less data gets shuffled.

The same thing in the DataFrame API

When I'm in Python I often switch to the DataFrame API. The equivalent of the deduplication query:

1: from pyspark.sql import functions as F, Window
2: 
3: keys = ["umr", "section_no", "certificate_ref", "transaction_type", "bordereau_month"]
4: w = Window.partitionBy(*keys).orderBy(F.col("submitted_at").desc())
5: 
6: latest = (spark.table("premium_raw")
7:             .withColumn("rn", F.row_number().over(w))
8:             .filter("rn = 1")
9:             .drop("rn"))

Both produce the same plan, so use whichever reads better to your team. For SQL people moving to Spark, starting in SQL and moving to DataFrames later is a perfectly good path.

December 7, 2023

Databricks Auto Loader: Incremental File Loading Without the Bookkeeping

When I built file ingestion on Databricks a few years ago, Azure Data Factory did the "which files are new?" work: an event trigger or a Get Metadata activity found the file, and a notebook processed it. It worked, but the state of what had been loaded lived in two places, and replaying a day's files was always fiddly.

Auto Loader moves that job into Databricks. It watches a cloud storage folder, keeps track of which files it has already processed, and loads only the new ones, exactly once. This post walks through it using a common insurance case: a regular feed of claims transactions arriving as CSV files.

The basic pattern

Auto Loader is a Structured Streaming source called cloudFiles. Don't let "streaming" put you off: with availableNow it runs like a batch job, processes everything new, and stops.

 1: source_path     = "abfss://feeds@mystorage.dfs.core.windows.net/claims/"
 2: schema_path     = "abfss://meta@mystorage.dfs.core.windows.net/autoloader/claims/schema"
 3: checkpoint_path = "abfss://meta@mystorage.dfs.core.windows.net/autoloader/claims/checkpoint"
 4: 
 5: claims = (spark.readStream
 6:             .format("cloudFiles")
 7:             .option("cloudFiles.format", "csv")
 8:             .option("cloudFiles.schemaLocation", schema_path)
 9:             .option("header", True)
10:             .load(source_path))
11: 
12: (claims.writeStream
13:        .option("checkpointLocation", checkpoint_path)
14:        .trigger(availableNow=True)
15:        .toTable("prod.raw.claims_raw"))

Two locations matter:

  • Checkpoint: where Auto Loader records which files it has processed. Delete it and everything loads again.
  • Schema location: where it stores the schema it has inferred, and how that schema changes over time.

Schema: strings by default

For CSV and JSON, Auto Loader infers every column as STRING unless you set cloudFiles.inferColumnTypes to true. For external feeds, that default is exactly right. Land the data as text, then cast it downstream where you can handle bad values deliberately. If a few columns are safe to type up front, use schema hints:

1: .option("cloudFiles.schemaHints", "claim_ref STRING, transaction_date DATE")

When the feed adds a column

Feeds change. One month the claims file gains a cause_of_loss column. Auto Loader's default schema evolution mode, addNewColumns, handles this in two steps: the stream stops with an error that reports the new column, updates the stored schema, and the next run picks the column up. In a scheduled job with retries, that's usually invisible.

Data that doesn't fit the schema isn't thrown away. It lands in a _rescued_data column as JSON, together with the source file path:

1: SELECT _rescued_data, COUNT(*)
2: FROM   prod.raw.claims_raw
3: WHERE  _rescued_data IS NOT NULL
4: GROUP  BY _rescued_data;

If you'd rather the schema never changes on its own, set cloudFiles.schemaEvolutionMode to rescue. New columns then go to _rescued_data and the table stays as it is until you decide otherwise.

Add file metadata

For audit and replay, I always keep the source file and load time on every row:

 1: from pyspark.sql import functions as F
 2: 
 3: claims = (spark.readStream
 4:             .format("cloudFiles")
 5:             .option("cloudFiles.format", "csv")
 6:             .option("cloudFiles.schemaLocation", schema_path)
 7:             .option("header", True)
 8:             .load(source_path)
 9:             .withColumn("source_file", F.col("_metadata.file_path"))
10:             .withColumn("file_modified", F.col("_metadata.file_modification_time"))
11:             .withColumn("loaded_at", F.current_timestamp()))

The _metadata column is available on newer runtimes and is the replacement for input_file_name().

Directory listing or file notifications?

By default, Auto Loader lists the folder to find new files. That's fine for most feeds, especially when files are organised into date folders. For folders with very large numbers of files, file notification mode (cloudFiles.useNotifications) subscribes to storage events through a queue instead of listing. It needs extra permissions to create the queue and subscription, so I'd start with listing and only switch if listing becomes slow.

Upserting into a transactions table

The raw table is append-only, which is what you want for an audit trail. To maintain a current claims position, use foreachBatch to MERGE each micro-batch into a Delta table:

 1: from delta.tables import DeltaTable
 2: from pyspark.sql import Window
 3: 
 4: def upsert_claims(batch_df, batch_id):
 5:     w = Window.partitionBy("claim_ref", "bordereau_month").orderBy(F.col("file_modified").desc())
 6:     latest = (batch_df.withColumn("rn", F.row_number().over(w))
 7:                       .filter("rn = 1").drop("rn"))
 8: 
 9:     target = DeltaTable.forName(batch_df.sparkSession, "prod.core.claims")
10:     (target.alias("t")
11:        .merge(latest.alias("s"),
12:               "t.claim_ref = s.claim_ref AND t.bordereau_month = s.bordereau_month")
13:        .whenMatchedUpdateAll()
14:        .whenNotMatchedInsertAll()
15:        .execute())
16: 
17: (claims.writeStream
18:        .foreachBatch(upsert_claims)
19:        .option("checkpointLocation", checkpoint_path + "_core")
20:        .trigger(availableNow=True)
21:        .start())

The deduplication inside the batch matters. If the same claim arrives twice in one run, MERGE fails with "multiple source rows matched". Keeping the latest version per key avoids that.

Replaying and backfilling

  • Reprocess everything: write to a new checkpoint location (and usually a fresh target table).
  • Load only from a date: cloudFiles.includeExistingFiles set to false skips files already in the folder when the stream first starts. Use it when onboarding a feed with years of history you'll load separately.
  • A corrected file with the same name: by default, a file with the same path isn't processed twice. Agree versioned file names with the feed provider, or look at cloudFiles.allowOverwrites with care.

Why I'd use it now

Compared with the ADF-triggers-a-notebook approach, Auto Loader keeps file tracking, schema changes and loading in one place, gives exactly-once processing, and makes a replay as simple as a new checkpoint. Orchestration tools still have a job, scheduling and alerting, but working out which files are new is no longer one of them.