DEV Community

Danny C.
Danny C.

Posted on

Lakeflow Pipelines Deep Dive

Lakeflow Pipelines Deep Dive

Speaker Information

  • Taranpreet Singh Grover
  • Sr. Specialist Solutions Architect

Introduction to Lakeflow Pipelines

Modern software engineering for ETL processing.

Lakeflow Pipeline is the first ETL framework that uses a simple declarative approach to building reliable data pipelines. These pipelines automatically manages your infrastructure at scale so data analysts and engineers can spend less time on tooling and focus on getting value from data.

  • Accelerate ETL development
  • Automatically manage your infrastructure
  • Have confidence in your data
  • Simplify batch and streaming

Declarative Programming

Say what should be done, not how to do it.

Spark Imperative Program Example

def upsertToDelta (microBatchOutputDF: DataFrame, batchId: Long) {
  microBatchOutputDF
    .groupBy("key")
    .agg (max_by("ts", struct("*").alias ("row")))
    .select("row.*")
    .createOrReplaceTempView("updates")

  microBatchOutputDF.sparkSession.sql(s"""
    MERGE INTO cdc_data_raw t
    USING updates s
    ON s.key = t.key
    WHEN MATCHED AND s.is_delete THEN
      UPDATE SET DELETED_AT=now()
    WHEN MATCHED THEN UPDATE SET
      A = CASE WHEN s.ts > t.ts THEN s.a ELSE t.a END,
      B = CASE WHEN s.ts > t.ts THEN s.b ELSE t.b END
    WHEN NOT MATCHED THEN INSERT *
  """)
}

cdcData.writeStream
  .foreachBatch (upsertToDelta _)
  .outputMode ("append")
  .start()

Enter fullscreen mode Exit fullscreen mode

Lakeflow Pipeline Declarative Program Example

CREATE FLOW cdc_flow
AS AUTO CDC INTO target_data
FROM source_data
KEYS (id)
SEQUENCE BY ts
APPLY AS DELETE WHEN is_deleted

Enter fullscreen mode Exit fullscreen mode

Streaming Tables and Flows

Streaming tables process files or events in a message bus (like Kafka) or other streaming data.

Core Characteristics

  • Incremental processing
  • Exactly once processing (handles each output exactly once over multiple refreshes)
  • Low latency

How Queries Work Against a Stream

  • Time sequence involves t0, t1, and t2.
  • Input Row 1: {"name": "Zach"}
  • Input Row 2: {"name": "Zara"}
  • Input Row 3: {"name": "Zee"}
  • Input Row 4: {"name": "Zev"}
  • Input Row 5: {"name": "Zoe"}
  • Query variant 1: SELECT LOWER (name) FROM data
  • Query variant 2: SELECT UPPER (name) FROM data
  • Output sequence: zach, zara, zee, zev, ZOE

Defining Streaming Tables
Streaming tables are defined and updated by a single Lakeflow pipeline. When creating a pipeline, you explicitly define streaming tables in the source code. Note: Unlike Structured streaming, you do not need to use spark.writeStream. Lakeflow pipelines take care of writing streaming tables and materialized views for you.

Python API:

import dlt

@dlt.table
def customers_bronze():
    return (spark.readStream.format("cloudFiles")
        .option("cloudFiles.format", "json")
        .option("cloudFiles.inferColumnTypes", "true")
        .load("/Volumes/path/to/files")
    )

Enter fullscreen mode Exit fullscreen mode

SQL API:

CREATE OR REFRESH STREAMING TABLE
customers_bronze
AS SELECT * FROM STREAM read_files(
    "/volumes/path/to/files",
    format => "json"
);

Enter fullscreen mode Exit fullscreen mode

Flows
Data is processed through flows. Each flow consists of a query and, typically, a target. The flow processes the query, either as a batch, or incrementally as a stream of data into the target.

Append Flows
Multiple flows can write to a single target using append flows.

@dlt.append_flow(target = "kafka_target")
def topic1():
    return (spark.readStream.format("kafka")
        .option("kafka.bootstrap.servers", "host1:port1,...")
        .option("subscribe", "topic1")
        .load())

@dlt.append_flow(target = "kafka_target")
def topic2():
    return (spark.readStream.format("kafka")
        .option("kafka.bootstrap.servers", "host1:port1,...")
        .option("subscribe", "topic2")
        .load())

Enter fullscreen mode Exit fullscreen mode

Append-Only Behavior Constraint
Streaming tables can only process append-only data. That is, streaming tables expect only new rows of data to show up in the streaming source. Any other operation, such as updating or deleting any record from a source table used for streaming, is not supported and breaks the stream.

  • Source to Streaming Table (Apply Changes, Group By, Delete) is NOT supported.

Change Data Capture (CDC)

Stream change records (inserts, updates, deletes) from any supported data source, cloud storage, or DBFS. This translates data sources (Streaming sources, Cloud object stores, Structured data, Unstructured data, Semi-structured data, Data migration services) from Bronze layers to Silver layers via UPSERT via CDC.

  • Simple, declarative APPLY CHANGES INTO API
  • Handles out-of-order events
  • Schema evolution
  • Supports both SCD type 1 & SCD type 2

AUTO CDC FLOW (Formerly Apply Changes)
Previously, the MERGE INTO statement was commonly used for processing CDC records. However, MERGE INTO can produce incorrect results because of out-of-sequence records or requires complex logic to re-order records. AUTO CDC is used to process changes from a change data feed (CDF).

import dlt
from pyspark.sql.functions import col, expr

@dlt.view
def users():
    return spark.readStream.table("cdc_data.users")

dlt.create_streaming_table("target")

dlt.create_auto_cdc_flow(
    target = "target",
    source = "users",
    keys = ["userId"],
    sequence_by = col("sequenceNum"),
    apply_as_deletes = expr("operation = 'DELETE'"),
    apply_as_truncates = expr("operation = 'TRUNCATE'"),
    except_column_list = ["operation", "sequenceNum"],
    stored_as_scd_type = 1
)

Enter fullscreen mode Exit fullscreen mode

AUTO CDC FROM SNAPSHOT
Used to process changes in database snapshots.

Example:

import dlt

@dlt.view(name="source")
def source():
    return spark.read.table("delta_table")

dlt.create_streaming_table("target")

dlt.create_auto_cdc_from_snapshot_flow(
    target="target",
    source="source",
    keys=["key"],
    stored_as_scd_type=2
)

Enter fullscreen mode Exit fullscreen mode

Snapshot progression example:

  • Snapshot at timestamp, stored in //filename1.csv contains Key, TrackingColumn, and NonTrackingColumn data.
  • Record 1: 1, a1, b1
  • Record 2: 2, a2, b2
  • Record 3: 4, a4, b4
  • Snapshot at timestamp + 5, stored in //filename2.csv contains Key, TrackingColumn, and NonTrackingColumn data.
  • Record 4: 2, a2_new, b2
  • Record 5: 3, a3, b3
  • Record 6: 4, a4, b4_new

Resulting tracked state with SCD Type 2:

  • Resulting tracked state includes Key, TrackingColumn, NonTrackingColumn, _START_AT, and END_AT columns.
  • State Record 1: 1, a1, b1, 1, 2
  • State Record 2: 2, a2, b2, 1, 2
  • State Record 3: 2, a2_new, b2, 2, null
  • State Record 4: 3, a3, b3, 2, null
  • State Record 5: 4, a4, b4_new, 1, null

Python API handling dynamic snapshots:

import dlt

def exist(file_name):
    # Storage system-dependent function that returns
    # true if file_name exists, false otherwise
    pass

def next_snapshot_and_version(latest_snapshot_version):
    latest_snapshot_version = latest_snapshot_version or 0
    next_version = latest_snapshot_version + 1
    file_name = "dir_path/filename_" + str(next_version) + ".csv"
    if (exist(file_name)):
        return (spark.read.load(file_name), next_version)
    else:
        return None

dlt.create_streaming_live_table("target")
dlt.create_auto_cdc_from_snapshot_flow(
    target = "target",
    source = next_snapshot_and_version,
    keys = ["Key"],
    stored_as_scd_type = 2,
    track_history_column_list = ["TrackingCol"]
)

Enter fullscreen mode Exit fullscreen mode

Materialized Views (MVs)

MVs perform complex transformations for ETL and accelerate end-user queries for dashboards/BI.

Benefits:

  • Accelerate queries/dashboards: Much faster to query data that is pre-computed vs querying base tables.
  • Improve data freshness: MVs can be incrementally refreshed with Enzyme when new data arrives, avoiding time-consuming full recomputes.
  • Simple ETL: Transform and process data in a declarative way.
CREATE MATERIALIZED VIEW customer_orders
AS
SELECT
customers.name,
sum(orders.amount),
orders.orderdate
FROM orders
LEFT JOIN customers ON
orders.custkey = customers.c_custkey
GROUP BY
name,
orderdate;

Enter fullscreen mode Exit fullscreen mode

Incremental Refresh
When running updates on materialized views using serverless pipelines, many queries can be incrementally refreshed. Incremental refreshes save compute costs by detecting changes in the data sources used to define the materialized view and incrementally computing the result. Sources can include Streaming Tables, Materialized Views, and Delta Tables.

Configuration snippet:

ALTER TABLE <table-name> SET
TBLPROPERTIES (
delta.enableDeletionVectors = true,
delta.enableRowTracking = true,
delta.enableChangeDataFeed = true);

Enter fullscreen mode Exit fullscreen mode

Materialized views make a best-effort attempt to incrementally refresh results for supported operations. Some changes in data sources require a full refresh.

  • FULL_RECOMPUTE: Incremental refresh is No. The materialized view was fully recomputed.
  • NO_OP: Incremental refresh is Not applicable. The materialized view was not updated because no changes to the base table were detected.
  • ROW_BASED, PARTITION_OVERWRITE, WINDOW_FUNCTION, APPEND_ONLY, GROUP_AGGREGATE, GENERIC_AGGREGATE: Incremental refresh is Yes. The materialized view was incrementally refreshed using the specified technique.

Streaming Tables vs. Materialized Views Comparison

  • Primary Purpose (Streaming Tables): Real-time or near-real-time data ingestion and processing
  • Primary Purpose (Materialized Views): Fast query performance on precomputed, cached results
  • Data Handling (Streaming Tables): Processes continuous, append-only data streams as data arrives
  • Data Handling (Materialized Views): Stores results of a query at the time of last refresh (not always real-time)
  • Refresh Mechanism (Streaming Tables): Continuously updates as new data arrives
  • Refresh Mechanism (Materialized Views): Refreshed on a schedule or manually; can be incremental or full
  • Latency (Streaming Tables): Low latency; ideal for immediate analytics and event-driven workloads
  • Latency (Materialized Views): Not designed for ultra-low latency; refresh intervals are seconds to minutes
  • Best Use Cases (Streaming Tables): IoT, log/event streaming, real-time dashboards, continuous data ingestion, CDC
  • Best Use Cases (Materialized Views): BI dashboards, reporting, complex aggregations, compliance, slow queries
  • Query Performance (Streaming Tables): Good for current data; not optimized for repeated, complex queries
  • Query Performance (Materialized Views): Optimized for repeated queries; precomputed results for fast access
  • Scalability (Streaming Tables): Highly scalable for high-throughput, high-velocity data
  • Scalability (Materialized Views): Scalable for large query workloads; less suited for very high-velocity data
  • Data Freshness (Streaming Tables): Always up-to-date with latest incoming data
  • Data Freshness (Materialized Views): Up-to-date as of last refresh
  • Typical Data Sources (Streaming Tables): Message buses (Kafka, Kinesis), cloud storage, sensors, API feeds, Delta tables, Streaming Tables (append-only)
  • Typical Data Sources (Materialized Views): Delta tables, batch tables, other materialized views
  • Transformation Complexity (Streaming Tables): Supports stateless and stateful (windowed) streaming transformations
  • Transformation Complexity (Materialized Views): Supports complex aggregations, joins, and denormalizations
  • APPLY_CHANGES Support (Streaming Tables): Yes. Enables declarative, reliable change data capture (CDC) using APPLY CHANGES or APPLY CHANGES FROM SNAPSHOT APIs.
  • APPLY_CHANGES Support (Materialized Views): Not applicable.
  • CDC Handling (Streaming Tables): Handles inserts, updates, and deletes from change data feeds (CDF) with SCD Type 1 and Type 2 support; manages out-of-order events automatically.
  • CDC Handling (Materialized Views): Not designed for CDC or streaming change feeds.
  • When to Use (Streaming Tables): When you need real-time insights, event monitoring, or continuous data updates including CDC scenarios
  • When to Use (Materialized Views): When you need fast query results, complex analytics, or frequent reporting

Typical Pipeline Architecture

  • Bronze Layer: customers_raw (Streaming Table), orders_raw (Streaming Table)
  • Silver Layer: customers_clean (Streaming Table), orders_clean (Streaming Table)
  • Gold Layer: customer_orders (Materialized View)

Data Quality and Schema Management

Data Quality Expectations
Define data quality and integrity controls within the pipeline with data expectations. Address data quality errors with flexible policies: fail, drop, alert, quarantine(future). All data pipeline runs and quality metrics are captured, tracked and reported.

  • Warn (Default) - SQL syntax: EXPECT
  • Warn (Default) - Python syntax: dlt.expect
  • Warn (Default) - Result: Invalid records are written to the target.
  • Drop - SQL syntax: EXPECT ... ON VIOLATION DROP ROW
  • Drop - Python syntax: dlt.expect_or_drop
  • Drop - Result: Invalid records are dropped before data is written to the target. The count of dropped records is logged alongside other dataset metrics.
  • Fail - SQL syntax: EXPECT ... ON VIOLATION FAIL UPDATE
  • Fail - Python syntax: dlt.expect_or_fail
  • Fail - Result: Invalid records prevent the update from succeeding. Manual intervention is required before reprocessing. This expectation causes a failure of a single flow and does not cause other flows in your pipeline to fail.

Examples:

@dlt.table
@dlt.expect("valid_customer_age", "age BETWEEN 0 AND 120")
def customers():
    return spark.readStream.table("datasets.samples.raw_customers")

Enter fullscreen mode Exit fullscreen mode
/* Stage 1: Bronze Table drop invalid rows */
CREATE STREAMING TABLE fire_account_bronze AS
(CONSTRAINT valid_account_open_dt EXPECT (acconut_dt is not
null and (account_close_dt > account_open_dt)) ON VIOLATION DROP
ROW)
COMMENT "Bronze table with valid account ids"
SELECT * FROM fire_account_raw

Enter fullscreen mode Exit fullscreen mode

Key Considerations for Data Quality

  • Because only streaming tables and materialized views support expectations, data quality metrics are supported only for these object types.
  • Materialized Views with expectations always go through FULL_RECOMPUTE.
  • Data quality metrics are not available when no expectations are defined on a query.
  • Data quality metrics are not available when a flow uses an operator that does not support expectations.
  • Data quality metrics are not available when the flow type, such as DLT sinks and AUTO CDC FROM SNAPSHOT, does not support expectations.
  • Data quality metrics are not available when there are no updates to the associated streaming table or materialized view for a given flow run.
  • For some cases, a COMPLETED flow might not contain metrics. Instead, metrics are reported in each micro-batch in a flow_progress event with the status RUNNING.

Schema Evolution Scenarios

  • Scenario - New columns are added: Output is automatically handled.
  • Scenario - Columns are deleted: Output shows the target streaming table will have the same number of columns as earlier.
  • Scenario - Data type change (Output): Null Type to any other type and upcasts from shorter to the wider data type for e.g. ShortInt to Int are handled automatically.
  • Scenario - Data type change (Solution): Other data type changes are rescued in __rescued_column in the target streaming table.
  • Scenario - Columns are renamed (Output): There will be a new column with the updated column name.
  • Scenario - Columns are renamed (Solution): Load the data in the bronze layer with the updated column and create a view on top for silver to accommodate. Possibly use coalesce to rename the column in the code.

GDPR / CCPA / RTBF Compliance

Handling Deletes in Streaming Tables

  • Option 1 - Delete from the source: DELETE FROM source WHERE email='kim@example.com'
  • Option 1 - Delete from streaming table: DELETE FROM streaming_table WHERE email='kim@example.com'
  • Option 1 - Update streaming table: spark.readStream.option("skipChangeCommits", "true").table("source")
  • Option 2 - Delete from the source: DELETE FROM source WHERE email='kim@example.com'
  • Option 2 - Delete from streaming table: DELETE FROM streaming_table WHERE email='kim@example.com'
  • Option 2 - Full refresh of streaming table: spark.readStream.table("source")

Handling Deletes in Materialized Views
Materialized views automatically handle deletions in sources. Hence, you do not have to do anything special to ensure that a materialized view does not contain data that has been deleted from a source. You must refresh a materialized view and run maintenance to ensure that deletions are completely processed.

For deletion vectors enabled Materialized Views:

  • Step 1 - Run a REORG statement with PURGE: Execute the following SQL command to rewrite files and physically purge soft-deleted records: REORG TABLE <materialized-view-name> APPLY (PURGE);
  • Step 2 - Wait for the data retention period to pass: By default, Delta Lake retains deleted files for seven days to support time travel and rollback. If needed, you can configure this period using the delta.deletedFileRetentionDuration table property.
  • Step 3 - Refresh the materialized view: Run a REFRESH command on the materialized view. Within 24 hours of the refresh, it will automatically run maintenance tasks, including the VACUUM operation physically removes the deleted files from storage.

Example Pipeline Case for GDPR

  • Bronze Layer: users_bronze (contains PII: email) Streaming table, clicks_bronze (contains PII: ip_address) Streaming table
  • Silver Layer: users_silver (populated via Apply Changes Into), clicks_silver (populated via Append), user_clicks_silver (joined stream)
  • Gold Layer: user_behavior_gold Materialized view, marketing_insights_gold Materialized view
  • Control Table: gdpr_requests (Delta table) drives the deletion logic.
  • Streaming sources: Delta CDF, Kafka, Kinesis, etc.

Development Best Practices

Development vs Production Mode

  • Development mode: Reuses a long-running cluster running for fast iteration. No retries on errors enabling faster debugging.
  • Production mode: Cuts costs by turning off clusters as soon as they are done (within 5 minutes). Escalating retries, including cluster restarts, ensure reliability in the face of transient issues.

Modularize Your Code with Configuration
Avoid hard coding paths, topic names, and other constants in your code. A pipeline's configuration is a map of key value pairs that can be used to parameterize your code. This improves code readability/maintainability and allows reusing code in multiple pipelines for different data.

SQL Example:

CREATE STREAMING TABLE data AS
SELECT * FROM read_files("${my_etl.input_path}", "json")

Enter fullscreen mode Exit fullscreen mode

Python Example:

@dlt.table
def data():
    input_path = spark.conf.get("my_etl.input_path")
    spark.readStream.format("cloudFiles").load(input_path)

Enter fullscreen mode Exit fullscreen mode

AI Assistant
Generate streaming tables and materialized views with an Assistant for data and analytics tasks. It learns from your data and workspace context, and helps users write, create, debug, explain and document Python and SQL code.

DevOps & CI/CD
Deploy with Asset Bundles (DABs) to enable source control, code review, testing, and CI/CD. Validate, deploy, and run DLT pipelines.

  • Data workers operate in a Local dev environment (project bundle) connected to version control (project repository) which drives CI/CD.
  • Workspaces span Development workspace (dev deployment), Staging workspace (staging deployment), and Production workspace (production deployment).
  • Users can do direct edits for items that aren't source controlled.
  • Users can manually deploy to see and test changes in dev.
  • Users can commit changes to source control.
  • Notifications trigger CI/CD.
  • Code and integration tests are deployed to staging.
  • Code is deployed to production after review and approval.
  • Configure service principals, kick off runs of jobs, and other tasks.

VSCode Integration
VSCode with Asset Bundles (DAB) uses a YAML-based format to specify and deploy notebooks, pipelines, and jobs across environments. Supports CLI or Git actions (e.g., $bundle validate, $bundle deploy -t prod).

Alternative Options

  • Python SDK: The Jobs Python API allows you to create, edit, and delete jobs.
  • Terraform Provider: The jobs resource can be used to create and manage Jobs with Terraform.
  • Jobs REST API: Low-level REST API allows you to manage Jobs programmatically.

Observability and Governance

Observability via Event Log
The event log contains all information related to a pipeline (data quality checks, progress, lineage). It can be viewed through the user interface, the API, or queried directly as a Delta Table.

SELECT
timestamp,
Double(details:cluster_resources.avg_num_queued_tasks) as queue_size
FROM
event_log_raw,
latest_update
WHERE
event_type = 'cluster_resources'
AND
origin.update_id = latest_update.id

Enter fullscreen mode Exit fullscreen mode

Data Governance (Unity Catalog Integration)

  • Row/column level security
  • Publish to multiple schemas
  • Change data feed from streaming tables
  • Supports Hive Metastore migration

Python Syntax Examples:

@dlt.table
def table_name():
    pass

@dlt.table(name="schema.name")
def func():
    pass

@dlt.table(name="catalog.schema.name")
def func():
    pass

Enter fullscreen mode Exit fullscreen mode

SQL Syntax Examples:

# fully qualified
CREATE MATERIALIZED VIEW catalog.schema.name

# partially qualified
CREATE MATERIALIZED VIEW schema.name

# single part name
CREATE MATERIALIZED VIEW name

Enter fullscreen mode Exit fullscreen mode

Data Lineage
Supports end-to-end lineage mapping, from Volumes through pipelines to Feature Stores.

Data Portability

Move and Undrop Tables
Easily move tables between pipelines. You can even undrop tables if they were accidentally removed.

ALTER STREAMING TABLE catalog.schema.foo
SET TBLPROPERTIES ("pipelines.pipelineId"="<destination-pipeline-id>");

DROP MATERIALIZED VIEW catalog.schema.bar;
UNDROP MATERIALIZED VIEW catalog.schema.bar;

Enter fullscreen mode Exit fullscreen mode

Pipelines Writing to Kafka or Delta Tables
The Sink API enables writing to destinations outside of the pipeline, such as Apache Kafka and external Delta tables. This simplifies building end-to-end data products across environments.

create_sink("my_sink",
"delta", {"tableName":
"catalog.schema.table"})

@append_flow(name = "flow",
target = "my_sink")
def flowFunc():
    return read_stream("xxx")

Enter fullscreen mode Exit fullscreen mode

Performance and Optimization

Powered by Delta Lake, pipelines provide best-in-class performance.

  • Efficient reads & writes with Liquid Clustering, Deletion Vectors & Predictive I/O.
  • Cheaper & faster query execution with Photon.
  • Incremental MV Refresh with Enzyme on Serverless.

Liquid Clustering
Fast, self-tuning, incremental, skew-resistant, flexible. It offers significant improvements in ingestion time and write amplification (bytes) compared to traditional Hive-style partitioning and ZORDER clustering. Supports both Python & SQL.

SQL API:

CREATE OR REFRESH STREAMING TABLE nyctaxi_trips_st
CLUSTER BY (pickup_zip)
AS SELECT * FROM STREAM(samples.nyctaxi.trips)

Enter fullscreen mode Exit fullscreen mode

Python API:

@dlt.table(
    name="nyctaxi_trips_st",
    cluster_by=["pickup_zip"]
)

Enter fullscreen mode Exit fullscreen mode

Compute Modes

  • Performance-optimized mode: Fast, performant compute startup and execution speed.
  • Standard mode: Disabling performance optimization gives you startup times similar to Classic infrastructure and reduces your cost. (Currently only applies to certain Serverless workloads).

Latency Improvements
Ongoing performance improvements have led to DAG performance improving by over 60%, showing a strong downward trend in End-to-End Latency across Large, Medium, and Small DAG sizes over time.

Top comments (0)