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.

October 12, 2023

Unity Catalog for SQL Server Developers: Catalogs, Schemas and Permissions

The last time I worked on Databricks day to day, in 2020-21, tables lived in the workspace's Hive metastore, permissions were a patchwork of table ACLs and storage access, and every workspace had its own view of the world. Coming back to it now, the biggest change is Unity Catalog. It went GA last year, and it changes how you organise data, who can see what, and how you find things.

For anyone with a SQL Server background, Unity Catalog will feel more familiar than the old setup. This post maps the concepts across and shows a simple layout for insurance data: risk, premium and claim transactions as facts, with broker, coverholder and contract section dimensions.

The three-level namespace

In SQL Server you write database.schema.table. Unity Catalog adds one level above it:

1: catalog.schema.table
2: 
3: SELECT * FROM prod.core.fct_premium;
SQL ServerUnity Catalog
InstanceMetastore (one per region, shared by many workspaces)
DatabaseCatalog
SchemaSchema
Table / viewTable / view (plus volumes, functions and models)
Logins and database usersAccount-level users, groups and service principals

The metastore sits at the account level, so the same catalog is visible from every workspace attached to it. A table created in the engineering workspace can be queried from the analytics workspace without copying anything, as long as the permissions allow it.

A simple layout

I'd use one catalog per environment and schemas by purpose:

1: CREATE CATALOG IF NOT EXISTS dev;
2: CREATE CATALOG IF NOT EXISTS prod;
3: 
4: USE CATALOG prod;
5: 
6: CREATE SCHEMA IF NOT EXISTS raw        COMMENT 'Feeds as received';
7: CREATE SCHEMA IF NOT EXISTS core       COMMENT 'Cleansed, conformed transactions and dimensions';
8: CREATE SCHEMA IF NOT EXISTS reporting  COMMENT 'Star schema and aggregates for Power BI';

A catalog per environment means the same code can run in dev and prod by changing one parameter, and a careless query in dev can't touch production tables. Schemas by purpose keep permissions simple: most people only ever need reporting.

Managed and external tables

A managed table stores its files in the storage location Unity Catalog controls. Drop the table and the data goes too, just like SQL Server. An external table points at files in your own storage path, and dropping it leaves the files in place.

 1: CREATE TABLE prod.core.dim_coverholder (
 2:   coverholder_key   BIGINT GENERATED ALWAYS AS IDENTITY,
 3:   coverholder_id    STRING NOT NULL,
 4:   coverholder_name  STRING,
 5:   country           STRING,
 6:   approval_status   STRING
 7: );
 8: 
 9: CREATE TABLE prod.raw.claims_raw
10: LOCATION 'abfss://feeds@mystorage.dfs.core.windows.net/claims/';

External paths go through two objects an admin sets up once: a storage credential (a managed identity or IAM role) and an external location that grants use of a path. Users never see keys, which is a big improvement on mounting storage with a service principal secret, as we used to.

Permissions feel like SQL Server again

Grants are standard SQL and are inherited downwards. To query a table you need USE CATALOG on the catalog, USE SCHEMA on the schema and SELECT on the table (or on the whole schema):

1: GRANT USE CATALOG ON CATALOG prod TO `analysts`;
2: GRANT USE SCHEMA  ON SCHEMA  prod.reporting TO `analysts`;
3: GRANT SELECT      ON SCHEMA  prod.reporting TO `analysts`;
4: 
5: GRANT USE CATALOG ON CATALOG prod TO `engineers`;
6: GRANT ALL PRIVILEGES ON SCHEMA prod.core      TO `engineers`;
7: GRANT ALL PRIVILEGES ON SCHEMA prod.reporting TO `engineers`;
8: 
9: SHOW GRANTS ON SCHEMA prod.reporting;

Grant to groups, never to individuals. Groups come from your identity provider through account-level SCIM, so joiners and leavers are handled in one place.

Row-level security with dynamic views

In insurance, not everyone should see every coverholder's business. A class underwriter may only see their own class, and claims handlers may not need premium detail. A dynamic view filters rows based on who is asking:

 1: CREATE OR REPLACE VIEW prod.reporting.v_premium_secure AS
 2: SELECT p.*
 3: FROM   prod.reporting.fct_premium p
 4: JOIN   prod.reporting.dim_section cs
 5:        ON cs.contract_section_key = p.contract_section_key
 6: WHERE  is_account_group_member('all-classes')
 7:    OR (cs.class_of_business = 'Property' AND is_account_group_member('property-team'))
 8:    OR (cs.class_of_business = 'Marine'   AND is_account_group_member('marine-team'));
 9: 
10: GRANT SELECT ON VIEW prod.reporting.v_premium_secure TO `analysts`;

Users get SELECT on the view but not on the underlying table. Hard-coding classes in the WHERE clause doesn't scale far, so for anything bigger, join to a mapping table of group to class or coverholder instead.

Lineage and discovery

Unity Catalog records lineage automatically for queries run on Databricks compute: which tables and columns fed a table, and which notebooks, jobs and dashboards read it. When someone asks where the GWP figure on a dashboard comes from, Catalog Explorer can show the path back to the raw feed. On SQL Server that question usually meant searching stored procedures for a column name.

Add comments and tags as you build, so search actually finds things:

1: COMMENT ON TABLE prod.reporting.fct_premium IS
2:   'One row per premium transaction from the bordereaux feed, in original and GBP amounts';
3: 
4: ALTER TABLE prod.reporting.fct_premium
5:   ALTER COLUMN gross_premium_gbp COMMENT 'Gross written premium converted at month-end ROE';

Moving from the Hive metastore

Existing workspaces still have a hive_metastore catalog with the old tables. You can query it alongside Unity Catalog while you migrate. External tables can be upgraded in place with SYNC, and managed tables are usually copied with CREATE TABLE ... AS SELECT or DEEP CLONE. Plan it schema by schema, and update jobs to use three-part names as you go.

Quick recap

  • Think of a catalog as a database, and use one per environment.
  • Prefer managed tables. Use external locations instead of mounts and secrets.
  • Grant to groups, at schema level where you can.
  • Use dynamic views for row-level rules such as class of business or coverholder.
  • Add comments as you build. Lineage does the rest.