Sub topic 9
Enforcing data quality between layers
This chapter assumes you can read the bronze and silver code from the earlier chapters. You should know what MERGE does, and you should have seen a PySpark DataFrame and a Delta table. Here you decide what happens when a row breaks a rule on its way from bronze to silver.
Where quality rules belong
Bronze stores data as it arrived, so it should accept almost anything. Rejecting a row at ingestion means losing evidence of what the source sent. Silver is where data becomes trustworthy, so silver is where you enforce rules. Gold then inherits that trust and only needs checks on its own business logic, such as "revenue is never negative after aggregation."
A data quality rule is a boolean SQL condition that every row should satisfy. Examples are order_id IS NOT NULL and amount >= 0. The rule itself is simple. The real decision is what to do with a row that fails.
Three failure behaviors
| Behavior | What happens to a failing row | Use when |
|---|---|---|
| Warn | The row is kept. The violation is counted in metrics. | The rule is a soft signal, or you are still learning what the data looks like. |
| Drop | The row is removed from the output. The drop is counted. | Bad rows are expected and a missing row is cheaper than a wrong one. |
| Fail | The update stops and the target is not changed. | A violation means something upstream is broken and downstream consumers must not see partial data. |
Pick the weakest behavior that still protects consumers. Failing is the safest option, but it can stop a whole pipeline over one malformed row. Dropping keeps the pipeline running, but it can hide a problem. Do not combine a drop with a metric nobody reads.
Expectations in a declarative pipeline
In a declarative pipeline (Delta Live Tables, now part of Lakeflow), a rule is called an expectation. You attach expectations to a table with decorators. Each one has a name and a condition, and the decorator you choose sets the behavior.
import dlt
from pyspark.sql import functions as F
@dlt.table(comment="Typed orders with valid keys")
@dlt.expect("positive_amount", "amount >= 0")
@dlt.expect_or_drop("valid_order_id", "order_id IS NOT NULL")
@dlt.expect_or_fail("known_status", "status IN ('placed','completed','cancelled','refunded')")
def orders_silver():
return (
dlt.read_stream("orders_bronze")
.select(
"order_id",
"customer_id",
F.col("order_ts").cast("timestamp").alias("order_ts"),
F.col("amount").cast("decimal(12,2)").alias("amount"),
"status",
)
)The three decorators map to the three behaviors:
dlt.expectwarns. Failing rows are written, and the violation count is recorded.dlt.expect_or_dropremoves failing rows before they reach the table.dlt.expect_or_failstops the update with an error as soon as one row fails. The table keeps its previous contents.
When several rules share a behavior, group them in a dictionary and use dlt.expect_all, dlt.expect_all_or_drop, or dlt.expect_all_or_fail. This keeps the rules in one place where you can review them or load them from a config table.
rules = {
"valid_order_id": "order_id IS NOT NULL",
"valid_customer": "customer_id IS NOT NULL",
}
@dlt.table
@dlt.expect_all_or_drop(rules)
def orders_checked():
return dlt.read_stream("orders_bronze")Databricks records pass and fail counts for every expectation in the pipeline event log. It also shows them in the pipeline UI. This is how a warning turns into something you can watch. A warn-only rule is useful only if someone alerts on its metric.
Enforcing rules without a declarative pipeline
Not every silver step is a declarative pipeline. A notebook with MERGE still has two built-in tools and one pattern you can write yourself.
Delta constraints
Delta tables support NOT NULL and CHECK constraints. They behave like the fail option. A write that violates one is rejected as a whole.
ALTER TABLE main.silver.orders ALTER COLUMN order_id SET NOT NULL;
ALTER TABLE main.silver.orders
ADD CONSTRAINT positive_amount CHECK (amount >= 0);Adding a constraint validates the rows already in the table. If any existing row violates it, the ALTER statement fails, and you must clean the data first. Constraints are a good last line of defense because they apply to every writer, not only your pipeline. They cannot warn or drop, though.
A quarantine table
Dropping rows silently discards information you may need later. A quarantine table keeps the rejected rows, together with the reason, so you can inspect them or replay them after a fix. This code does that for a batch step:
from pyspark.sql import functions as F
rules = {
"valid_order_id": "order_id IS NOT NULL",
"positive_amount": "CAST(amount AS DECIMAL(12,2)) >= 0",
}
# Treat NULL as a failure: coalesce turns an unknown result into false.
passes = " AND ".join(f"coalesce({cond}, false)" for cond in rules.values())
bronze = spark.table("main.bronze.orders")
good = bronze.where(passes)
failed_rules = F.array_compact(F.array(*[
F.when(~F.coalesce(F.expr(cond), F.lit(False)), F.lit(name))
for name, cond in rules.items()
]))
bad = (
bronze.where(f"NOT ({passes})")
.withColumn("_failed_rules", failed_rules)
.withColumn("_quarantined_at", F.current_timestamp())
)
bad.write.mode("append").saveAsTable("main.silver.orders_quarantine")
good.createOrReplaceTempView("orders_clean")The MERGE from the silver chapter can then read from orders_clean instead of main.bronze.orders. The _failed_rules column records which rules each row broke, so a later query such as "which rule rejects the most rows?" is a plain GROUP BY over explode(_failed_rules).
Choosing what to check
Rules fall into a few families. Covering each family once catches most real problems.
- Completeness: key columns are not null, required fields are present.
- Validity: values fall in an allowed range or set, such as
amount >= 0or a known list of statuses. - Uniqueness: one row per business key. The
MERGEdeduplication handles this, and a rule can confirm it afterward. - Consistency: related columns agree, for example
completedorders always have a non-nullorder_ts. - Volume and freshness: the batch is not empty and is not wildly smaller than yesterday's. These are table-level checks, so a row-level expectation cannot express them. Use a query in a job task that fails when the count looks wrong.
Common errors
- Putting strict rules in bronze. A drop or fail at ingestion loses or blocks raw data. Keep bronze permissive so you can replay.
- Forgetting NULL semantics. A condition that evaluates to NULL is not true, so it counts as a failure in expectations. It can also slip through hand-written filters, as the warning above shows.
- Drop without monitoring. If a source change makes 40% of rows fail
valid_order_id, a drop rule will hide the loss. Alert on the drop count or the failure ratio. - Fail on a rule that should be soft. One bad row in a million stops the whole update. Use drop with a quarantine instead.
- Rules that depend on other rows. Expectations and constraints judge each row alone. Checks such as "no duplicate
order_id" or "row count within 20% of yesterday" need a separate query. - Adding a
CHECKconstraint to a dirty table. The statement fails until existing data is repaired.
Exercise
An orders feed occasionally contains rows with a null order_id. Finance wants those rows kept for investigation, but they must never reach the silver table that dashboards use. Which behavior and mechanism would you choose, and why not the other two behaviors?
Show answer
Use a drop-style rule (expect_or_drop in a declarative pipeline) together with a quarantine table that stores the rejected rows and the rule they failed. Warn would let the null-key rows into silver, which breaks the dashboards. Fail would stop the whole update because of a few bad rows, which is too strong for an expected, recoverable problem. The quarantine table preserves the rows for Finance, and a metric or alert on the quarantine volume keeps the drops visible.
Exercise
You run ALTER TABLE main.silver.orders ADD CONSTRAINT positive_amount CHECK (amount >= 0) and it fails. What is the most likely cause, and what do you do next?
Show answer
Adding a CHECK constraint validates the rows already in the table, so some existing rows have a negative amount. Query for them with SELECT * FROM main.silver.orders WHERE amount < 0. Then fix or remove them, for example by correcting the source and re-running the silver step, or by moving them to a quarantine table. After that, run the ALTER statement again.