Why a declarative pipeline?
In lessons 6 and 7 we wrote a lot of plumbing: checkpoint paths, tableExists checks, MERGE code, the order of steps. Lakeflow Declarative Pipelines remove most of that. You write the medallion pipeline as a few table definitions, and Databricks handles the rest.
| You handled manually (lessons 6β7) | The pipeline handles |
|---|---|
| Run bronze, then silver, then gold | Builds a dependency graph and runs in order |
| Checkpoint locations | Managed automatically |
| Create table if it doesn't exist | Creates and updates tables |
| Count and quarantine bad rows | Expectations with quality metrics |
| SCD Type 2 MERGE trick | AUTO CDC with stored_as_scd_type=2 |
| Retries and cluster setup | Managed compute and automatic retries |
Two kinds of datasets
| Streaming table | Materialized view | |
|---|---|---|
| Processes | Each new input row once (append) | Whole query result, kept correct |
| Best for | Ingestion (bronze), append-style silver | Aggregations, joins, gold |
| Reads source with | spark.readStream / STREAM(...) | spark.read / normal SELECT |
| If an old source row changes | Not reprocessed | Result is refreshed |
There are also views (temporary, not stored) for intermediate steps, and sinks to write to outside systems like Kafka.
ShopKart's pipeline in Python
from pyspark import pipelines as dp
from pyspark.sql import functions as F
# BRONZE: Auto Loader, as a streaming table
@dp.table(comment="Raw orders, loaded as files arrive")
def bronze_orders():
return (spark.readStream
.format("cloudFiles")
.option("cloudFiles.format", "json")
.load("/Volumes/shopkart/raw/landing/orders/")
.withColumn("_ingested_at", F.current_timestamp()))
# SILVER: data quality rules decide what gets in
@dp.table(comment="Valid orders with amount")
@dp.expect_or_drop("has_customer", "customer_id IS NOT NULL")
@dp.expect_or_drop("positive_quantity", "quantity > 0")
@dp.expect("known_status", "status IN ('PLACED', 'DELIVERED', 'CANCELLED')") # warn only
def silver_orders():
return (spark.readStream.table("bronze_orders")
.withColumn("amount", F.col("quantity") * F.col("price")))
# GOLD: a materialized view, always correct
@dp.materialized_view(comment="Delivered revenue per day")
def gold_daily_revenue():
return (spark.read.table("silver_orders")
.filter("status = 'DELIVERED'")
.groupBy(F.to_date("order_ts").alias("order_date"))
.agg(F.sum("amount").alias("revenue")))The same pipeline in SQL
CREATE OR REFRESH STREAMING TABLE bronze_orders
AS SELECT *, current_timestamp() AS _ingested_at
FROM STREAM read_files('/Volumes/shopkart/raw/landing/orders/', format => 'json');
CREATE OR REFRESH STREAMING TABLE silver_orders (
CONSTRAINT has_customer EXPECT (customer_id IS NOT NULL) ON VIOLATION DROP ROW,
CONSTRAINT positive_quantity EXPECT (quantity > 0) ON VIOLATION DROP ROW,
CONSTRAINT known_status EXPECT (status IN ('PLACED', 'DELIVERED', 'CANCELLED'))
)
AS SELECT *, quantity * price AS amount
FROM STREAM(bronze_orders);
CREATE OR REFRESH MATERIALIZED VIEW gold_daily_revenue
AS SELECT to_date(order_ts) AS order_date, SUM(amount) AS revenue
FROM silver_orders
WHERE status = 'DELIVERED'
GROUP BY to_date(order_ts);πVolume files
π₯bronze_orders
streaming table
π₯silver_orders
streaming table + 3 expectations
π₯gold_daily_revenue
materialized view
Expectations: data quality built in
| Python | SQL | Failing rows |
|---|---|---|
| @dp.expect | EXPECT (...) | Kept; violation counted |
| @dp.expect_or_drop | ON VIOLATION DROP ROW | Dropped; counted |
| @dp.expect_or_fail | ON VIOLATION FAIL UPDATE | The update stops |
| @dp.expect_all_or_drop({...}) | (several constraints) | Many rules at once |
The pipeline UI shows, for every table, how many rows passed and failed each rule. That's your data quality dashboard for free.
CDC and SCD Type 2 in a few lines: AUTO CDC
CDC (change data capture) means receiving a stream of changes from a source database: inserts, updates and deletes. Applying them correctly (in order, with history) is hard by hand, as you saw in lesson 6. AUTO CDC (formerly APPLY CHANGES INTO) does it for you:
dp.create_streaming_table("silver_customers")
dp.create_auto_cdc_flow(
target="silver_customers",
source="bronze_customer_changes", # a streaming table of change events
keys=["customer_id"], # what identifies a customer
sequence_by=F.col("updated_at"), # which change is newer
stored_as_scd_type=2, # keep history (1 = overwrite)
)It adds __START_AT and __END_AT columns to track each version, and handles out-of-order events using sequence_by.
Running a pipeline
- Development mode: reuses compute and doesn't retry, so you iterate quickly. Production mode: restarts and retries on failure.
- Triggered: process what's new, then stop (schedule it with a job). Continuous: keep running for low latency.
- Full refresh: clear the tables and rebuild everything from source (careful with sources that no longer keep old data).
- Pipelines publish tables to a Unity Catalog catalog and schema you choose, so permissions and lineage from lesson 8 apply.
π― Interview questions on this topic
Try to answer out loud first, then tap to check.
Q1What is DLT / Lakeflow Declarative Pipelines?Fresher+
Q2Streaming table vs materialized view?1β3 yrs+
Q3How do you enforce data quality in Databricks pipelines?1β3 yrs+
Q4How do you implement SCD Type 2 in a declarative pipeline?1β3 yrs+
Q5When would you choose plain Structured Streaming + Jobs over declarative pipelines?3+ yrs+
Key takeaways
- βDeclare tables, not steps: the pipeline handles order, state and retries.
- βStreaming tables for ingestion, materialized views for gold.
- βExpectations give built-in data quality with metrics.
- βAUTO CDC replaces the hand-written SCD Type 2 MERGE.
Frequently asked questions
What is Delta Live Tables (DLT)?
DLT was Databricks' framework for declarative pipelines. It is now called Lakeflow Declarative Pipelines (and the core was open-sourced to Apache Spark as Spark Declarative Pipelines). Old code with import dlt still works; new code uses from pyspark import pipelines as dp.
What does declarative mean here?
You describe what each table should contain (a query), not the steps to build it. The framework works out the order, creates the tables, handles checkpoints, retries and incremental processing for you.
Streaming table or materialized view?
A streaming table processes each new input row once: ideal for ingestion and append-heavy silver. A materialized view stores the result of a query and is refreshed to stay correct even when source rows change: ideal for aggregates and gold.
What are expectations?
Data quality rules attached to a table, like customer_id IS NOT NULL. You choose what happens to failing rows: keep them and record the violation (warn), drop them, or fail the update. Results show up in the pipeline's quality metrics.
When should I NOT use declarative pipelines?
When you need full control over each step, complex custom logic per batch, or writes to many external systems. Then plain notebooks with Structured Streaming and Lakeflow Jobs are often simpler.
π§ Quick check: declarative pipelines
1. Which object fits an ingestion table fed by Auto Loader?
2. @dp.expect_or_drop("valid_qty", "quantity > 0") does what to bad rows?
3. Who decides the order tables are built in?
4. AUTO CDC (formerly APPLY CHANGES) helps with...
Checking your accessβ¦