Sub topic 11
Building all three layers as a declarative pipeline
This chapter assumes you can write the bronze, silver, and gold steps by hand: Auto Loader into a bronze table, a typed and deduplicated silver table, and a gold aggregate. It also assumes you know what a Structured Streaming checkpoint does. Here you collapse those separate scripts into one declarative pipeline, and you learn what the pipeline manages for you and where it can still go wrong.
Imperative versus declarative
In the earlier chapters you wrote the control flow yourself. You started a stream, set a checkpoint path, ran a MERGE, and scheduled the steps in the right order. This is imperative code: it says how to do the work.
A declarative pipeline works differently. You define each dataset as a query, and the pipeline engine works out the rest. It reads your definitions and builds a dependency graph. It then runs the datasets in order, manages checkpoints, and decides whether each update can be incremental. The product is called Delta Live Tables (DLT). It is now part of Lakeflow, and you may see it called Lakeflow Spark Declarative Pipelines. The Python module in this chapter is dlt. Newer releases offer a renamed module with the same ideas, so check which one your workspace documents.
The three layers map directly onto three dataset definitions.
The three definitions
This is the full pipeline source. It is a single Python file or notebook that you attach to a pipeline. You do not run it cell by cell.
import dlt
from pyspark.sql import functions as F
@dlt.table(comment="Raw orders as ingested")
def orders_bronze():
return (
spark.readStream.format("cloudFiles")
.option("cloudFiles.format", "json")
.load("/Volumes/main/sales/landing/orders/")
.withColumn("_ingested_at", F.current_timestamp())
)
@dlt.table(comment="Typed orders with valid keys")
@dlt.expect_or_drop("valid_order_id", "order_id IS NOT NULL")
@dlt.expect("positive_amount", "amount >= 0")
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",
)
)
@dlt.table(comment="Daily revenue for completed orders")
def daily_revenue_gold():
return (
dlt.read("orders_silver")
.where("status = 'completed'")
.groupBy(F.to_date("order_ts").alias("order_date"))
.agg(F.count("*").alias("orders"), F.sum("amount").alias("revenue"))
)Compare this with the hand-built version:
- No checkpoint or schema location. The pipeline stores streaming state and the inferred schema itself.
- No trigger. The pipeline update, or the pipeline's continuous mode, decides when to process data.
- No
toTablecall. The function name becomes the table name, and the return value is the table's contents. - No explicit ordering.
dlt.read_stream("orders_bronze")is both a read and a declared dependency.
Streaming tables and materialized views
The decorator @dlt.table creates different object types depending on what the function returns.
| Function returns | Object created | Behavior |
|---|---|---|
| A streaming DataFrame (`readStream`, `dlt.read_stream`) | Streaming table | Appends only new input rows on each update |
| A batch DataFrame (`dlt.read`, `spark.read`) | Materialized view | Recomputes the result, incrementally when the engine can |
In the example, bronze and silver are streaming tables. Each file is processed once, and old rows are not reprocessed. Gold is a materialized view. A daily aggregate changes whenever late rows land in an old day, so it is a query result, not an append-only log. The engine updates it for you and avoids a full rebuild when it can.
This split matches the layers' roles. Bronze and silver are about moving new records forward. Gold is about answering a question over the whole silver table.
Expectations: warn, drop, or fail
An expectation is a named SQL condition attached to a dataset. It is the pipeline's version of the quality rules from the silver chapter. You choose what happens to rows that violate it.
| Decorator | Violating rows | Update | Use when |
|---|---|---|---|
| `@dlt.expect` | Kept | Continues, violations counted | The rule is a signal, not a blocker |
| `@dlt.expect_or_drop` | Removed | Continues, drops counted | Bad rows would corrupt downstream joins or aggregates |
| `@dlt.expect_or_fail` | None written | Fails | Any violation means upstream is broken |
In the example, a null order_id is dropped because silver needs a key. A negative amount is only recorded, because refunds might legitimately appear and you want to see them before deciding.
The pipeline records pass and fail counts for every expectation in its event log. You can query them for the silver table like this (adjust the table name to your pipeline's target schema):
SELECT
timestamp,
exp.name,
exp.dataset,
exp.passed_records,
exp.failed_records
FROM (
SELECT
timestamp,
explode(
from_json(
details:flow_progress.data_quality.expectations,
'array<struct<name:string,dataset:string,passed_records:bigint,failed_records:bigint>>'
)
) AS exp
FROM event_log(TABLE(main.silver.orders_silver))
WHERE event_type = 'flow_progress'
)
WHERE exp.name IS NOT NULL
ORDER BY timestamp DESCDeduplication in a pipeline
The example silver table keeps every row. It has no deduplication, and the hand-built silver step had a MERGE. This is the most common gap when people port a notebook flow to a pipeline.
You cannot write a MERGE inside a dataset function, because the function only returns a query. The declarative replacement is change data capture (CDC) processing, exposed as dlt.apply_changes (also called AUTO CDC in newer releases). It takes a target streaming table, a source, the key columns, and an ordering column. It then applies the "latest record per key wins" logic for you.
import dlt
dlt.create_streaming_table("orders_silver_current")
dlt.apply_changes(
target="orders_silver_current",
source="orders_silver",
keys=["order_id"],
sequence_by="order_ts",
stored_as_scd_type=1,
)Here order_ts stands in for "which version is newer". Use an ordering column that really reflects event order. If you sequence by ingestion time and a file arrives late, the old version overwrites the new one.
In this layout orders_silver becomes a validated staging table and orders_silver_current is the deduplicated table that gold reads. Point daily_revenue_gold at orders_silver_current when you use this pattern.
Creating and running the pipeline
You attach the source code to a pipeline in the workspace, and the pipeline configuration holds the operational choices:
- Source code. The notebook or file with the definitions above.
- Default catalog and schema. Unqualified dataset names are published here. You can also use fully qualified names, such as
main.silver.orders_silver, so that each layer lands in its own schema from the layout chapter. - Mode. Triggered mode processes available data and stops. Continuous mode keeps running and lowers latency, at the cost of a cluster that never shuts down.
- Compute. Serverless is simplest. Otherwise you configure a cluster and its size.
- Development or production. Development mode reuses compute and does not retry on failure, which makes the edit-and-run cycle faster.
Run a validation first. It checks the graph, the references, and the syntax without processing data, so a typo in a dataset name fails in seconds.
Common errors
- Running the notebook directly. Calling a pipeline notebook on a normal cluster does not build tables.
import dltworks only inside a pipeline run, and the functions only declare datasets. - Using
dlt.readwhere you need streaming. Reading bronze withdlt.readmakes silver a materialized view that recomputes from all of bronze. Usedlt.read_streamfor append-style layers. - Side effects in dataset functions. Writes,
display()calls, and.collect()inside a dataset function make results unpredictable, because the engine may call the function more than once while planning. Keep functions pure queries. - Two datasets with the same name. The second definition fails the update. Remember that the function name is the table name.
- Expecting a full refresh to be harmless. A full refresh of a streaming table clears its state and reprocesses everything. For bronze, where source files may have been deleted from the landing volume, that can lose history. Protect bronze tables from full refresh with the table property
pipelines.reset.allowed = false. - Treating
expectas enforcement.@dlt.expectonly counts violations. Rows still flow to gold.
What the pipeline does not replace
A pipeline manages the data flow, but the surrounding design choices are still yours:
- Permissions are Unity Catalog grants, the same as before. The pipeline owner's rights decide what the pipeline can create.
- Scheduling is still needed for triggered pipelines. A job can run the pipeline on a schedule, alongside other tasks.
- Maintenance such as optimization and vacuuming is largely automated for pipeline-managed tables, but you should still check that it runs.
The next chapter covers how to schedule the pipeline and combine it with other tasks.
Exercise
Your silver table, defined with @dlt.table and dlt.read("orders_bronze"), takes longer on every update, and each run reprocesses all historical orders. Explain the cause and give the fix. Then say which decorator you would add to fail the update if any row has a null customer_id.
Show answer
dlt.read returns a batch DataFrame, so silver is a materialized view that recomputes from the whole bronze table. Change the read to dlt.read_stream("orders_bronze") so silver becomes a streaming table that processes only new bronze rows. To fail the update when any customer_id is null, add @dlt.expect_or_fail("valid_customer_id", "customer_id IS NOT NULL") to the silver function.
Exercise
A teammate adds @dlt.expect("valid_order_id", "order_id IS NOT NULL") to silver and is surprised that gold revenue still includes rows with null order IDs. What happened, and what change gives the behavior they wanted?
Show answer
@dlt.expect only records violations in the event log and keeps the rows. To remove the rows before they reach gold, use @dlt.expect_or_drop("valid_order_id", "order_id IS NOT NULL").