Lakeflow Declarative Pipelines
Declare streaming tables and materialized views, enforce expectations, and apply ordered changes with AUTO CDC.
Core idea
In a normal job you write imperative steps ("read, transform, write, in this order"). In a declarative pipeline you define datasets, and the pipeline builds a DAG from their references, runs them in the right order, manages checkpoints, and records lineage and quality metrics.
| Dataset | Use |
|---|---|
| Streaming table | Incremental, append-style processing (ingestion with Auto Loader or Kafka, bronze and silver) |
| Materialized view | Results of a query, refreshed (incrementally where possible); joins and aggregates (silver and gold) |
| Temporary view | Intermediate step inside the pipeline, not published |
| Sink | Write a stream to Kafka, Event Hubs or an external Delta table |
SQL syntax
CREATE OR REFRESH STREAMING TABLE orders_bronze
COMMENT "Raw orders"
AS SELECT *, _metadata.file_path AS source_file
FROM STREAM read_files('/Volumes/main/raw/landing/orders/', format => 'json');
CREATE OR REFRESH STREAMING TABLE orders_silver (
CONSTRAINT valid_id EXPECT (order_id IS NOT NULL) ON VIOLATION DROP ROW,
CONSTRAINT valid_amount EXPECT (amount >= 0) ON VIOLATION FAIL UPDATE,
CONSTRAINT has_country EXPECT (country IS NOT NULL)
)
AS SELECT order_id, CAST(amount AS DECIMAL(10,2)) AS amount, country
FROM STREAM(orders_bronze);
CREATE OR REFRESH MATERIALIZED VIEW revenue_by_country
AS SELECT country, SUM(amount) AS revenue FROM orders_silver GROUP BY country;
Use STREAM(table) (or STREAM table) to read a dataset incrementally. Reading without STREAM is a batch read.
The video slides use Delta Live Tables syntax: CREATE OR REFRESH LIVE TABLE, the LIVE. prefix for upstream tables, and APPLY CHANGES INTO. Current syntax is CREATE OR REFRESH STREAMING TABLE or MATERIALIZED VIEW, plain table names, and AUTO CDC. STREAM(...) still means "read this source incrementally".
Python syntax
from pyspark import pipelines as dp # older code: import dlt, @dlt.table
from pyspark.sql import functions as F
@dp.table(comment="Raw orders")
def orders_bronze():
return (spark.readStream.format("cloudFiles")
.option("cloudFiles.format", "json")
.load("/Volumes/main/raw/landing/orders/"))
@dp.table
@dp.expect_or_drop("valid_id", "order_id IS NOT NULL")
@dp.expect_or_fail("valid_amount", "amount >= 0")
@dp.expect("has_country", "country IS NOT NULL")
def orders_silver():
return spark.readStream.table("orders_bronze").withColumn("amount", F.col("amount").cast("decimal(10,2)"))
@dp.materialized_view
def revenue_by_country():
return spark.read.table("orders_silver").groupBy("country").agg(F.sum("amount").alias("revenue"))
A function returning spark.readStream... under @dp.table makes a streaming table; returning a batch DataFrame makes a materialized view.
Expectations (data quality)
| Action | SQL | Python | Effect on bad rows |
|---|---|---|---|
| Warn (default) | EXPECT (cond) | @dp.expect | Kept in the target; violation counted in metrics |
| Drop | ... ON VIOLATION DROP ROW | @dp.expect_or_drop | Removed from the target; counted |
| Fail | ... ON VIOLATION FAIL UPDATE | @dp.expect_or_fail | The update fails; the transaction rolls back; manual fix needed |
@dp.expect_all, expect_all_or_drop, expect_all_or_fail take a dictionary of several rules. To quarantine bad rows instead of losing them, write a second table with the inverted condition. Quality metrics appear in the pipeline UI and the event log.
CDC with AUTO CDC
CREATE OR REFRESH STREAMING TABLE customers;
CREATE FLOW customers_cdc AS AUTO CDC INTO customers
FROM STREAM(customers_changes)
KEYS (customer_id)
APPLY AS DELETE WHEN op = 'DELETE'
SEQUENCE BY change_ts
COLUMNS * EXCEPT (op, change_ts)
STORED AS SCD TYPE 2; -- or SCD TYPE 1 (default)
Python: dp.create_auto_cdc_flow(target=..., source=..., keys=[...], sequence_by=..., stored_as_scd_type=2). Older name: APPLY CHANGES INTO / dlt.apply_changes. SEQUENCE BY handles out-of-order events. SCD Type 2 adds __START_AT and __END_AT columns.
Pipeline settings and modes
- Source code: one or more notebooks or files (SQL and Python can be mixed across files). In the pipeline settings these source notebooks or files are listed as the pipeline's libraries (source code). The Lakeflow Pipelines Editor is the multi-file IDE for pipelines.
- Target: default catalog and schema for published datasets, that is, the catalog and schema for outputs.
- Compute: serverless (recommended) or classic with enhanced autoscaling.
- Triggered mode: process available data, then stop (schedule it). Continuous mode: keep running for low latency, higher cost.
- Development mode: reuses the cluster between updates and does not retry, for fast iteration. Production mode: restarts the cluster on recoverable errors and retries.
- Full refresh: clears and recomputes all tables from scratch (streaming tables reprocess all source data). Avoid on sources that no longer hold history.
- Editions (classic): Core, Pro (CDC), Advanced (expectations).
Monitoring pipelines
The pipeline UI shows the DAG, each dataset's status, rows written, and expectation pass/fail counts. Everything is also in the event log, queryable with SELECT * FROM event_log(TABLE(main.silver.orders_silver)) or event_log('<pipeline-id>'): flow progress, data quality, lineage, cluster events, errors.
When an update fails, the pipeline UI shows which dataset (table) and flow failed, the error message with the failing line of source code, and the stage, so you do not trace notebook dependencies by hand. The same errors are in the event log.
Protect a downstream aggregate
A silver table accepts rows with nonnegative amounts. You want valid rows to continue flowing and a count of rejected records. Which expectation behavior fits?
Check your reasoning
Use ON VIOLATION DROP ROW. The pipeline emits valid records and records expectation metrics for the rows that failed.
Product reference
Spark Declarative Pipelines on Lakeflow in the Databricks documentation
Lakeflow Declarative Pipelines quiz
Answer 6 questions. Check each answer for an explanation.