Blog
Oct 27, 2026 - 14 MIN READ
Data Quality on Databricks: A Framework for Lakeflow Jobs

Data Quality on Databricks: A Framework for Lakeflow Jobs

A step-by-step data quality framework for a Databricks lakehouse built on Lakeflow Jobs: three lines of defence, a rule catalogue seeded from Git, a runner that warns, quarantines or fails, thresholds and alerts routed to owner groups, monitoring that never gates, and a scorecard.

Radek Řezáč

Radek Řezáč

Data quality on a lakehouse usually ends up in one of two places: scattered assert statements inside notebooks, or a monitoring tool that tells you about a broken table the morning after the dashboard showed wrong numbers. This article describes a framework that sits between the two. Every rule is data in a table, seeded from Git; every load passes through one runner that decides per row whether to warn, quarantine or fail; every result is logged before anything is raised; and alerts reach the group that owns the data. It is based on a runbook written for a finance data platform migrating from SQL Server to Databricks Lakeflow Jobs; the names here are generic.

The Setup

ItemChoice
Environmentsdev, test and prod, one catalog per environment
Schemaserp_bronze, erp_silver, finance_gold, control, and one shared dq schema for every DQ object
ExecutionLakeflow Jobs, one task per migrated procedure, idempotent Delta MERGE INTO. No declarative pipelines, so no built-in expectations and no event log
DeploymentA Databricks Asset Bundle deployed by CI/CD under a CI service principal (OAuth M2M, no personal tokens)
Ownershipdp-<env>-erp-engineers (Bronze/Silver rules), dp-<env>-finance-engineers (Gold rules), a finance business owner who signs Gold thresholds

Because the jobs are plain tasks rather than declarative pipelines, the framework rebuilds what expectations would give you, and adds what they do not: quarantine instead of silently dropping rows, thresholds, routing and a scorecard.

Three Lines of Defence

LineWhatGates the write?
1 EngineSchema enforcement, Delta NOT NULL / CHECK, informational PK/FK, a dq_flags columnYes, and it cannot be skipped
2 Runnerapply_dq() in every job task: rules from dq.rules, evaluated in one pass, evidence written firstYes
3 MonitoringData profiling and anomaly detectionNever

One load, end to end:

transform ─► rank + hash key ─► apply_dq() ─┬─► MERGE INTO target          (rows that passed; dq_flags on Silver)
                                            ├─► MERGE INTO dq.quarantine_* (held-back rows, JSON + failed rule ids)
                                            ├─► dq.violation_log, then dq.run_summary   (evidence, always)
                                            └─► raise DQFailure            (only after the evidence is committed)
after the load:  dq_evaluate_thresholds ─► dq.threshold_breach ─► SQL alert ─► owner group (dq.contacts)
asynchronously:  data profiling + anomaly detection ─► metric tables in dq ─► drift alerts (never gate)

The dq Schema

Everything lives in one schema, created by idempotent DDL that the deploy job runs after every bundle deploy:

TableHolds
dq.rulesEvery rule: target table, layer, dimension, type, scope, SQL expression, action, severity, owner group, validity dates
dq.thresholdsAlert thresholds per table or rule, with the accountable group and escalation
dq.contactsNotification routing per owner group; individuals are exceptions that expire
dq.violation_logOne row per rule execution
dq.run_summaryOne row per runner call — written last, so it marks completion
dq.threshold_breachBreaches, their notification and acknowledgement
dq.quarantine_<source>_<entity>Rows held back by a quarantine rule

The rule catalogue protects itself with constraints:

CREATE TABLE IF NOT EXISTS dq.rules (
    rule_id         STRING    NOT NULL,   -- stable, e.g. 'SIL_ERP_TRADE_ID_NOT_NULL'
    target_table    STRING    NOT NULL,   -- 'erp_silver.trade'
    layer           STRING    NOT NULL,   -- bronze | silver | gold | control
    dimension       STRING    NOT NULL,   -- one of the six dimensions
    rule_type       STRING    NOT NULL,
    rule_scope      STRING    NOT NULL,   -- ROW | DATASET
    rule_expression STRING    NOT NULL,   -- SQL boolean; only TRUE passes
    action          STRING    NOT NULL,   -- WARN | QUARANTINE | FAIL
    severity        STRING    NOT NULL,   -- INFO | WARNING | CRITICAL (reporting only)
    owner_group     STRING    NOT NULL,
    enabled         BOOLEAN   NOT NULL,
    valid_from      DATE      NOT NULL,
    valid_to        DATE
    -- rule_name, description, updated_at, updated_by
) COMMENT 'Every data-quality rule applied by the DQ runner. Seeded from Git only.';

ALTER TABLE dq.rules ADD CONSTRAINT valid_action
  CHECK (action IN ('WARN', 'QUARANTINE', 'FAIL'));
ALTER TABLE dq.rules ADD CONSTRAINT valid_dimension
  CHECK (dimension IN ('consistency','accuracy','validity','completeness','timeliness','uniqueness'));
ALTER TABLE dq.rules ADD CONSTRAINT dataset_rules_cannot_quarantine
  CHECK (NOT (rule_scope = 'DATASET' AND action = 'QUARANTINE'));

ALTER TABLE … ADD CONSTRAINT is not idempotent, so the deploy job adds a constraint only when it is missing from information_schema.check_constraints.

Grants follow the same model as the rest of the platform: the CI service principal owns the objects, workload service principals read the rules and write results, engineers read, and consumers see only the scorecard views. No human group holds MODIFY on dq in production. Each quarantine table gets the same classification tags, row filter and column masks as the table it protects — quarantine must never become the place where restricted data is readable.

Line 1: Engine Controls in the DDL

For every Silver and Gold table, before its first load:

  1. Keep schema enforcement on. Silver and Gold writes never set mergeSchema or auto-merge. A schema change is DDL in the bundle. Bronze may evolve additively, but each change is a SCHEMA_DRIFT warning that gets reviewed.
  2. Use Delta NOT NULL and CHECK for invariants only — Gold business keys, valid_from <= valid_to on SCD2 dimensions, closed-list status columns. A violation aborts the whole transaction, so never use a constraint for something that should be quarantined.
  3. Declare informational primary and foreign keys on Gold for documentation and lineage. They are not enforced, so uniqueness is still a rule.
  4. Add dq_flags ARRAY<STRING> NOT NULL to every Silver table, holding the ids of the warning rules a row violated.
CREATE TABLE IF NOT EXISTS finance_gold.dim_trade (
    trade_key  STRING    NOT NULL,
    trade_id   BIGINT    NOT NULL,
    folder_id  BIGINT    NOT NULL,
    valid_from TIMESTAMP NOT NULL,
    valid_to   TIMESTAMP,
    is_current BOOLEAN   NOT NULL,
    CONSTRAINT pk_dim_trade PRIMARY KEY (trade_key, valid_from)      -- informational
) CLUSTER BY (trade_id);

ALTER TABLE finance_gold.dim_trade ADD CONSTRAINT scd2_interval
  CHECK (valid_to IS NULL OR valid_from <= valid_to);

The Rule Vocabulary

The action decides behaviour, exactly like a declarative-pipeline expectation's ON VIOLATION clause — except that a dropped row is kept in quarantine instead of discarded:

actionExpectation analogueThe rowThe task
WARNexpectkept; rule id in dq_flags on Silvercontinues; violation logged
QUARANTINEexpect_or_dropnot written; held in dq.quarantine_*continues; counters record the loss
FAILexpect_or_failnothing writtenresult logged first, then the task fails
rule_typeScopeDimensionExample expression
NOT_NULLROWcompletenesstrade_id IS NOT NULL
RANGEROWaccuracypl_amount BETWEEN -1e9 AND 1e9
ALLOWED_VALUESROWvaliditypl_type IN ('NPV','ACCRUAL','REALIZED')
PATTERNROWvalidityisin RLIKE '^[A-Z]{2}[A-Z0-9]{9}[0-9]$'
REFERENTIALROWcompletenessfolder_id IN (SELECT folder_id FROM finance_gold.dim_folder)
UNIQUENESSDATASETuniquenessCOUNT(*) = COUNT(DISTINCT trade_key)
ROW_COUNTDATASETcompletenessCOUNT(*) >= 1000
FRESHNESSDATASETtimelinessMAX(business_date) >= CURRENT_DATE() - 1
VOLUME_ANOMALYDATASETcompletenessCOUNT(*) BETWEEN 0.7 * :avg_30d AND 1.3 * :avg_30d
SCHEMA_DRIFTDATASETvalidityevaluated by the runner
RECONCILIATIONDATASETconsistencyABS(SUM(pl_amount) - :source_total) < 0.01

Two rules that are easy to get wrong:

  • NULL is a violation. pl_amount BETWEEN … is NULL when pl_amount is null, and only TRUE passes. If a null is acceptable, say so: pl_amount IS NULL OR pl_amount BETWEEN ….
  • A dataset rule cannot quarantine — there is no row to hold back. The constraint on dq.rules enforces it.

Layer defaults:

LayerDefaultBelongs here
BronzeWARN only — never reject the source recordRow count, freshness, schema drift. Reconciliation with the source system is FAIL for the downstream Silver task, not for the Bronze append
SilverQUARANTINE for row rules; FAIL for duplicate business keysNot-null keys, allowed values, ranges, referential checks, Silver vs Bronze row counts
GoldFAIL — publication stopsMissing dimension members, invalid keys, broken aggregates, measure-level reconciliation
controlFAIL on the gateA missing or stale readiness row fails the gate instead of letting a task read partial data

Rules From a Version-Controlled Seed

Rules are data, but reproducible data. They live in resources/dq/rules.sql and the deploy job applies them with MERGE, so a rule is added without a code change and no rule exists in production that is not in Git.

MERGE INTO dq.rules AS t
USING (
  SELECT * FROM VALUES
    ('SIL_ERP_TRADE_ID_NOT_NULL', 'erp_silver.trade', 'silver', 'completeness',
     'NOT_NULL', 'ROW', 'trade_id IS NOT NULL',
     'QUARANTINE', 'CRITICAL', 'dp-${env}-erp-engineers', true, DATE'2026-09-01', CAST(NULL AS DATE)),
    ('SIL_ERP_TRADE_UNIQUE', 'erp_silver.trade', 'silver', 'uniqueness',
     'UNIQUENESS', 'DATASET', 'COUNT(*) = COUNT(DISTINCT trade_key)',
     'FAIL', 'CRITICAL', 'dp-${env}-erp-engineers', true, DATE'2026-09-01', CAST(NULL AS DATE)),
    ('GLD_PL_FOLDER_FK', 'finance_gold.fact_profit_and_loss', 'gold', 'completeness',
     'REFERENTIAL', 'ROW', 'folder_id IN (SELECT folder_id FROM finance_gold.dim_folder)',
     'FAIL', 'CRITICAL', 'dp-${env}-finance-engineers', true, DATE'2026-09-01', CAST(NULL AS DATE))
  AS s(rule_id, target_table, layer, dimension, rule_type, rule_scope, rule_expression,
       action, severity, owner_group, enabled, valid_from, valid_to)
) AS s
ON t.rule_id = s.rule_id
WHEN MATCHED THEN UPDATE SET
  rule_expression = s.rule_expression, action = s.action, enabled = s.enabled, valid_to = s.valid_to,
  -- ... every other seeded column
  updated_at = current_timestamp(), updated_by = current_user()
WHEN NOT MATCHED THEN INSERT (/* seeded columns */ ..., updated_at, updated_by)
VALUES (/* s.* */ ..., current_timestamp(), current_user());

A rule is retired by setting valid_to, never by deleting it. Onboarding a migrated object is always the same three actions: add its rules to the seed, add one passing and one failing test row per rule, and raise a pull request.

Line 2: The Runner

One function, apply_dq(), is called by every transformation task between building its DataFrame and writing it. It reads the active rules for the target, evaluates all row rules in one aggregate, splits the data, runs the dataset rules on the rows that will be written, writes the evidence, and only then raises if a blocking rule failed. A condensed version, with the helpers elided:

def apply_dq(df, target_table, run_id, spark, task_key=None, params=None, reconcile=False):
    """Validate df against the active rules for target_table and return the rows that may be written."""
    rules = active_rules(spark, target_table, reconcile)
    results = []

    # row rules become flag columns; only TRUE passes, so NULL is a violation
    flagged, row_rules = df, []
    for r in (r for r in rules if r.rule_scope == "ROW"):
        candidate = flagged.withColumn(f"_dq_{r.rule_id}",
                                       F.expr(f"coalesce(NOT ({r.rule_expression}), true)"))
        try:
            candidate.schema          # forces analysis now; Spark Connect is lazy otherwise
            flagged = candidate
            row_rules.append(r)
        except AnalysisException as exc:
            results.append(_result(r, run_id, target_table, task_key, 0, 0, "ERROR", str(exc)))

    flagged = add_failed_warn_and_blocked_columns(flagged, row_rules)
    agg = one_pass_aggregate(flagged, row_rules)          # rows_in, rows_quarantined, per-rule failures
    results += row_results(row_rules, agg)

    # dataset rules run on the rows that will actually be written; parameters are bound, not concatenated
    valid = flagged.where(~F.col("_dq_blocked"))
    valid.createOrReplaceTempView("_dq_input")
    results += dataset_results(spark, rules, params, valid)

    if agg["rows_quarantined"]:
        _write_quarantine(flagged.where(F.col("_dq_blocked")), target_table, run_id, spark)

    hard = [x for x in results if (x["status"] == "FAILED" and x["action"] == "FAIL")
            or (x["status"] == "ERROR" and x["action"] in ("FAIL", "QUARANTINE"))]
    _log(spark, results, agg, outcome(hard, agg, results))   # violation_log first, run_summary last
    if hard:
        raise DQFailure(f"{target_table}: blocking rule(s) failed: {[x['rule_id'] for x in hard]}")

    return with_dq_flags_on_silver(valid, target_table)

Properties any change to the runner must preserve:

  • One pass for all row rules, and no .cache() (not supported on serverless).
  • NULL is a violation, so no row falls between the valid and the quarantined split.
  • A row can fail several rules; all of their ids are kept.
  • A broken expression is an ERROR result. It blocks the write when the rule protects data (FAIL / QUARANTINE) and is only reported for a WARN.
  • Dataset rules see the written rows, so quarantined rows do not distort a uniqueness check.
  • Evidence order: dq.violation_log first, dq.run_summary last. The summary row is the completion marker.
  • Quarantine is idempotent through a MERGE on run_id and a hash of the record, so a repair run adds nothing twice.

Unit tests run on every pull request: a clean DataFrame passes; a warning row is kept and flagged; a quarantined row appears in quarantine exactly once after two calls with the same run_id; a NULL-evaluating rule fails; a FAIL rule raises after both result tables have rows; a broken expression behaves correctly on WARN and on FAIL.

Wiring the Runner Into Every Task

The runner always sits between the transformation and the write. Nothing writes to Silver or Gold without it.

Silver: deduplicate, gate, merge. Deduplicate in the MERGE source with a ranking window on the business key, hash composite keys into one key column, and let the UNIQUENESS rule assert the result — this replaces the unique index of the old database.

latest = Window.partitionBy("trade_key").orderBy(F.col("update_ts").desc(), F.col("trade_id").desc())
silver_df = (
    build_silver_trade(spark.table("erp_bronze.trade"))        # the migrated procedure
    .withColumn("trade_key", F.sha2(F.concat_ws("||", "trade_id", "trade_version"), 256))
    .withColumn("_rn", F.row_number().over(latest))
    .where("_rn = 1").drop("_rn")
)

clean_df = apply_dq(silver_df, "erp_silver.trade", run_id, spark, task_key="s2_trade")

(DeltaTable.forName(spark, "erp_silver.trade").alias("t")
    .merge(clean_df.alias("s"), "t.trade_key = s.trade_key")
    .whenMatchedUpdateAll()
    .whenNotMatchedInsertAll()
    .execute())

The same {{job.run_id}} is passed to Bronze, Silver, Gold and reconciliation tasks, so every DQ row joins to the load and to the task that produced it.

Bronze: observe, then reconcile separately. The Bronze append only applies warnings, so it always lands. A separate reconcile task per feed computes the source-side figures for the same business date and calls apply_dq(..., params={"source_row_count": n}, reconcile=True). A failure there stops the Silver task, not the append.

Gold: FAIL stops publication. A failed Gold rule fails the task, and nothing downstream — corrections, materialised-view refreshes, status logging, BI extract refreshes — runs on data that did not pass. A pure sql_task cannot call Python, so a Gold task that must be gated becomes a notebook task that loads the same SQL file, calls apply_dq and writes with MERGE. The SQL itself is unchanged.

Control gates. A readiness check is a control rule with action FAIL: a missing or stale row stops the downstream task.

Quarantine

One table per quarantined entity, always in dq, named dq.quarantine_<source>_<entity>. The record is stored as JSON, which tolerates source drift, together with every failed rule id:

CREATE TABLE IF NOT EXISTS dq.quarantine_erp_trade (
    run_id           STRING        NOT NULL,
    quarantined_at   TIMESTAMP     NOT NULL,
    target_table     STRING        NOT NULL,
    failed_rule_ids  ARRAY<STRING> NOT NULL,   -- every violated rule, not just the first
    source_row       STRING        NOT NULL,   -- the record as JSON
    record_hash      STRING        NOT NULL,   -- idempotency key with run_id
    reprocess_status STRING        NOT NULL,   -- NEW | IN_REVIEW | REPROCESSED | REJECTED
    reprocessed_at   TIMESTAMP,
    review_note      STRING
) CLUSTER BY (quarantined_at);

The lifecycle:

NEW ──► IN_REVIEW ──┬─► REPROCESSED   (sent back through the same runner and written)
                    └─► REJECTED      (genuinely invalid; note recorded)
  1. Triage — the owner group reviews new rows within the agreed window; a backlog alert fires when it does not.
  2. Fix at the source or fix the rule — a rule that quarantines correct data is a defect in the rule.
  3. Reprocess — a deployed job parses source_row back with from_json, sends it through apply_dq with a new run_id and merges what passes. Status changes go through job parameters, never a console UPDATE.
  4. Retention — rows past the protected table's retention class are deleted by the same job. Quarantine is a holding area, not an archive.

Thresholds and Contacts

A single failed row should not page anyone; a trend should. Thresholds are seeded from Git like the rules:

metricMeaning
quarantine_rate_pctrows quarantined / rows in
fail_rate_pctfailed rules / rules applied, or 100 − pass rate of one rule
rows_quarantinedabsolute rows held back
rows_written_minrows written; with LT it catches an empty or short load
  • consecutive_runs is at least 1; use 2 or more on rates so one noisy run does not alert.
  • Every Gold threshold carries the business owner in approved_by — engineering proposes, the business signs.
  • dq.contacts is keyed on the owner group. A named individual is a documented exception with an expiry date. Channels are distribution lists or notification destination ids, never webhook URLs.

Alerting

Alerting has two independent paths: a FAIL fails the job, so the job's own failure notification fires at once; and threshold breaches are evaluated after the load and routed to the owner group.

The loading task never decides who is paged. A separate SQL task, dq_evaluate_thresholds, is the last task of each job, with run_if: ALL_DONE so failed runs are counted too:

- task_key: dq_evaluate_thresholds
  depends_on: [{ task_key: set_status_log }]
  run_if: ALL_DONE
  sql_task:
    warehouse_id: ${var.warehouse_id}
    file: { path: ../src/dq/evaluate_thresholds.sql }

It records a breach only when every run in the window is in breach, and a MERGE on threshold and run means a re-run never records it twice. Each owner group then gets a Databricks SQL alert on its open breaches, deployed as a bundle resource:

resources:
  alerts:
    dq_breach_erp:
      display_name: "[${bundle.target}] DQ breach - ERP engineering"
      warehouse_id: ${var.warehouse_id}
      query_text: >
        SELECT COUNT(*) AS open_breaches
        FROM `${var.catalog}`.dq.threshold_breach
        WHERE owner_group = 'dp-${var.env}-erp-engineers' AND notified_at IS NULL
      evaluation:
        comparison_operator: GREATER_THAN
        source: { name: open_breaches, display: open_breaches }
        threshold: { value: { double_value: 0 } }
        notification:
          subscriptions:
            - destination_id: ${var.dq_destination_id}
      schedule:
        quartz_cron_schedule: "0 */15 * * * ?"
        timezone_id: Europe/Prague

After a notification, notified_at is written back, so an alert that was never sent is itself visible; an unacknowledged breach escalates after an agreed number of hours. One more alert per quarantine table watches the age of the oldest NEW row — quarantine that nobody empties is data loss with extra steps.

Line 3: Monitoring That Never Gates

The runner checks only what someone wrote down. Monitoring finds what nobody predicted: drift in distributions, null rates and volumes, and tables that stopped updating.

  • Data profiling on Gold — a time-series profile on each fact (on the business date) and a snapshot profile on each dimension, with metric tables in dq, declared as bundle resources and scheduled after Gold publication. SQL alerts on the drift metrics go to the owner group.
  • Anomaly detection per schema — freshness and completeness on Bronze, Silver and Gold without a rule per table, as an independent check next to the FRESHNESS and ROW_COUNT rules.

Monitoring never gates a job. A finding becomes a gate only when it is promoted to a rule in dq.rules.

The Scorecard

One AI/BI dashboard over the run summary, the violation log, the quarantine tables and the monitor metrics. Consumers get SELECT on scorecard views only.

-- scorecard per table and quality dimension, last 30 days
SELECT target_table, dimension,
       ROUND(100.0 * SUM(rows_checked - rows_failed) / NULLIF(SUM(rows_checked), 0), 3) AS pass_rate_pct,
       COUNT_IF(status <> 'PASSED') AS failed_executions
FROM dq.violation_log
WHERE check_timestamp >= current_date() - INTERVAL 30 DAYS
GROUP BY ALL ORDER BY target_table, dimension;

Because each rule has a dimension, "the trade data is complete but not timely" is a query, not an investigation.

Operating It

SituationWhat to do
Daily checkEvery in-scope task has a run summary for today; no unacknowledged breach; quarantine backlog below threshold
Job failed with DQFailureRead the failing rule ids; decide whether the data or the rule is wrong; fix the source and repair-run, or fix the rule through a pull request. Never disable a rule in production by hand
Threshold breachAcknowledge, investigate with the scorecard and quarantine, record the resolution
ERROR resultA rule no longer evaluates, usually after a schema change — fix it in the seed
Drift alertInvestigate; if it should gate future loads, add a rule
Bad Gold publication found laterRoll back with Delta time travel
DESCRIBE HISTORY finance_gold.fact_profit_and_loss;   -- match versions to dq.run_summary
RESTORE TABLE finance_gold.fact_profit_and_loss TO VERSION AS OF 412;

VACUUM retention on Gold must cover the agreed rollback window, or the version you need is gone.

During a migration, a daily parity job writes one row per measure, test case and reference system to dq.parity_* tables — never into Gold — and an out-of-tolerance row is a breach routed like any other.

Definition of Done

  • A migrated object is done only when its rules are in the seed, each rule has a passing and a failing test row, and its results appear in dq.run_summary.
  • A Gold serving view is certified only when its rules are registered, its failure behaviour is FAIL, its freshness rule and threshold are set, and its scorecard has been green for the agreed number of runs.

Acceptance checklist for the framework:

  • dq objects deployed by CI in every environment; no human MODIFY on dq in production
  • Every Silver and Gold write path calls apply_dq (checked in CI)
  • Schema enforcement on; constraints present before first load; dq_flags on every Silver table
  • Every rule has a dimension, an owner group and two test rows
  • Every quarantined entity has its quarantine table, protected like its target, with a backlog alert
  • dq_evaluate_thresholds is the last task of every job, with run_if: ALL_DONE
  • Alerts and job failure notifications reach each owner group
  • Profiling on Gold and anomaly detection on every schema, with nothing gating on them
  • Gold thresholds and parity tolerances carry approved_by

Conclusion

The framework rests on a few ideas: rules are data seeded from Git, one runner sits between every transformation and its write, every row either passes, is flagged, is quarantined or stops the load, evidence is written before anything fails, alerts go to groups rather than people, and monitoring informs but never blocks. The result is a platform where adding a check is a pull request, a bad load never reaches Gold, and data quality per table and dimension is a dashboard rather than a guess.

Radek Řezáč • Senior Lead Data Engineer • © 2026