Lakeflow Declarative Pipelines – Delta Live Tables (DLT)

Delta Live Tables (DLT) is the former name of what Databricks now calls Lakeflow Declarative Pipelines.

In other words: Lakeflow Declarative Pipelines is the current evolution and product name of DLT.

Lakeflow Declarative Pipelines is a data-pipeline framework in Databricks for defining, executing, and maintaining data processing pipelines using a declarative programming model.

The key idea is:
You define the desired state and data relationships of your datasets, rather than explicitly controlling every execution step.
你描述“数据应该是什么样、数据之间是什么关系、数据质量应该满足什么条件”,而不是手工控制每一个执行步骤。

A Declarative Pipeline can contain:

  • data sources
  • data flows
  • streaming tables
  • materialized views
  • transformations
  • data-quality rules
  • dependencies between datasets
  • pipeline configuration
  • operational and monitoring information

The pipeline engine uses the definitions to construct a dependency graph / DAG and determine how the pipeline should be executed.

In current Databricks terminology, the technology formerly known as Delta Live Tables (DLT) has evolved into Lakeflow Declarative Pipelines. The underlying open framework is also referred to as Apache Spark Declarative Pipelines (SDP).

Our Data platform:

ADLS
↓
Bronze
↓
Silver
↓
Gold

Traditional data engineering flow looks this:

ADF Trigger
      ↓
Databricks Job
      ↓
Notebook 1
      ↓
Notebook 2
      ↓
Notebook 3
      ↓
Data Quality Job
      ↓
Aggregation Job
      ↓
Power BI Refresh
 

Data Engineer have to consider and orchestrate

When does it run?                         什么时候运行?
What are the dependencies?                谁依赖谁?
What is the execution order?              谁先执行?
How are failures handled?                 失败以后怎么办?
How do we handle re-runs / retries?       重新执行怎么办?
How is incremental processing handled?    如何处理增量?
How do we avoid duplicate data?           如何避免重复?
How is data quality enforced/validated?   如何做数据质量?
How is the pipeline monitored?            如何监控?

Declarative Pipeline does this:

Bronze = source data

Silver = cleaned Bronze data

Gold = business aggregation of Silver

------------------------

Silver depends on Bronze

Gold depends on Silver

-----------------------
Bronze
   ↓
Silver
   ↓
Gold

This is called Dependency Graph.

The important architectural shift is: Execution logic becomes separated from data logic. 把 Data Logic 和 Execution Logic 分离。

Your code primarily describes:
(Data Engineers are more focused on: Data Engineer 更关注)

  • What data should exist? 数据是什么?
  • What transformation defines it? 数据怎么转换?
  • What quality rules must it satisfy? 数据质量要求是什么?
  • What datasets does it depend on? 数据依赖谁?

The platform can then manage much of (而 Pipeline Framework 更多负责):

  • Execution 怎么执行
  • Dependency resolution 依赖怎么解析
  • Incremental processing 怎么增量更新
  • Pipeline updates
  • Monitoring 怎么监控
  • Data quality metrics
  • Recovery 怎么处理失败
  • Parallel execution 哪些任务可以并行
                    Declarative Pipeline
                           │
          ┌────────────────┼────────────────┐
          │                │                │
          ↓                ↓                ↓
      Ingestion       Transformation    Data Quality
          │                │                │
     Auto Loader       Spark SQL       Expectations
          │                │                │
          ↓                ↓                ↓
       Bronze  ───────→  Silver  ─────→ Gold
          │
          ↓
      Delta Lake
          │
          ↓
   Unity Catalog

What exactly is the core problem that Declarative Pipelines (DP) aim to solve?

Assuming, a Bank, has those everyday:

Customer
Account
Transaction
Payment
Loan

They come from

Oracle
SQL Server
Kafka
ADLS
REST API

Data Engineer should create:

                Sources
                   │
       ┌───────────┼───────────┐
       ↓           ↓           ↓
    Oracle       Kafka       ADLS
       │           │           │
       └───────────┼───────────┘
                   ↓
                Bronze
                   ↓
                Silver
                   ↓
                 Gold
                   ↓
              Power BI

If we do not have a good pipeline framwork, data engineer may create

ADF Pipeline 1
ADF Pipeline 2
ADF Pipeline 3
Databricks Job 1
Databricks Job 2
Databricks Job 3
Notebook 1
Notebook 2
Notebook 3
DQ Job
CDC Job

maintaining

dependencies
schedules
retries
checkpoints
parameters
error handling
monitoring

One of the primary goals of Declarative Pipelines (DP) is to shift more of this complexity onto the pipeline framework.”

Key foundational concepts of Declarative Pipelines

Declarative Pipelines
│
├── Pipeline
│
├── Dataset
│   ├── Streaming Table
│   ├── Materialized View
│   └── Temporary View
│
├── Flow
│
├── Dependency Graph
│
├── Incremental Processing
│
├── Data Quality
│   └── Expectations
│
├── Change Data Capture
│   └── AUTO CDC
│
├── Batch Processing
│
├── Streaming Processing
│
├── Monitoring
│   └── Event Log
│
├── Unity Catalog
│
└── Deployment / CI-CD

Pipeline / Dataset / Flow

ConceptProfessional Meaning人话
PipelineApplication / execution boundary整个工厂
DatasetData object produced/maintained产品
FlowData movement / processing path传送带
DependencyRelationship between datasets谁必须等谁
Pipeline EngineExecutes the declared pipeline工厂管理系统

Declarative Pipeline Python API code implement

# ============================================================
# Import the modern Declarative Pipelines API
# ============================================================

from pyspark import pipelines as dp


# ============================================================
# BRONZE DATASET
# ============================================================
#
# Purpose:
#   Define the Bronze dataset.
#
# Important:
#   We are DECLARING what this dataset should contain.
#   We are not manually starting a streaming query.
# ============================================================

@dp.table
def customer_bronze():

    return (
        spark.readStream

        # ----------------------------------------------------
        # Auto Loader
        #
        # Purpose:
        #   Incrementally discover new files arriving in ADLS.
        # ----------------------------------------------------
        .format("cloudFiles")

        # ----------------------------------------------------
        # Source format
        # ----------------------------------------------------
        .option("cloudFiles.format", "json")

        # ----------------------------------------------------
        # Source location
        # ----------------------------------------------------
        .load("/mnt/raw/customer")
    )


# ============================================================
# SILVER DATASET
# ============================================================
#
# Purpose:
#   Clean and standardize Bronze customer data.
#
# Dependency:
#
#       customer_bronze
#              ↓
#       customer_silver
#
# The dependency is expressed by reading customer_bronze.
# ============================================================

@dp.table
def customer_silver():

    return (
        spark.readStream

        # ----------------------------------------------------
        # Read the Bronze dataset.
        #
        # This establishes the logical dependency:
        #
        # customer_silver
        #        ↓
        # customer_bronze
        # ----------------------------------------------------
        .table("customer_bronze")

        # ----------------------------------------------------
        # Data quality / business rule:
        #
        # A customer record without customer_id is not useful
        # to downstream business processing.
        # ----------------------------------------------------
        .filter("customer_id IS NOT NULL")

        # ----------------------------------------------------
        # Keep only columns required by the Silver layer.
        # ----------------------------------------------------
        .select(
            "customer_id",
            "name",
            "email",
            "updated_at"
        )
    )

Step by Step build a Complete Lakeflow Declarative Pipeline

Customer Data Lakehouse Pipeline — Requirements

1. Project Goal / 项目目标

Build an end-to-end Lakeflow Declarative Pipeline for customer data:

ADLS Landing → Bronze → Data Quality / Routing → Silver → Gold

The pipeline must demonstrate:

  • Auto Loader incremental ingestion
  • Bronze raw-data preservation
  • Data Quality validation
  • Invalid-record quarantine
  • Severe-invalid record drop with audit logging
  • Silver trusted customer data
  • Gold business/analytics output
  • Declarative Pipeline dependency management
  • Incremental processing
  • Auditability and traceability

中文

我们建立一个完整的 Lakeflow Declarative Pipeline:

ADLS Landing → Bronze → 数据质量检查/路由 → Silver → Gold

这个实验不是简单地:

读数据 → filter → 写 Silver

而是模拟一个比较接近企业实际的 Data Engineering Pipeline。

重点学习:

  • Auto Loader 增量 ingestion
  • Bronze 保存原始数据
  • Data Quality validation
  • Bad data Quarantine
  • 严重坏数据 Drop + Audit Log
  • Silver Trusted Data
  • Gold Analytics Data
  • Declarative Pipeline 自动 dependency management
  • Incremental processing
  • 数据可追溯性和审计

2. Source Data / 数据源

Raw Data:
customer_001.json
customer_002.json
customer_003.json

ADLS Location: abfss://landing@.dfs.core.windows.net/customer/

ADLS
└── landing
    └── customer
        ├── customers_001.json
        ├── customers_002.json
        └── customers_003.json

Our pipeline will implement a simple Medallion Architecture using Lakeflow Declarative Pipelines.

                Azure ADLS
                    │
                    │ JSON files
                    ▼
              Auto Loader
                    │
                    ▼
          ┌───────────────────┐
          │ Bronze             │
          │ customer_bronze    │
          │ Raw / append       │
          └─────────┬─────────┘
                    │
                    │ transformation
                    ▼
          ┌───────────────────┐
          │ Silver            │
          │ customer_silver   │
          │ Cleaned data      │
          └─────────┬─────────┘
                    │
                    │ aggregation
                    ▼
          ┌───────────────────┐
          │ Gold              │
          │ customer_summary  │
          │ Business data     │
          └───────────────────┘

Customer Business Columns

ColumnMeaning
customer_idCustomer identifier
nameCustomer name
emailCustomer email
statusACTIVE / INACTIVE
countryCustomer country
updated_atSource/business update timestamp

3. Bronze Requirement / Bronze 要求

Bronze 是整个 pipeline 的原始数据入口层。Ingestion 必须使用:Auto Loader. 要能够:support scalable file ingestion
incremental discover new files
process new files
avoid reprocessing already processed files

4. Bronze Must Preserve Raw Data

这是非常重要的一条 requirement。Bronze 不能只保存清洗后的 business columns。Bronze 必须尽可能保留:

Business Data

customer_id
name
email
status
country
updated_at

Raw / Audit Metadata

例如:

_raw_record
_ingest_ts
_source_file
_source_file_name
_source_file_modification_time

如果适用,也可以考虑:

_source_system
_batch_id
_record_hash

5. Important Timestamp Definition

这里要特别区分两个时间, updated_at and _ingest_ts

updated_at: 这是 Source Business Timestamp, 表示源系统认为这条 customer record 什么时候更新。例如: updated_at = 2026-09-10 10:05:00

_ingest_ts: 这是 Data Platform Ingestion Timestamp, 表示这条数据什么时候进入我们的 Data Platform / Pipeline processing。例如:_ingest_ts = 2026-09-10 10:06:13

两者不能混为一谈。

6. Bronze Raw Record Requirement

我们希望 Bronze 能够保存原始 record 的 JSON representation,例如:_raw_record

这样以后:如果一条 record 被 quarantine 或 drop,我们可以看到它进入 pipeline 时的原始状态。这是企业 Data Platform 中非常重要的:Traceability / 可追溯性

7. Data Quality Requirements

这是整个实验最重要的部分。我们定义三个核心 Data Quality rules:

Rule 1 — Customer ID

customer_id must not be NULL

Rule 2 — Email

Email 必须:

NOT NULL

并且应该满足基本 email format。例如:alice@example.com 有效。而:alice@ 无效。

Rule 3 — Status

Status 必须是:ACTIVE 或者:INACTIVE . 其他值都是 invalid。 例如:

ACTIVE       → valid
INACTIVE     → valid
PENDING      → invalid
UNKNOWN      → invalid
NULL         → invalid

8. Data Quality Routing Requirement

我们不是简单地 DROP 所有坏数据。这是这个项目的核心设计。我们把 record 分成三个类别:

                    Bronze
                       │
                       ▼
                Data Quality
                   Validation
                       │
          ┌────────────┼────────────┐
          ▼            ▼            ▼
        VALID      RECOVERABLE    SEVERE
          │            │            │
          ▼            ▼            ▼
       Silver      Quarantine    Drop Log

9. Routing Decision Matrix

这是目前我们确认的正式 requirement baseline。

Customer_IDEmailStatusActionDestination
ValidValidACTIVEACCEPTSilver
ValidValidINACTIVEACCEPTSilver
NULLValidValidQUARANTINEQuarantine
ValidNULLValidQUARANTINEQuarantine
ValidValidInvalidQUARANTINEQuarantine
NULLNULLValidQUARANTINEQuarantine
NULLValidInvalidQUARANTINEQuarantine
ValidNULLInvalidQUARANTINEQuarantine
NULLNULLInvalidDROPDrop Log

10. Quarantine Requirement

如果 record 不符合正常 Silver 数据质量要求,但是没有达到 Severe Drop 条件:Quarantine

例如:

customer_id = NULL
email = bob@example.com
status = ACTIVE

不能进入 Silver。但是:不能直接删除。应该进入:

customer_quarantine

11. Quarantine Must Preserve Original Record

Quarantine 至少应该包含:Original Business Data

customer_id
name
email
status
country
updated_at

Original Record

_raw_record

Source Information

_source_file
_source_file_name

Ingestion Information

_ingest_ts

Data Quality Information

_dq_customer_id_valid
_dq_email_valid
_dq_status_valid

以及:

_dq_reason

例如:

CUSTOMER_ID_NULL

或者:

EMAIL_NULL

或者:

INVALID_STATUS

多个问题:

CUSTOMER_ID_NULL;EMAIL_NULL

12. Quarantine Timestamp

需要记录:_quarantine_ts . 表示:这条 record 被判定并进入 quarantine 的时间。

13. Drop Requirement

最严重的情况:

customer_id = NULL
email       = NULL
status      = INVALID

这条 record:不进入 Silver, 不作为正常 Quarantine Record. 而是:DROP

但是:Drop ≠ 数据完全消失,

这是非常重要的概念。真正的设计是:

Bronze
   │
   └── severe invalid
             │
             ▼
        Drop Audit Log

所以我们实际上是:从 business processing path 中 drop,但从 audit trail 中保留。

14. Drop Log Requirement

建立:customer_drop_log

至少保存:

Original Data

customer_id
name
email
status
country
updated_at

Raw Record

_raw_record

Source Metadata

_source_file
_source_file_name
_source_file_modification_time

Ingestion Information

_ingest_ts

Drop Information

_drop_ts
_drop_reason

例如:

_drop_reason =
CUSTOMER_ID_NULL;EMAIL_NULL;INVALID_STATUS

这样以后可以回答:Why was this customer record dropped?

以及:What exactly was the original record?

15. Silver Requirement

Silver 是:Trusted / Validated Customer Data

只有:

customer_id valid
AND
email valid
AND
status ∈ ('ACTIVE', 'INACTIVE')

的 record 才能进入 Silver。因此:

Bronze
   │
   ├── valid ─────────────→ Silver
   │
   ├── invalid/recoverable → Quarantine
   │
   └── severe invalid ────→ Drop Log

Silver 不应该包含:

  • NULL customer_id
  • NULL email
  • invalid email
  • invalid status

16. Silver Transformation Requirement

Silver 除了 DQ filtering,还可以做一些正常的 standardization,例如:

trim(customer_id)
trim(name)
lower(email)
upper(status)

例如:

" alice@example.com "

standardize 成:

"alice@example.com"

但是:Bronze 不修改原始数据。这是:

Bronze = Preserve
Silver = Clean / Standardize / Trust

17. Gold Requirement

Gold 是面向:Business / Analytics Consumption. 我们需要一个简单但有意义的 Gold dataset。

例如:

customer_summary

按:

status

统计 customer 数量:

status      customer_count
---------------------------
ACTIVE      5
INACTIVE    1

也可以进一步按:

country
status

进行 aggregation。

例如:

country    status       customer_count
---------------------------------------
Canada     ACTIVE       4
Canada     INACTIVE     0
USA        INACTIVE     1
UK         ACTIVE       1

Gold 使用:Materialized View 来体现:

Silver
   ↓
Gold Materialized View

18. Final Pipeline Architecture

                         ADLS
                          │
                          │
                    Auto Loader
                          │
                          ▼
                    ┌───────────┐
                    │  Bronze   │
                    │ Raw Data  │
                    │ + Metadata│
                    └─────┬─────┘
                          │
                          ▼
                  Data Quality Rules
                          │
             ┌────────────┼────────────┐
             │            │            │
             ▼            ▼            ▼
          VALID      RECOVERABLE     SEVERE
             │            │            │
             ▼            ▼            ▼
          Silver      Quarantine    Drop Log
             │
             │
             ▼
       Gold Materialized
             View

19. Final Dataset List

整个 Pipeline 最终应该至少有 4 个主要数据集:

1. customer_bronze
2. customer_silver
3. customer_quarantine
4. customer_drop_log
5. customer_summary        ← Gold

也就是说:

Bronze
   │
   ├──────────────→ Silver
   │                   │
   │                   ▼
   │                  Gold
   │
   ├──────────────→ Quarantine
   │
   └──────────────→ Drop Log

20. Declarative Pipeline Requirement

我们不希望自己手工 orchestration, 而是 Declare the datasets and their relationships.

Silver reads Bronze
Gold reads Silver
Quarantine reads Bronze
Drop Log reads Bronze

Pipeline framework 根据这些 dependencies 自动建立:

Dependency Graph

然后负责:

  • execution
  • dependency resolution
  • orchestration
  • incremental processing
  • checkpointing
  • pipeline updates
  • table maintenance

我们的代码主要负责:定义“数据应该是什么样子,以及它从哪里来”。

22. Incremental Processing Requirement

实验必须体现:First Run 例如:customers_001.json ; customers_002.json, 进入 pipeline。

Later 再增加:customers_003.json

Pipeline update 后:只处理新的 input data,而不是每次重新从头读取所有文件。

最终我们观察:

Bronze
Silver
Quarantine
Drop Log
Gold

23. Data Lineage / Traceability Requirement

我们最终应该能够回答:Where did this Silver record come from?

Silver
 ↓
Bronze
 ↓
ADLS file

Why was this record quarantined?

Quarantine
 ↓
DQ reason
 ↓
Original record
 ↓
Source file

Why was this record dropped?

Drop Log
 ↓
Drop reason
 ↓
Original record
 ↓
Source file
 ↓
Ingestion timestamp

这就是:

Data Lineage + Auditability + Traceability

25. Coding Order / 我们之后的 Coding 顺序

Step 1: Create Bronze

ADLS
 ↓
Auto Loader
 ↓
customer_bronze

Step 2: Validate Bronze Data

建立:

customer_id validation
email validation
status validation

Step 3: Classify / Route Records

VALID
QUARANTINE
DROP

Step 4: Create Quarantine

customer_quarantine

Step 5: Create Drop Audit Log

customer_drop_log

Step 6: Create Silver

customer_silver

Step 7: Create Gold

customer_summary

Step 8: Test Incremental Processing

增加新的 JSON:

customers_003.json

Step 9: Review Pipeline Graph / Data Quality / Audit

Test Data

we want to demonstrate incremental ingestion.

# File 1 — customers_001.json

[
  {
    "customer_id": "C001",
    "name": "Alice",
    "email": "alice@example.com",
    "status": "ACTIVE",
    "country": "Canada",
    "updated_at": "2026-09-10T09:00:00"
  },
  {
    "customer_id": "C002",
    "name": "Bob",
    "email": "bob@example.com",
    "status": "ACTIVE",
    "country": "Canada",
    "updated_at": "2026-09-10T09:05:00"
  },
  {
    "customer_id": "C003",
    "name": "Charlie",
    "email": "charlie@example.com",
    "status": "INACTIVE",
    "country": "USA",
    "updated_at": "2026-09-10T09:10:00"
  }
]





# File 2 — customers_002.json
[
  {
    "customer_id": "C004",
    "name": "David",
    "email": "david@example.com",
    "status": "ACTIVE",
    "country": "Canada",
    "updated_at": "2026-09-10T10:00:00"
  },
  {
    "customer_id": "C005",
    "name": "Emma",
    "email": "emma@example.com",
    "status": "ACTIVE",
    "country": "UK",
    "updated_at": "2026-09-10T10:05:00"
  }
]

URL: abfss://landing@storageaccount.dfs.core.windows.net/customer/

Pipeline source code will like:

customer_pipeline/
│
├── customer_pipeline.py
│
└── configuration

1: Create Bronze (Simple, no for product)

aim: Incrementally load JSON files from ADLS into a Bronze Streaming Table.

# 简单实现, 其实在实际项目不会这么简单
from pyspark import pipelines as dp


@dp.table 
def customer_bronze():        # create a table called "customer_bronze" 
   # The decorator declares that the function defines a pipeline-managed dataset.
   # In this context, it creates a streaming table.

    return (
        spark.readStream
            .format("cloudFiles")
            .option("cloudFiles.format", "json")
            .load("abfss://landing@myaccount.dfs.core.windows.net/customer/")
    )

we do not do ” create table ……” then “writeStream.start()” ,

Declarative Pipeline WILL TAKE OVER this job

The pipeline framework manages:

  • execution
  • checkpointing
  • dependency resolution
  • incremental processing
  • scheduling
  • table maintenance
  • orchestration

The developer primarily declares: what dataset should exist and how it is derived.

2: Create Silver (Simple, not for product)

@dp.table
@dp.expect(                          # Data Quality Expectation
    "valid_customer_id",
    "customer_id IS NOT NULL"        # customer_id cannot null
)

@dp.expect(
    "valid_email",
    "email IS NOT NULL AND email RLIKE '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$'"
                                           # email cannot be null and it should be in good form
)

@dp.expect(
    "valid_status",
    "status IN ('ACTIVE', 'INACTIVE')"    # status only allow ACTIVE or INACTIVE
)

def customer_silver():

    return (
        spark.readStream
            .table("customer_bronze")
            .filter("customer_id IS NOT NULL")
            .select(
                "customer_id",
                "name",
                "email",
                "status",
                "country",
                "updated_at"
            )
    )

Product grade, end- to-end code implement

test data

abfss://landing@<storage-account>.dfs.core.windows.net/customer/

customers_001.json
customers_002.json

[
  {
    "customer_id": "C001",
    "name": "Alice",
    "email": "alice@example.com",
    "status": "ACTIVE",
    "country": "Canada",
    "updated_at": "2026-09-10T09:00:00"
  },
  {
    "customer_id": "C002",
    "name": "Bob",
    "email": "bob@example.com",
    "status": "ACTIVE",
    "country": "Canada",
    "updated_at": "2026-09-10T09:05:00"
  },
  {
    "customer_id": "C003",
    "name": "Charlie",
    "email": "charlie@example.com",
    "status": "INACTIVE",
    "country": "USA",
    "updated_at": "2026-09-10T09:10:00"
  }
]

Step 1 — Create Bronze

Our first pipeline layer is:

ADLS Landing
      │
      │ Auto Loader
      ▼
customer_bronze

Bronze’s job is not to clean the data. Its job is: Ingest and preserve the source data faithfully, together with ingestion/source metadata.

First Bronze implementation

from pyspark import pipelines as dp


@dp.table
def customer_bronze():  # create a table called "customer_bronze" 

    return (
        spark.readStream
            .format("cloudFiles")
            .option("cloudFiles.format", "json")
            .load(
                "abfss://landing@<storage-account>.dfs.core.windows.net/customer/"
            )
    )

What does this code actually produce? it creates “customer_bronze”

Table customer_bronze:

customer_id
name
email
status
country
updated_at

# we're missing
├── _raw_record
├── _ingest_ts
├── _source_file
├── _source_file_name
└── _source_file_modification_time
这些是我们之前 Requirement 中要求的 audit information。只有改成下面的

现在我们把代码升级, 满足requirement 的要求。

from pyspark import pipelines as dp
from pyspark.sql.functions import (
    current_timestamp,
    col,
    struct,
    to_json
)


@dp.table(
    comment="Bronze layer containing raw customer data ingested incrementally from ADLS using Auto Loader."
)
def customer_bronze():

    return (
        spark.readStream

            # ---------------------------------------------------------
            # Use Databricks Auto Loader as the streaming file source.
            # Auto Loader incrementally discovers new files arriving
            # in the ADLS landing folder.
            # ---------------------------------------------------------
            .format("cloudFiles")

            # ---------------------------------------------------------
            # The source files in our experiment are JSON files.
            # ---------------------------------------------------------
            .option("cloudFiles.format", "json")

            # ---------------------------------------------------------
            # Load files from the ADLS landing zone.
            #
            # Replace <storage-account> with the real storage account.
            # ---------------------------------------------------------
            .load(
                "abfss://landing@<storage-account>.dfs.core.windows.net/customer/"
            )

            # ---------------------------------------------------------
            # Add platform ingestion timestamp.
            #
            # This is NOT the source business timestamp.
            # updated_at = source/business time
            # _ingest_ts = data-platform ingestion/processing time
            # ---------------------------------------------------------
            .withColumn(
                "_ingest_ts",
                current_timestamp()
            )

            # ---------------------------------------------------------
            # Capture source file metadata.
            #
            # _metadata is provided by Auto Loader.
            # We preserve the file path and modification time so that
            # downstream DQ issues can be traced back to the source file.
            # ---------------------------------------------------------
            .withColumn(
                "_source_file",
                col("_metadata.file_path")
            )
            .withColumn(
                "_source_file_modification_time",
                col("_metadata.file_modification_time")
            )

            # ---------------------------------------------------------
            # Keep the raw source record as JSON.
            #
            # This gives us a representation of the record as it exists
            # at the Bronze stage before Silver transformations.
            #
            # This will later be extremely useful for:
            #   - Quarantine
            #   - Drop Audit Log
            #   - Troubleshooting
            #   - Data lineage / traceability
            # ---------------------------------------------------------
            .withColumn(
                "_raw_record",
                to_json(
                    struct(
                        "customer_id",
                        "name",
                        "email",
                        "status",
                        "country",
                        "updated_at"
                    )
                )
            )

            # ---------------------------------------------------------
            # Select the columns that belong to the Bronze contract.
            #
            # Bronze preserves business data plus source/audit metadata.
            # ---------------------------------------------------------
            .select(
                "customer_id",
                "name",
                "email",
                "status",
                "country",
                "updated_at",

                "_raw_record",
                "_ingest_ts",

                "_source_file",
                "_source_file_modification_time"
            )
    )

三个时间的区别 (以后你面试很可能会被问到)

FieldMeaning
updated_atSource business timestamp
_source_file_modification_timeSource file timestamp
_ingest_tsPlatform ingestion timestamp

为什么需要 _raw_record? 这是我们后面设计:

Quarantine
Drop Log

Current Bronze Architecture

现在我们已经从:

ADLS
 ↓
Auto Loader
 ↓
Bronze

升级成:

                         ADLS
                          │
                          ▼
                    Auto Loader
                          │
                          ▼
                ┌──────────────────┐
                │ customer_bronze  │
                ├──────────────────┤
                │ customer_id      │
                │ name             │
                │ email            │
                │ status           │
                │ country          │
                │ updated_at       │
                │                  │
                │ _raw_record      │
                │ _ingest_ts       │
                │ _source_file     │
                │ _source_file_... │
                └──────────────────┘

What should we see after the first run? 如果 source 中:

C001
C002
C003
C004
C005

那么 Bronze 应该有:5 records. 例如:

customer_idemailstatus_source_file_ingest_ts
C001alice@example.comACTIVEcustomers_001.json…
C002bob@example.comACTIVEcustomers_001.json…
C003charlie@example.comINACTIVEcustomers_001.json…
C004david@example.comACTIVEcustomers_002.json…
C005emma@example.comACTIVEcustomers_002.json…

注意:我们还没有进行任何 Business Data Quality filtering。

所以把代码补完整:

from pyspark import pipelines as dp
from pyspark.sql.functions import (
    current_timestamp,
    col,
    struct,
    to_json
)

@dp.table(
    comment="Bronze layer containing raw customer data ingested incrementally from ADLS using Auto Loader."
)
def customer_bronze():

    return (
        spark.readStream
            .format("cloudFiles")
            .option("cloudFiles.format", "json")
            .load(
                "abfss://landing@<storage-account>.dfs.core.windows.net/customer/"
            )

            # Platform ingestion timestamp
            .withColumn(
                "_ingest_ts",
                current_timestamp()
            )

            # Source file metadata
            .withColumn(
                "_source_file",
                col("_metadata.file_path")
            )
            .withColumn(
                "_source_file_name",
                col("_metadata.file_name")
            )
            .withColumn(
                "_source_file_modification_time",
                col("_metadata.file_modification_time")
            )

            # Serialized representation of the parsed business record
            .withColumn(
                "_raw_record",
                to_json(
                    struct(
                        "customer_id",
                        "name",
                        "email",
                        "status",
                        "country",
                        "updated_at"
                    )
                )
            )

            .select(
                "customer_id",
                "name",
                "email",
                "status",
                "country",
                "updated_at",
                "_raw_record",
                "_ingest_ts",
                "_source_file",
                "_source_file_name",
                "_source_file_modification_time"
            )
    )

Step 2 — Data Quality Validation

数据质量验证

from pyspark import pipelines as dp
from pyspark.sql.functions import (
    col,
    when,
    concat_ws,
    array,
    lit
)

@dp.temporary_view
def customer_validation():

    return (
        spark.readStream
            .table("customer_bronze")

            # ==============================
            # DQ Rule 1: Customer ID
            # ==============================
            .withColumn(
                "_dq_customer_id_valid",
                col("customer_id").isNotNull()
            )

            # ==============================
            # DQ Rule 2: Email
            # ==============================
            .withColumn(
                "_dq_email_valid",
                (
                    col("email").isNotNull()
                    &
                    col("email").rlike(
                        r"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$"
                    )
                )
            )

            # ==============================
            # DQ Rule 3: Status
            # ==============================
            .withColumn(
                "_dq_status_valid",
                col("status").isin("ACTIVE", "INACTIVE")
            )

            # ==============================
            # Overall validation
            # ==============================
            .withColumn(
                "_dq_all_valid",
                (
                    col("_dq_customer_id_valid")
                    &
                    col("_dq_email_valid")
                    &
                    col("_dq_status_valid")
                )
            )

            # ==============================
            # DQ reason
            # ==============================
            .withColumn(
                "_dq_reason",
                concat_ws(
                    ";",
                    array(
                        when(
                            col("customer_id").isNull(),
                            lit("CUSTOMER_ID_NULL")
                        ),

                        when(
                            col("email").isNull(),
                            lit("EMAIL_NULL")
                        ),

                        when(
                            col("email").isNotNull()
                            &
                            ~col("email").rlike(
                                r"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$"
                            ),
                            lit("INVALID_EMAIL_FORMAT")
                        ),

                        when(
                            ~col("status").isin("ACTIVE", "INACTIVE"),
                            lit("INVALID_STATUS")
                        )
                    )
                )
            )

            # ==============================
            # Routing decision
            # ==============================
            .withColumn(
                "_dq_action",
                when(
                    col("_dq_all_valid"),
                    lit("ACCEPT")
                )
                .when(
                    (~col("_dq_customer_id_valid"))
                    &
                    (~col("_dq_email_valid"))
                    &
                    (~col("_dq_status_valid")),
                    lit("DROP")
                )
                .otherwise(
                    lit("QUARANTINE")
                )
            )
    )

Step 3 — Routing into Silver / Quarantine / Drop Log

Silver 的原则:Only trusted, validated customer records enter Silver.

from pyspark import pipelines as dp
from pyspark.sql.functions import (
    col,
    when,
    concat_ws,
    array,
    lit,
    trim,
    lower,
    upper,
    current_timestamp
)


# ============================================================
# 1. Validation and Routing
# ============================================================

@dp.temporary_view
def customer_validation():

    return (
        spark.readStream
            .table("customer_bronze")

            # ------------------------------------------------
            # DQ Rule 1: customer_id must not be NULL
            # ------------------------------------------------
            .withColumn(
                "_dq_customer_id_valid",
                col("customer_id").isNotNull()
            )

            # ------------------------------------------------
            # DQ Rule 2:
            # email must not be NULL and must match
            # the basic email format
            # ------------------------------------------------
            .withColumn(
                "_dq_email_valid",
                (
                    col("email").isNotNull()
                    &
                    col("email").rlike(
                        r"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$"
                    )
                )
            )

            # ------------------------------------------------
            # DQ Rule 3:
            # status must be ACTIVE or INACTIVE
            # ------------------------------------------------
            .withColumn(
                "_dq_status_valid",
                (
                    col("status").isNotNull()
                    &
                    col("status").isin(
                        "ACTIVE",
                        "INACTIVE"
                    )
                )
            )

            # ------------------------------------------------
            # Overall DQ result
            # ------------------------------------------------
            .withColumn(
                "_dq_all_valid",
                (
                    col("_dq_customer_id_valid")
                    &
                    col("_dq_email_valid")
                    &
                    col("_dq_status_valid")
                )
            )

            # ------------------------------------------------
            # DQ Reason
            #
            # Multiple reasons are concatenated:
            #
            # CUSTOMER_ID_NULL;EMAIL_NULL
            # ------------------------------------------------
            .withColumn(
                "_dq_reason",
                concat_ws(
                    ";",
                    array(

                        when(
                            col("customer_id").isNull(),
                            lit("CUSTOMER_ID_NULL")
                        ),

                        when(
                            col("email").isNull(),
                            lit("EMAIL_NULL")
                        ),

                        when(
                            col("email").isNotNull()
                            &
                            ~col("email").rlike(
                                r"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$"
                            ),
                            lit("INVALID_EMAIL_FORMAT")
                        ),

                        when(
                            col("status").isNull()
                            |
                            ~col("status").isin(
                                "ACTIVE",
                                "INACTIVE"
                            ),
                            lit("INVALID_STATUS")
                        )
                    )
                )
            )

            # ------------------------------------------------
            # Routing Decision
            #
            # ACCEPT:
            #   All three rules pass
            #
            # DROP:
            #   All three rules fail
            #
            # QUARANTINE:
            #   Everything else
            # ------------------------------------------------
            .withColumn(
                "_dq_action",
                when(
                    col("_dq_all_valid"),
                    lit("ACCEPT")
                )
                .when(
                    (~col("_dq_customer_id_valid"))
                    &
                    (~col("_dq_email_valid"))
                    &
                    (~col("_dq_status_valid")),
                    lit("DROP")
                )
                .otherwise(
                    lit("QUARANTINE")
                )
            )
    )


# ============================================================
# 2. Silver
# ============================================================

@dp.table(
    comment="Trusted customer records that passed all core data quality rules."
)
def customer_silver():

    return (
        spark.readStream
            .table("customer_validation")

            # Only fully valid records
            .filter(
                col("_dq_action") == "ACCEPT"
            )

            # Standardize trusted business data
            .select(
                trim(
                    col("customer_id")
                ).alias("customer_id"),

                trim(
                    col("name")
                ).alias("name"),

                lower(
                    trim(
                        col("email")
                    )
                ).alias("email"),

                upper(
                    trim(
                        col("status")
                    )
                ).alias("status"),

                trim(
                    col("country")
                ).alias("country"),

                col("updated_at"),

                # Audit / lineage metadata
                col("_raw_record"),
                col("_ingest_ts"),
                col("_source_file"),
                col("_source_file_name"),
                col("_source_file_modification_time")
            )
    )


# ============================================================
# 3. Quarantine
# ============================================================

@dp.table(
    comment="Customer records that failed one or more recoverable data quality rules."
)
def customer_quarantine():

    return (
        spark.readStream
            .table("customer_validation")

            # Recoverable DQ failures
            .filter(
                col("_dq_action") == "QUARANTINE"
            )

            .select(
                # Original business data
                "customer_id",
                "name",
                "email",
                "status",
                "country",
                "updated_at",

                # Raw / lineage information
                "_raw_record",
                "_ingest_ts",
                "_source_file",
                "_source_file_name",
                "_source_file_modification_time",

                # DQ results
                "_dq_customer_id_valid",
                "_dq_email_valid",
                "_dq_status_valid",
                "_dq_reason",

                # Quarantine audit timestamp
                current_timestamp().alias(
                    "_quarantine_ts"
                )
            )
    )


# ============================================================
# 4. Drop Log
# ============================================================

@dp.table(
    comment="Audit log for severely invalid customer records excluded from normal processing."
)
def customer_drop_log():

    return (
        spark.readStream
            .table("customer_validation")

            # Severe DQ failures
            .filter(
                col("_dq_action") == "DROP"
            )

            .select(
                # Original business data
                "customer_id",
                "name",
                "email",
                "status",
                "country",
                "updated_at",

                # Raw / lineage information
                "_raw_record",
                "_ingest_ts",
                "_source_file",
                "_source_file_name",
                "_source_file_modification_time",

                # DQ results
                "_dq_customer_id_valid",
                "_dq_email_valid",
                "_dq_status_valid",

                # Audit reason
                col("_dq_reason").alias(
                    "_drop_reason"
                ),

                # Drop audit timestamp
                current_timestamp().alias(
                    "_drop_ts"
                )
            )
    )

这四个 Dataset 的关系

                    customer_bronze
                           │
                           │
                           ▼
                ┌────────────────────┐
                │ customer_validation│
                │                    │
                │ DQ Rules           │
                │ + Reason           │
                │ + Routing          │
                └─────────┬──────────┘
                          │
             ┌────────────┼────────────┐
             │            │            │
          ACCEPT      QUARANTINE      DROP
             │            │            │
             ▼            ▼            ▼
     customer_silver   customer_     customer_
                      quarantine    drop_log

最终 Routing Logic

customer_idemailstatus_dq_action去哪里
validvalidACTIVEACCEPTSilver
validvalidINACTIVEACCEPTSilver
NULLvalidvalidQUARANTINEQuarantine
validNULLvalidQUARANTINEQuarantine
validinvalid formatvalidQUARANTINEQuarantine
validvalidinvalidQUARANTINEQuarantine
NULLNULLvalidQUARANTINEQuarantine
NULLvalidinvalidQUARANTINEQuarantine
validNULLinvalidQUARANTINEQuarantine
NULLNULLinvalidDROPDrop Log

Step 4 — Gold: customer_summary

from pyspark import pipelines as dp


@dp.materialized_view(
    comment="Gold customer summary by customer status."
)
def customer_summary():

    return (
        spark.read
            .table("customer_silver")
            .groupBy("status")
            .count()
            .withColumnRenamed(
                "count",
                "customer_count"
            )
    )

完整架构:

                       ADLS Landing
                            │
                            ▼
                     ┌─────────────┐
                     │ Auto Loader │
                     └──────┬──────┘
                            │
                            ▼
                    ┌───────────────┐
                    │    Bronze     │
                    │ Raw + Metadata│
                    └───────┬───────┘
                            │
                            ▼
                 ┌─────────────────────┐
                 │ Customer Validation │
                 │                     │
                 │ DQ Rules            │
                 │ DQ Reason           │
                 │ Routing             │
                 └─────────┬───────────┘
                           │
              ┌────────────┼────────────┐
              │            │            │
              ▼            ▼            ▼
           ACCEPT      QUARANTINE      DROP
              │            │            │
              ▼            ▼            ▼
           Silver      Quarantine    Drop Log
              │
              ▼
        Materialized View
              │
              ▼
             Gold
              │
              ▼
     customer_summary

Lakeflow Declarative Pipeline

我们现在写的是:

@dp.table
def customer_bronze():
    ...

然后:

@dp.temporary_view
def customer_validation():
    return spark.readStream.table("customer_bronze")

然后:

@dp.table
def customer_silver():
    return spark.readStream.table("customer_validation")

最后:

@dp.materialized_view
def customer_summary():
    return spark.read.table("customer_silver")

Streaming Table vs Materialized View

Streaming TableMaterialized View
典型用途incremental row processingderived / aggregated result
数据特点持续到来的数据查询计算结果
常见操作filter / transform / enrichaggregation / business metrics
API@dp.table@dp.materialized_view
我们的例子customer_silvercustomer_summary

Step 6 — Put the Code into a Lakeflow Pipeline

现在进入真正的 hands-on 部分:

我们已经写完 Dataset definitions。下一步就是把这些 definitions 放进一个 Lakeflow Pipeline,让 Databricks 真正执行它。

这里先只做 Pipeline structure + code organization,暂时不深入 Deployment / Schedule / Production settings。

先把代码组织起来

最简单的方式是一个 Python pipeline source file,例如:

customer_pipeline/
│
└── customer_pipeline.py

里面包含我们目前的全部 Dataset definitions:

customer_pipeline.py
│
├── customer_bronze
│
├── customer_validation
│
├── customer_silver
│
├── customer_quarantine
│
├── customer_drop_log
│
└── customer_summary

Introducing Fabric

What is Fabic?

Microsoft Fabric is an all-in-one, SaaS (Software as a Service) analytics platform. It combines data movement, data engineering, data science, and business intelligence into one single website. It is built on OneLake, which is like “OneDrive for data.”

Why use Microsoft Fabric?

Traditional data stacks are “fragmented”—you might use Azure Data Factory for moving data, Databricks for cleaning it, Datalake for storing it, and Power BI for seeing it.

Fabric fixes this by putting everything in one place.

  • Unified Data: Every tool (SQL, Spark, Power BI) uses the same copy of data in OneLake. No more duplicating data.
  • SaaS Simplicity: You don’t need to manage servers, clusters, or storage accounts. It’s all managed by Microsoft.
  • Direct Lake Mode: Power BI can read data directly from the lake without “importing” it, making reports incredibly fast.
  • Cost Efficiency: You pay for one pool of “Compute Capacity” and share it across all your teams.

What can Microsoft Fabric do?

It handles the entire data journey:

  • Ingest: Pull data from anywhere (SQL, AWS, Web).
  • Store: Store massive amounts of data in an open format (Delta Parquet).
  • Process: Clean and transform data using Python/Spark or SQL.
  • Analyze: Run complex queries and train Machine Learning models.
  • Visualize: Build real-time dashboards in Power BI.

Components of Fabric

Fabric is divided into “Experiences” based on what you need to do:

Component (Experience)RolePurpose
Data FactoryData EngineerETL, Pipelines, and Dataflows.
Synapse Data EngineeringSpark DeveloperHigh-scale processing using Notebooks.
Synapse Data WarehouseSQL DeveloperProfessional-grade SQL storage.
Synapse Data ScienceData ScientistBuilding AI and ML models.
Real-Time IntelligenceIoT / App DevHigh-speed streaming data.
Power BIBusiness AnalystVisualizing data for the business.
Data ActivatorOperationsAutomatic alerts (e.g., “Email me if sales drop”).

Step-by-Step: Getting Started

If you were a Data Engineer working on a project today, your workflow would look like this:

Step 1: Create a Workspace

  • Log in to Fabric. Create a Workspace.
  • Ensure it has a Fabric Capacity license attached.

Step 2: The Lakehouse (Bronze)

  • Create a Lakehouse called “Company_Data_Lake“.
  • This creates a folder in OneLake where your raw files will live.

Step 3: Data Pipeline (Ingestion

  • Use Data Factory to create a pipeline.
  • >> Data Pipeline | Source: SQL Server | Destination: Lakehouse Files | 03/2026
  • This pulls your raw data into the “Files” folder.

Step 4: Notebook (Silver/Gold)

  • Open a Notebook. Use PySpark to clean the data.
  • Example: Remove duplicates, fix date formats.
  • Save the result as a Table (Delta format).

Step 5: Power BI (Visualization)

  • Switch to your SQL Analytics Endpoint.
  • Click New Report. Power BI will use Direct Lake to show your data instantly.

Appendix

Microsoft Fabric fundamentals documentation

Interview Questions and Answers

>> Talk yourself | Day-2-Day work | interested in position | Why work for us | Good Fit Role | Why hire you | Bring to team | Strength | Weakness | Jobs/task conflict | Change Requriement | Collaborate deploy AI/LLM | support-self-service | Translate-requirements-solution |

>> Design Metadata-Driven Pipeline | Design data Architecture | Incremental-Loading | Multiple-Domains Source | Troubleshoot | Performane Tuning | Quality-consistency | Monitor Pipeline | Migrating | Design models & schemas | Governance-security | CICD DevOps | Late-Arriving data |

>> Delta Live Tables DLT | Bundles & Job | Delta Sharing | Databricks Architecture | DBT | Schema Drift | hive to unity Catalog | Schema Enforcement | Schema Evolution | Time Travel | Schema Contract | Volumnes | Photon | Z-order | Liquid Clustering | catching | Boardcast | RDD-DF-DS|

Tell me about yourself.

I’m a Senior Azure Data Engineer with over 20 years of experience. I’ve worked across several domains, including financial services, consulting, the public sector, and healthcare.

I hold Microsoft and Databricks certifications. My core technical skills include Azure Data Factory, Databricks, Synapse, Fabric, Spark, Python, PySpark, SQL, and Power BI.

I’m a hands-on engineer. I focus on building production-ready, end-to-end data solutions. I also build metadata-driven, automated, reusable, and scalable data pipelines.

My work covers the entire data lifecycle, from ingestion and validation to transformation, standardization, enrichment, reconciliation, and reporting.

In addition, I have strong experience modernizing legacy data platforms and migrating existing data pipelines to modern platforms.

I also focus on data quality, security, and governance, including Unity Catalog. I work closely with business stakeholders, QA teams, business analysts, and data scientists.

I believe my experience in data engineering, automation, modernization, and governance aligns well with this role at ABC.

30 seconds’ answer

Can you talk about your day-to-day work? What’s your day-to-day work looks like?

My work covers several areas.

First, I review my tasks and priorities for the day. I also attend team meetings to discuss project progress and any blockers.

A big part of my work is hands-on data engineering. I use Databricks, Azure Data Factory, Python, PySpark, and SQL to ingest and transform data. I also validate the data and reconcile source and target results.

Another important part of my work is data quality. I check schemas, missing values, and duplicate records.

I also handle troubleshooting. If a pipeline fails or runs slowly, I check the logs, identify the root cause, fix the issue, and safely rerun the pipeline when needed.

I review code, test changes, and support deployments across different environments. I also work with business analysts, QA engineers, Data Scientists, and stakeholders to clarify requirements and resolve issues.

Finally, I update documentation and monitor production pipelines to make sure they run reliably.

Overall, my goal is to deliver reliable, high-quality data pipelines that meet business requirements.

Why are you interested in this position?

I’m interested in this role for three main reasons.

First, the role matches my experience with Azure Data Factory, Databricks, Synapse, and Power BI. I enjoy building reliable and scalable data pipelines that support business needs.

Second, I’m interested in the opportunity to work with company. I believe data plays an important role in improving business operations and supporting better decisions.

Finally, I believe I can bring my hands-on experience in data engineering, data quality, and data platform development to the team. I’d also like to contribute to company’s data initiatives.

That’s why I want to join your team.

20“ answer

Why do you think you are a good fit for this role?

I believe I’m a good fit for this role for three main reasons.

First, I have strong hands-on experience with Azure, Databricks, Data Factory, Synapse, and Power BI. I’ve used these technologies to build data solutions that support business needs.

Second, I have experience building reliable, scalable, and reusable data solutions. My work covers the full data lifecycle, including data ingestion and transformation to reporting and data quality. I also focus on performance tuning and making pipelines easy to maintain.

Finally, I have experience working with different teams to understand business needs and deliver production-ready data solutions.

I believe I have the skills and experience needed for this role.

20” answer

Why should we hire you?

I believe you should hire me because of my hands-on experience with Azure Data Factory, Azure Databricks, Synapse, and Power BI.

I have experience building end-to-end data solutions. My work covers the full data lifecycle, from ingestion and transformation to standardization, validation, and reporting.

I build reliable, scalable, and reusable data pipelines. I also focus on performance tuning, idempotency, and making pipelines easy to maintain.

Finally, I have real-world project experience. I work well with different teams and focus on delivering solutions that meet business needs.

I believe I can use my experience and skills to make a positive contribution to the team.

20” answer

What would you bring to our team?

> What would make you a valuable addition to our team?

I believe I can bring several strengths to the team.

First, I have hands-on experience with Azure Data Factory, Databricks, Synapse, and Power BI. I can build end-to-end data pipelines.

Second, I focus on building reliable, reusable, and secure data solutions that are easy to maintain.

Finally, I have solid project experience. I work well with other teams to understand their needs and deliver solutions efficiently.

I believe I can use these skills and experience to add value to the team.

20“ answer

What is your biggest strength as a Senior Data Engineer?

My biggest strength is that I can build end-to-end data solutions and make sure they are reliable, scalable, and easy to maintain. I focus not only on getting the job done, but also on data quality and long-term performance.

What is your biggest weakness?

> What is one area you need to improve?
> What would you like to improve about yourself?

One area I’m still improving is learning new technologies and business areas.

I have strong experience in data engineering, but every project is different. Sometimes, I need to learn new tools or understand a new business area.

When this happens, I read the documentation, do hands-on practice, and discuss with team members when needed.

I’m always willing to learn, and I can usually apply what I learn to my work quickly.

How do you prioritize competing requests, communicate with cross-functional teams, and ensure successful delivery?

Yes, I’ve done this in my previous projects.

First, I clarify the business requirements and expected outcomes. Then I assess each request based on business value, urgency, risk, dependencies, and estimated effort.

I work with business teams to understand their needs and priorities. If there are too many requests, I discuss with them what we should do first and what can wait.

I also collaborate with different teams, including business analysts, QA engineers, Data Scientists, and other data engineers. We use Scrum to organize the work into sprints, track milestones, and provide regular progress updates.

During development, I monitor risks and dependencies. If I identify a blocker, I raise it early and work with the team to resolve it.

Before delivery, I validate the results against the requirements and acceptance criteria. I also document important decisions and any issues that need follow-up.

My goal is to deliver the highest-priority business outcomes on time, while maintaining data quality and keeping stakeholders informed.

How do you collaborate with Data Scientists to prepare data and deploy machine learning models into production?

Yes, I’ve worked with Data Scientists to deploy AI/LLM, Machine learning models in my previous projects.

First, I understand the business requirements and expected outcomes. Then I work with the Data Scientists to understand their data needs, including schemas, data types, required features, and refresh frequency.

I prepare curated data using Databricks, PySpark, and SQL. I validate the data to make sure it is accurate, consistent, and complete.

I also build metadata-driven frameworks to automate data preparation and refresh. This makes the process reusable and easier to maintain.

For AI and RAG solutions, I prepare enterprise documents and extract metadata. I also support chunking, embedding, and indexing in a vector store.

For security, I follow the principle of least privilege. Users and applications only have access to the data they need.

Finally, I implement logging and monitoring. I work with the Data Scientists to resolve data issues and support production use.

My goal is to provide reliable, secure, and reusable data pipelines for analytics, machine learning, and AI applications.


How do you design and build an end-to-end data pipeline?

I usually start by understanding the business requirements and expected outputs. Then I profile the source data, checking schemas, data types, code values, missing data, and duplicates.

I use Azure Data Factory to orchestrate the pipeline. For incremental loading, I use CDC when available, or a watermark-based approach. For file-based ingestion, I can use Databricks Auto Loader.

I maintain metadata and control tables to store pipeline configurations, processing status, timestamps, and checkpoints.

To make pipelines reusable and scalable, I use metadata-driven frameworks and parameterized configurations. I also use Delta MERGE with appropriate business keys to support idempotent processing and prevent duplicate records.

For security and governance, I use Microsoft Entra ID, role-based access control, and Unity Catalog to manage access and data lineage.

My goal is to deliver reusable, scalable, reliable, and idempotent data pipelines that are ready for production and downstream consumption.

How do you design a metadata–driven framework to automate repetitive data integration tasks?

Yes, I’ve designed metadata-driven frameworks before.

I start by understanding the business requirements. Then I profile the source data and identify the schema, data types, and loading method.

I use metadata tables to store source and target information. I also store schemas, file locations, load types, and other configuration values.

At runtime, the pipeline reads the metadata. It then passes the configuration values to the right activities.

For incremental loading, I use CDC when the source supports it. For file-based data, I can use Databricks Auto Loader. I can also use watermarks to track incremental progress.

I maintain control tables to track run IDs, timestamps, processing status, checkpoints, and row counts.

For data quality, I check schemas, data types, missing values, and duplicates. I also compare source and target record counts and business control totals.

I never simply drop invalid records. I move them to a quarantine area and notify the responsible team. After the issues are fixed, I reprocess the records.

For security, I use Microsoft Entra ID, RBAC, Key Vault, and Unity Catalog.

The main benefit is reusability. For supported source patterns, I can onboard new sources by updating the metadata. I don’t need to build a separate pipeline for every source.

How do you design a data architecture that is scalable, reusable, and easy to maintain?

I usually start by understanding the business requirements, business processes, and expected outcomes.

Then I profile the source data. I check the schema, data types, volume, and data quality. I also identify the relationships between the data and the business needs.

Next, I design the data models. I define the conceptual and logical models first. If data comes from multiple domains, I may use a canonical model to standardize business terms and codes. For analytical data, I define the grain and design the fact and dimension tables.

For implementation, I follow the Medallion architecture: Bronze, Silver, and Gold. I use Azure Data Factory for ingestion and Databricks for data validation, cleaning, and transformation.

To make the solution reusable, I build metadata-driven pipelines. Configuration tables define the source, target, load type, and processing rules. Control tables track the run status, timestamps, and checkpoints. This allows me to onboard new data sources through configuration instead of building a separate pipeline for each source.

I also implement incremental loading, data quality checks, source-to-target reconciliation, and quarantine handling.

For security, I use Microsoft Entra ID, role-based access control, and Unity Catalog.

My goal is to build data solutions that are reusable, scalable, secure, and easy to maintain.

How do you design data models and schemas for analytics and downstream data consumers?

Yes, I’ve designed data models schemas for downstream consumption.

I start with the business requirements. I understand the business process, business events, and expected outcomes.

Then I define the grain. I make sure each fact table has a clearly defined and consistent grain.

Next, I design the fact tables, dimension tables, business keys, schemas, and relationships.

I also design conceptual, logical, and physical data models.

When data comes from different domains, business terms, definitions, and code values may differ. I use a canonical data model to standardize the data across these domains.

I also define clear schemas, column names, and data types. This makes the data easier to understand and use.

Finally, I prepare consistent, well-structured tables for downstream consumption. These tables support reports, visualizations, and Power BI semantic models.

How would you integrate operational source data from multiple systems to support planning and day-of operations?

Yes, I have handled the similar projects multiple source domains before.

I would start by understanding the business requirements and the business’ operational needs. For example, the airport may need to combine flight, baggage, and ground operations data to support planning and daily operations.

First, I would identify the source systems, data owners, data formats, refresh frequency, and data quality issues. I would also clarify whether the business needs batch processing or near-real-time data.

Then, I would use Azure Data Factory to ingest the data and Databricks to process it through the Bronze, Silver, and Gold layers.

Since the data comes from different systems, I would standardize the schemas, business keys, timestamps, and code values. I would use a canonical data model where needed to make the data consistent.

I would also implement data quality checks and source-to-target reconciliation. If records were invalid, I would quarantine them for review instead of simply dropping them.

For incremental loading, I would use CDC when available. For file-based data, I could use Auto Loader. Otherwise, I would use watermarks and control tables.

I would apply access controls and data governance, and monitor the pipelines to ensure they run reliably.

Finally, I would work with airport operations teams to validate the results against their business requirements.

My goal would be to provide reliable, consistent, and timely data that helps airport teams make better operational decisions.

How do you Migrating existing ETL processes into production and make them reliable and maintainable?

Yes, I’ve migrated existing ETL processes to modern data platforms before.

First, I understand the business requirements and review the existing ETL process. I check the business logic, dependencies, source data, data quality, and expected outcomes.

Then I assess the target environment and identify the risks. I prepare a backup and recovery plan before making any changes.

Next, I define the source-to-target mapping and design the new solution. I choose the migration approach based on the business requirements, technical needs, and risk level.

Before deployment, I test the new solution. I validate the business logic, data quality, and transformation results. I also reconcile the source and target data.

During migration, I keep the existing solution running when possible. This helps reduce business disruption and provides a fallback option.

After deployment, I compare the old and new solutions. I check record counts, key business totals, and transformation results. I also work with stakeholders to confirm that the new solution meets the requirements.

For production support, I configure logging, monitoring, alerts, and error handling. I also prepare an operational runbook that covers dependencies, recovery steps, and rollback procedures. I use version control and CI/CD to make future changes safer and easier to maintain.

My goal is to deliver a reliable, recoverable, and maintainable solution with minimal business disruption.

How do you collaborate with Data Scientists to prepare data and deploy machine learning models into production?

Yes, I’ve worked with Data Scientists to deploy AI/LLM , Machine Learning in my previous projects.

First, I understand the business requirements and expected outcomes. Then I work with the Data Scientists to understand their data needs, including schemas, data types, required features, and refresh frequency.

I prepare curated data using Databricks, PySpark, and SQL. I validate the data to make sure it is accurate, consistent, and complete.

I also build metadata-driven frameworks to automate data preparation and refresh. This makes the process reusable and easier to maintain.

For AI and RAG solutions, I prepare enterprise documents and extract metadata. I also support chunking, embedding, and indexing in a vector store.

For security, I follow the principle of least privilege. Users and applications only have access to the data they need.

Finally, I implement logging and monitoring. I work with the Data Scientists to resolve data issues and support production use.

My goal is to provide reliable, secure, and reusable data pipelines for analytics, machine learning, and AI applications.

How do you manage data governance, security, access control, and compliance in a data platform?

Yes, I’ve managed data governance, security and compliance in my previous projects.

First, I understand the business requirements and the company’s security policies.

I use Microsoft Entra ID to manage identities. I use role-based access control to manage permissions for users, groups, and applications.

I follow the principle of least privilege. I only give them the access they need.

In Databricks, I use Unity Catalog to manage data access and governance. I also use data lineage to track where the data comes from.

For secrets, I use Azure Key Vault to store passwords, API keys, and connection strings. Pipelines can retrieve these secrets securely at runtime.

My goal is to protect data, control access, and meet the company’s security and compliance requirements.

How do you troubleshoot a data pipeline that fails or runs much slower than expected in production?

Yes, I’ve handled performance tuning and troubleshooting in production.

For performance tuning, I first establish a baseline. I don’t make changes before identifying the bottleneck.

I check the business requirements and profile the source data. Then I review the logs and use Spark UI to identify slow tasks, shuffle operations, and data skew.

I also review the SQL queries. I filter data early and select only the required columns. If one side of a join is small enough, I consider using a broadcast join.

For data skew, I check the root cause. Depending on the situation, I may use AQE or salting. If there are too many small files, I consider Delta Lake OPTIMIZE. If a dataset is reused several times, I consider caching it.

Finally, I compare the results with the baseline to confirm the improvement.

For pipeline failures, I first check the logs and alerts. I identify the failed activity and assess the impact on downstream systems.

Then I review recent changes, source data, ingestion, transformation, validation, and reconciliation. I also check the business logic to find the root cause.

If it is a data issue, I work with the responsible team to correct it. If it is a technical issue, I fix the code or configuration.

After fixing the issue, I rerun the process safely. I validate the results and reconcile the data before confirming recovery.

My goal is to restore the pipeline quickly and keep it reliable, accurate, and scalable.

How do you implement CI/CD, DevOps, and DataOps practices for data engineering?

Yes, I’ve done this CI/CD, DevOps in my project.

I use GitHub for version control and Azure DevOps to automate the CI/CD process.

Each team member works on a separate branch. After completing the code, they create a pull request. Another team member reviews the changes. Once approved, the code is merged into the main branch.

I also use Scrum to organize the work into sprints and track progress against milestones.

For deployment, I maintain separate development, SIT, UAT, and production environments. I use Azure DevOps pipelines to automate testing and promote approved changes between environments.

I also include data quality checks and reconciliation to make sure the pipeline produces the expected results. Before production deployment, I work with stakeholders to complete validation and obtain sign-off.

In addition, I document the changes and maintain operational runbooks. I also make sure deployment issues can be investigated and resolved safely.

My goal is to make releases reliable, traceable, repeatable, and easy to maintain.

What is Databricks’ architecture?

Databricks uses a lakehouse architecture. It combines a data lake and a data warehouse.

There are three main parts.

First, the control plane manages the workspace, notebooks, and jobs.

Second, the compute plane runs Spark jobs and SQL queries. It processes the data.

Third, the storage layer stores data in cloud storage, such as Azure Data Lake Storage. Delta Lake helps keep the data accurate and reliable.

We often use the medallion architecture to organize data.

The Bronze layer stores raw data. The Silver layer cleans and transforms the data. The Gold layer stores data for business reports and analytics.

We also use Unity Catalog to manage data access and permissions.

Together, these components help us build secure and scalable data solutions.

How do you optimize data pipelines when working with large and heterogeneous datasets?

Yes, I’ve optimized data pipelines before.

First, I establish a baseline. This helps me measure the improvement.

Then I profile the data. I check the data volume, schema, data types, and data quality.

I review the SQL queries. I select only the necessary columns and filter data before joins.

If one side of a join is small enough, I use a broadcast join. If I reuse a dataset several times, I consider caching it.

I also use Spark UI to identify bottlenecks. I check slow tasks, shuffle operations, and data skew.

If there are too many small files, I use Delta Lake OPTIMIZE when needed. I also review the partition strategy and enable AQE when appropriate.

For large datasets, I use incremental loading. I use CDC when available. Otherwise, I may use a watermark or file-based processing.

I maintain control tables to track job IDs, processing status, timestamps, and checkpoints.

Finally, I compare the results with the baseline. My goal is to reduce runtime and cost while keeping the pipeline reliable and scalable.

How do you ensure data quality and data consistency across multiple source systems?

Yes, I’ve handled data quality and consistency across multiple source systems.

First, I understand the business requirements and profile the source data. I check the schema, data types, missing values, and duplicates.

When data comes from different systems, business definitions and code values may differ. I use a canonical data model to standardize the data.

Then I use Databricks to validate the data. I check schemas, data types, business rules, and code values. I also remove duplicate records based on business keys and timestamps.

Next, I reconcile the source and target data. I compare record counts, business keys, and business control totals.

I never simply drop invalid records. I move them to a quarantine area and notify the responsible team. After the issues are fixed, I reprocess the records.

I also use Delta MERGE to insert new records and update existing records. Control tables help me track processing status and results.

My goal is to deliver consistent, accurate, and reliable data for production and downstream analytics.

How do you monitor data pipelines and ensure they run reliably in production?

Yes, I’ve done monitor data pipelines in my prijects before.

In one of my previous projects, I worked on a metadata-driven data platform. We incrementally loaded data from around 12 to 18 source tables every day.

First, I used Azure Data Factory monitoring and Databricks job monitoring to track pipeline execution. I also maintained logging and control tables. These tables recorded the run ID, source information, start and end times, processing status, and checkpoints.

I configured alerts to notify the responsible team when a pipeline failed or encountered an issue.

I also implemented data quality checks in Databricks. These checks covered schemas, data types, code values, missing values, and duplicate records.

For reconciliation, I compared source and target record counts and key business control totals. If records were invalid or failed validation, I routed them to a quarantine area instead of simply dropping them. The responsible team could review and fix the issues before we safely reran the pipeline.

After recovery, I validated the results and confirmed that the data was consistent.

My goal is to detect problems early, recover safely, and keep production pipelines reliable and stable.

How do you handle changing business requirements during a data engineering project?

Yes, I’ve handled changing requirements in a previous project involving nearly 50 tables.

We were already in the middle of development when the business requirements changed.

First, I reviewed the new requirements and compared them with the existing ones. I worked with business stakeholders to clarify the changes, including the business rules and data refresh frequency.

Then I assessed the impact on the data model, pipeline design, development effort, testing, and delivery timeline.

For major changes, I built a proof of concept to validate the proposed solution. I also discussed the risks, effort, and timeline with the team and stakeholders before we agreed on the approach.

Once the changes were approved, I updated the design and implemented the required changes. I also updated the test cases and validated the schema, data types, business rules, and source-to-target reconciliation.

Finally, I documented the changes and obtained stakeholder confirmation that the solution met the updated requirements.

My goal is to manage changes in a controlled way while maintaining data quality and delivering a reliable solution that meets business needs.

How do you implement incremental data loading and handle CDC, updates, and duplicate records?

Yes, I’ve implemented incremental data loading before.

First, I check the source system and its capabilities.

If CDC is available, I use it to capture inserts, updates, and deletes.

For file-based data, I use Databricks Auto Loader to process new files.

If CDC is not available, I can use a watermark. I maintain a control table to track run IDs, timestamps, processing status, and checkpoints.

To handle duplicates, I use ROW_NUMBER with a business key and update timestamp. This helps me keep the latest record for each key.

Then I use Delta MERGE to insert new records and update existing records. I deduplicate the source data before the merge and use stable business keys.

If the source does not provide delete events, I check for a soft-delete flag or audit table. If the source provides a full snapshot, I can compare source and target keys to identify possible deletions.

Finally, I design the pipeline to be idempotent. If a job fails and runs again, it should not create duplicate records.

This makes the pipeline reliable and easier to recover.

How do you design reusable data pipelines and support self-service analytics through semantic models and Power BI?

Yes, I’ve done this before. I worked on a Greenfield data platform project involving nearly 500 tables.

First, I built reusable, metadata-driven pipelines using Azure Data Factory and Databricks. I used metadata and control tables to manage source information, load types, processing status, and checkpoints.

For incremental loading, I used CDC when available. Otherwise, I used watermarks or other suitable loading methods.

I also implemented data quality checks, including schema validation, business rules, and source-to-target reconciliation. If records were invalid, I isolated them for review instead of simply dropping them.

To support self-service analytics, I prepared curated Gold-layer data and designed fact tables, dimension tables, and clear relationships. I also supported Power BI semantic models with consistent business definitions and reusable measures.

This allowed business analysts to create their own reports, filter data, and analyze different business dimensions without depending on data engineers for every reporting request.

Because the data came from different business domains, I also used a canonical data model to standardize definitions and improve consistency.

My goal was to provide reusable pipelines and trusted data, so business users could perform self-service analytics more efficiently.

How do you work with business stakeholders and data analysts to translate business requirements into data solutions?

Yes, I’ve done this – translate business requirements into data solutions, before.

In one of my previous projects, I worked on incremental data loading from databases. The solution processed around 32 to 50 megabytes of data per day and involved between 12 and 80 tables.

First, I understood the business process and expected outcomes. I worked with key stakeholders and data analysts to clarify business definitions, required outputs, acceptance criteria, and refresh SLAs.

Then I profiled the source data. I checked schemas, data types, missing values, duplicates, and code values. I also created source-to-target mappings, Data dictionary, Business glossary and designed conceptual, logical, and physical data models.

Because the data came from multiple domains, some business definitions and code values were different. I designed a canonical data model to standardize them and make the data consistent.

Based on the agreed requirements, I built the data pipelines using Azure Data Factory and Databricks. I implemented data validation, transformation, deduplication, and source-to-target reconciliation.

I compared record counts, business keys, and key business control totals. I then worked with stakeholders and data analysts to validate the results against the acceptance criteria.

After business sign-off, I moved the solution into production and prepared the documentation and operational runbook.

My goal was to translate business requirements into a reliable, scalable, and maintainable data solution.

Landing Zone

A Microsoft Landing Zone usually refers to an Azure Landing Zone (often part of the Cloud Adoption Framework (CAF)). It is a pre-built, best-practice cloud foundation that organizations use to deploy workloads in Azure in a secure, governed, and scalable way.

A Landing Zone is the “foundation environment” in the cloud:

  • networking is ready
  • security is enforced
  • identity is centralized
  • governance is in place
  • logging & monitoring are enabled

Core Components

  • Identity & Access (Entra ID)
    • Central authentication
    • RBAC roles
  • Networking
    • Hub-Spoke architecture
    • VNet design
    • Private endpoints
  • Governance
    • Policies (Azure Policy)
    • Management Groups
    • Resource tagging standards
  • Security
    • Microsoft Defender for Cloud
    • Security baselines
    • Key Vault for secrets
  • Monitoring
    • Log Analytics
    • Azure Monitor
    • Alerting system
Star schema vs Snowflake schema

Star schema has a central fact table connected directly to denormalized dimension tables. It is simple and fast for querying.
Snowflake schema has normalized dimension tables, where dimensions are split into multiple related tables.

Snowflake = more normalized, less redundancy but more joins

Star = simpler, faster queries

How do you design a dimensional model?

I design it using business requirements:

  • Align with BI/reporting needs
  • Identify facts (measures) like sales, transactions
  • Identify dimensions like customer, product, time
  • Choose grain (very important)
  • Use surrogate keys for dimensions
  • Apply star schema for analytics performance

What is Azure Data Factory?

Azure Data Factory is a cloud-based data integration service used to create data-driven workflows for orchestrating and automating data movement and transformation across different data stores and compute services.

Key capabilities

  • Data ingestion
  • Data orchestration
  • Data transformation
  • Scheduling and monitoring
What are the core components of ADF?

The main components are:

ComponentPurpose
PipelineLogical grouping of activities
ActivitySingle task in a pipeline
DatasetData structure pointing to data
Linked ServiceConnection to external resources
TriggerSchedule or event that starts a pipeline
Integration RuntimeCompute infrastructure used to run activities
What is a Pipeline?

A pipeline is a logical grouping of activities that together perform a task such as data ingestion or transformation.

What is Integration Runtime (IR)?

Integration Runtime is the compute infrastructure used by ADF to perform data integration tasks.

  • Azure IR Fully managed compute in Azure
  • Self-hosted IR Runs on on-premises machines
  • Azure SSIS IR Used to run SSIS packages

Types:

What is a Linked Service?

A linked service defines the connection information needed for ADF to connect to external resources, example:

  • Azure SQL Database
  • Data Lake
  • databricks
  • On-Prem database
What is a Dataset?

A dataset represents the structure of data within a data store.

Difference between Pipeline and Data Flow
FeaturePipelineData Flow
PurposeOrchestrationData transformation
ComputeOrchestration engineSpark cluster
UIActivity workflowVisual transformation
How do you handle incremental loading?

Solution 1: Watermark column
last_modified_date:
Max(Last_modified)
WHERE last_modified > last_run_time

Solution 2: CDC
transaction log
change tracking

Solution 3: File-based incremental
folder partition by date

How do you implement error handling?

Try-Catch pattern
Failure path
Retry policy

Activity
├ success → next step
└ failure → error handling pipeline

What are triggers in ADF?

Triggers are used to automatically start pipelines.

TriggerPurpose
Schedule triggerTime-based execution
Tumbling windowTime-based incremental
Event triggerStorage events
What is Tumbling Window Trigger?

A tumbling window trigger runs pipelines at fixed time intervals and processes data in discrete time windows.

How do you parameterize pipelines?

ADF supports parameters at:

  • Linked Service
  • plpeline
  • dataset
What are common ADF performance optimizations?

Parallel copy: pipeline success; pipeline duration; failure rate
Staging: use blob staging
Partitioning: split large tables

How do you monitor pipelines?

Monitoring options:
ADF Monitor UI
Azure Monitor
Log Analytics

Difference between Mapping Data Flow vs Pipeline

Azure Data Factory Pipeline is an orchestration layer used to coordinate activities (copy, Databricks, API calls).
Mapping Data Flow is a visual ETL engine running on Spark for transformations without coding

How do you handle retries and failure recovery?

I handle failures using:

  • Delta Lake ACID for safe writes and rollback support
  • ADF retry policies (activity-level retries)
  • Idempotent pipeline design (safe re-runs)
  • Checkpointing in streaming jobs
  • Logging + monitoring (Log Analytics / Databricks logs)
How do you orchestrate Databricks notebooks from ADF?

I use ADF Databricks Notebook activity:

  • Prefer job clusters for cost optimization
  • Pass parameters from ADF to notebook
  • Use cluster or job cluster
  • Chain multiple notebooks in pipeline
  • Use retries + monitoring in ADF
ADF retry policies (activity-level retries)

ADF supports built-in retry at the activity level:

  • You can configure retry count + interval
  • Used for transient failures (network, timeout, throttling)
  • Works per activity (Copy, Databricks, Web, etc.)
  • Combined with timeout settings for better resilience

But retries should not replace good design (idempotency is still required).

ADF → Databricks Notebook failure: how do you know what happened?

From ADF side, I rely on:

  • Activity output logs
    • ADF captures Databricks job run URL + run ID
  • Error message propagation
    • ADF shows Databricks notebook failure message (exit code / exception summary)
  • Databricks Job Run API / UI
    • Use run ID to open detailed error logs in Databricks
  • Log Analytics integration
    • Centralized monitoring if enabled
  • Notebook logging best practice
    • Explicit try/except + logging errors back to ADF (custom messages)

So ADF gives high-level error, Databricks gives detailed stack trace.

How do you manage “Schema Drift” when ingesting data from diverse, changing corporate sources using Azure Data Factory (ADF)?

Answer: * I design a resilient ingest architecture rather than forcing hardcoded mappings. In ADF, I use Mapping Data Flows with the “Allow Schema Drift” option enabled so the pipeline doesn’t break when a source team adds a column.

When landing data into the Databricks Bronze layer, I utilize Databricks Auto Loader (cloudFiles) with Schema Evolution enabled (.option("mergeSchema", "true")). This allows Delta Lake to automatically infer and append new columns to the table schema on-the-fly, while isolating structural alerts into a monitoring log.


Describe the data storage options available in Databricks.

Databricks offers several ways to store data. First, there’s the Databricks File System for storing and managing files. Then, there’s Delta Lake, an open-source storage layer that adds ACID transactions to Apache Spark, making it more reliable. Databricks also integrates with cloud storage services like AWS S3, Azure Blob Storage, and Google Cloud Storage. Plus, you can connect to a range of external databases, both relational and NoSQL, using JDBC.

What is Databricks Delta (Delta Lakehouse) and how does it enhance the capabilities of Azure Databricks?

Databricks Delta, now known as Delta Lake, is an open-source storage layer that brings ACID transactions to Apache Spark and big data workloads. It enhances Azure Databricks by providing features like:

  • ACID transactions for data reliability and consistency.
  • Scalable metadata handling for large tables.
  • Time travel for data versioning and historical data analysis.
  • Schema enforcement and evolution.
  • Improved performance with data skipping and Z-ordering
Are there any alternative solution that is similar to Delta lakehouse?

there are several alternative technologies that provide Delta Lake–style Lakehouse capabilities (ACID + schema enforcement + time travel + scalable storage + SQL engine). such as,

  • Apache Iceberg
  • Apache Hudi
  • Snowflake (Iceberg Tables / Unistore)
  • BigQuery + BigLake
  • AWS Redshift + Lake Formation + Apache Iceberg
  • Microsoft Fabric (OneLake + Delta/DQ/DLTS)
What is Delta Live Table? Have you used DLT?

Yes. Delta Live Tables, or DLT, is a Databricks framework for building and managing reliable data pipelines. In current Databricks terminology, it is part of Lakeflow Declarative Pipelines, but DLT is still commonly used in projects and interviews.

I have used DLT in my previous projects, mainly for production data pipelines using the Bronze, Silver, and Gold architecture.

For example, in the Bronze layer, we ingested raw data from sources such as APIs, files, and enterprise systems. In Silver, we used DLT for data cleansing, validation, deduplication, CDC processing, and business transformations. The Gold layer provided curated datasets for reporting and downstream applications.

One of the key features I used was data quality expectations. I could define rules such as required business keys, valid values, and data completeness. Depending on the requirement, invalid records could be quarantined or handled separately instead of simply being dropped, while the pipeline continued processing valid data.

DLT is also declarative, which means I define what the target datasets should look like and how they depend on upstream data, rather than manually managing every execution step. Databricks manages things such as pipeline dependencies, incremental processing, monitoring, and lineage.

I also used DLT with incremental processing and CDC patterns, including identifying new or changed records using business keys and timestamps and applying changes to Delta tables.

So, in my experience, DLT is not just a transformation tool. I used it as part of a production-grade data engineering solution, covering ingestion, transformation, data quality, incremental processing, CDC, dependency management, monitoring, and the overall Bronze-Silver-Gold architecture.

Why DLT instead of regular Databricks jobs?

I would use DLT when I need a more managed and reliable data pipeline, especially for multi-stage production pipelines.

The main advantage is that DLT provides a declarative approach. I define the data transformations and dependencies, and Databricks manages much of the pipeline execution.

It also provides built-in capabilities for data quality expectations, dependency management, incremental processing, lineage, monitoring, and pipeline recovery.

For example, if I have a Bronze-to-Silver-to-Gold pipeline with multiple dependent datasets, DLT can manage those dependencies and process the data incrementally instead of requiring me to build all of that orchestration logic myself.

Regular Databricks Jobs are still very useful, especially for custom Python or PySpark processing, batch jobs, orchestration, and tasks that don’t naturally fit a declarative pipeline.

So I would say the key difference is: Databricks Jobs are primarily an execution and orchestration mechanism, while DLT provides a more complete framework for building and operating reliable data pipelines.

Delat Live table vs Telta Table side by side

Delta Table vs Delta Live Tables (Side-by-Side)

FeatureDelta TableDelta Live Tables (DLT)
DefinitionStorage layer built on Delta Lake formatManaged ETL framework built on top of Delta Lake
Main PurposeStore reliable data with ACID propertiesBuild and manage data pipelines automatically
TypeData storage / table formatData pipeline orchestration framework
ResponsibilityUser manages ETL logic manuallySystem manages ETL pipeline automatically
Pipeline ManagementNot includedBuilt-in (dependency handling, orchestration)
Data ProcessingManual (SQL / PySpark / Spark jobs)Declarative (define tables, system executes pipeline)
ETL ControlFully controlled by developerPartially automated (framework-managed execution)
Data Quality RulesNot built-inBuilt-in (expect, expect_or_drop, etc.)
MonitoringExternal tools requiredBuilt-in monitoring & observability
Lineage TrackingManual or external toolsAutomatic lineage tracking
Streaming SupportManual setup requiredNative streaming support built-in
Incremental ProcessingManually implementedAutomatically handled
Error Handling / RetryDeveloper must implementBuilt-in retry & recovery
CI/CD IntegrationPossible but manualFully integrated with pipelines
Underlying StorageParquet-based Delta formatUses Delta Tables underneath
Use CaseStore data, build tables, SQL analyticsBuild production ETL pipelines (Bronze/Silver/Gold)
Complexity LevelLower concept complexityHigher abstraction, easier operations
What is schema evolution in Delta Lake?

Schema evolution allows Delta tables to automatically or manually adapt when new columns are added or schema changes occur, without breaking pipelines.

What is Schema Enforcement?

Schema Enforcement means the system validates incoming data against a predefined schema before writing the data. It checks column names, data types, and structure to ensure data consistency and quality. And the system will reject the write or throw an error if incoming data does not match the expected schema.

What is Schema Contract?

A schema contract is an agreement between a data producer and a data consumer that defines the expected structure and rules of the data.

For example, it can define the required columns, data types, nullable rules, and sometimes business constraints.

The purpose is to make sure the producer and consumer have a clear and stable understanding of what the data should look like.

For example, if the contract says customer_id must be a non-null STRING, the producer should always provide the data in that format. If the producer wants to make a breaking change, such as changing the data type, that change needs to be agreed upon and managed.

So, in simple terms, a schema contract is the agreed data interface between the producer and the consumer.

What is Time Travel?

Time Travel is a feature that allows you to access and query previous versions of data in a table.

In Delta Lake, every data change (insert, update, delete) is versioned. This means the system keeps a history of changes, and you can query the table as it existed at a specific point in time or version.

SELECT * FROM table VERSION AS OF 5;
SELECT * FROM table TIMESTAMP AS OF '2024-01-01';
Explain how you can use Databricks to implement a Medallion Architecture (Bronze, Silver, Gold).
  1. Bronze Layer (Raw Data): Ingest raw data from various sources into the Bronze layer. This data is stored as-is, without any transformation.
  2. Silver Layer (Cleaned Data, as known Enriched layer): Clean and enrich the data from the Bronze layer. Apply transformations, data cleansing, and filtering to create more refined datasets.
  3. Gold Layer (Aggregated Data, as known Curated layer): Aggregate and further transform the data from the Silver layer to create high-level business tables or machine learning features. This layer is used for analytics and reporting.
What Is Z-Order (Databricks / Delta Lake)?

Z-Ordering in Databricks (specifically for Delta Lake tables) is an optimization technique designed to co-locate related information into the same set of data files on disk.

OPTIMIZE mytable
ZORDER BY (col1, col2);
What Is Liquid Clustering (Databricks)?

Liquid Clustering is Databricks’ next-generation data layout optimization for Delta Lake.
It replaces (and is far superior to) Z-Order.

## At creation time:
CREATE TABLE sales
CLUSTER BY (customer_id, event_date)
AS SELECT * FROM source;

## For existing tables:
ALTER TABLE sales
CLUSTER BY (customer_id, event_date);

## Trigger the actual clustering:
OPTIMIZE sales;

## Remove clustering:
ALTER TABLE sales
CLUSTER BY NONE;
What is broadcast? Have you used it?

Broadcast is a Spark optimization. It sends a small table to all worker nodes, so Spark can join it with a large table without shuffling the large table across the cluster.

Yes, I have used broadcast joins in Databricks to improve join performance, especially when joining a large fact table with a small dimension table.

I usually check the table size and the Spark execution plan before using it.

from pyspark.sql.functions import broadcast

result = large_df.join(
    broadcast(small_df),
    "customer_id",
    "inner"
)
What is catching and its types?

A cache is a temporary storage that holds frequently accessed data, aiming to reduce latency and enhance speed. Caching involves the process of storing data in cache memory.

What is Spark Cache / Persist (Memory Cache)

This is the standard Apache Spark feature. It stores data in the JVM Heap (Memory).

What is Databricks Disk Cache (Local Disk)

This is a Databricks-specific optimization. It automatically stores copies of remote files (Parquet/Delta) on the local NVMe SSDs of the worker nodes.

comparing .cache() and .persist()

both .cache() and .persist() are used to save intermediate results to avoid re-computing the entire lineage. The fundamental difference is that .cache() is a specific, pre-configured version of .persist().

.cache(): This is a shorthand for .persist(StorageLevel.MEMORY_ONLY). It tries to store your data in the JVM heap as deserialized objects.

.persist(): This is the more flexible version. It allows you to pass a StorageLevel to decide exactly how and where the data should be stored (RAM, Disk, or both).

How do you optimize Databricks?

When optimizing Databricks workloads, I focus on several layers. First, I optimize data layout using partitioning and Z-ordering on Delta tables. Second, I improve Spark performance by using broadcast joins, filtering data early, and caching intermediate results. Third, I tune cluster resources such as autoscaling and Photon engine. Finally, I run Delta maintenance commands like OPTIMIZE and VACUUM to manage small files and improve query performance.

Data Layout Optimization:
Partitioning:
CREATE TABLE sales
USING DELTA
PARTITIONED BY (date)

Z-Ordering:
OPTIMIZE sales
ZORDER BY (customer_id);

Liquid Clustering:

What is Photon Engine?

Photon is a high-performance query engine built in C++ that accelerates SQL queries and data processing workloads in Azure Databricks. It improves performance by using vectorized processing and optimized execution for modern hardware.

What is Data skew,

Data skew happens when some partitions have much more data than others, causing slow tasks and performance bottlenecks.

Data skew usually happens during:

  • Joins
  • GroupBy
  • Aggregations
When designing a production pipeline in Databricks, how do you diagnose and mitigate data skew or memory-related issues like Out of Memory (OOM) errors?

Answer: * Diagnosis: I look at the Spark UI. If one task takes significantly longer than others (Stage Skew) or if an executor’s memory usage spikes and drops unexpectedly, it indicates data skew. If an executor JVM dies entirely, it’s an OOM error.

I optimize partitioning using Adaptive Query Execution (AQE) or implement Liquid Clustering in Delta Lake to maintain balanced, performance-aware file sizes.

Mitigation for Skew: * If joining on a skewed key, I leverage Broadcast Joins if one table is small enough.

For larger tables, I use Skew Hints in Spark SQL (/*+ SKEW('tablename', 'columnname') */) to force Spark to salt the skewed key automatically.

Mitigation for OOM: * I review the code for anti-patterns like calling .collect() on large DataFrames.

How to fix Data Skew
  1. Salting: split one hot key into multiple keys
    for example: Add a random key to spread data across partitions.
    sample data:
    Partition 1: US (1M rows) ← Skew, slow
    Partition 2: UK (10k rows)
    Partition 3: CA (5k rows)

    doing this “Salting”
    df = df.withColumn("salt", rand() % 10)
    result:
    US_0 → 200k
    US_1 → 200k
    US_2 → 200k
    US_3 → 200k
    US_4 → 200k


    then re-partition by the new “salt” column
    df.repartition("salt")

    AFTER (Salting)
    Partition 1: US_0
    Partition 2: US_1
    Partition 3: US_2
    Partition 4: US_3
    Partition 5: US_4
  2. Better Partitioning: Repartition data using a better key.
    df.repartition(“country”)
  3. AQE:
    AQE (Adaptive Query Execution) in Spark dynamically optimizes query execution during runtime.

    How to enable AQE. It can adjust join strategies, merge small partitions, and handle data skew by splitting large partitions based on real execution statistics instead of static estimates.
    spark.conf.set("spark.sql.adaptive.enabled", "true")
How do you handle late-arriving data?

I handle late-arriving data using a combination of watermarks and incremental processing.

I allow a defined time window for late data. For records that arrive later, I use Delta Lake MERGE to insert new records or update existing ones.

I also track processing status and use reconciliation checks to make sure the data is complete and accurate.

I handle late data using:

  • Reprocessing logic for backfill if needed
  • Event-time processing (not processing-time)
  • Watermarking in Structured Streaming
  • Window-based aggregations
  • Delta Lake MERGE INTO for upserts
Difference between batch vs streaming in Databricks

Batch processing processes data in chunks at scheduled intervals, while streaming processes data continuously in near real-time.

Databricks uses Structured Streaming, which treats streaming as incremental batch processing with fault tolerance.

How do you manage cluster sizing and cost optimization?

I manage cost by:

  • Using Photon and Delta optimizations to reduce compute time
  • Using autoscaling clusters
  • Choosing right node types (memory vs compute optimized)
  • Using job clusters instead of all-purpose clusters
  • Auto-termination for idle clusters
How do you validate data quality?

I validate data quality using:

  • Row count validation
  • Null checks
  • Duplicate checks
  • Data type validation
  • Referential integrity checks
  • Business rule validation

I usually automate these checks in pipelines and log failures.

How do you monitor pipeline failures?

I monitor failures using:

  • ADF Monitor
  • Databricks job monitoring
  • Log Analytics / Azure Monitor
  • Alerts and notifications (email/Teams)
  • Custom logging tables

I also track pipeline run IDs for troubleshooting.

What metrics do you track in production pipelines?

Key production metrics:

  • Pipeline success/failure rate
  • Execution duration
  • Throughput
  • Data latency
  • Row counts
  • Error counts
  • Cluster utilization/cost
  • SLA compliance

These help identify performance or reliability issues.

How do you handle schema drift?

Schema drift happens when source schema changes unexpectedly.

I handle it by:

  • Enabling schema evolution
  • Using dynamic column mapping
  • Metadata-driven pipelines
  • Auto Loader schema inference
  • Logging and alerting schema changes
  • Separating mandatory vs optional columns
How would you secure and manage secrets in Azure Databricks when connecting to external data sources?
  1. Use Azure Key Vault to store and manage secrets securely.
  2. Integrate Azure Key Vault with Azure Databricks using Databricks-backed or Azure-backed scopes.
  3. Access secrets in notebooks and jobs using the dbutils.secrets API.
    dbutils.secrets.get(scope=”<scope-name>”, key=”<key-name>”)
  4. Ensure that secret access policies are strictly controlled and audited.
How do you design a scalable ingestion pipeline?

I design it using a layered approach (Medallion Architecture):

  • Bronze: raw ingestion (batch/streaming via ADF / Auto Loader)
  • Silver: cleaned and standardized data
  • Gold: business-ready aggregated data

For scalability:

  • Use Auto Loader for incremental file ingestion
  • Use partitioning + incremental loads
  • Decouple ingestion and transformation
  • Use Delta Lake for reliability and ACID
Scenario: You need to implement a data governance strategy in Azure Databricks. What steps would you take?

  • Data Classification: Classify data based on sensitivity and compliance requirements.
  • Access Controls: Implement role-based access control (RBAC) using Azure Active Directory.
  • Data Lineage: Use tools like Databricks Lineage to track data transformations and movement.
  • Audit Logs: Enable and monitor audit logs to track access and changes to data.
  • Compliance Policies: Implement Azure Policies and Azure Purview for data governance and compliance monitoring.
Scenario: You need to optimize a Spark job that has a large number of shuffle operations causing performance issues. What techniques would you use?
  1. Repartitioning: Repartition the data to balance the workload across nodes and reduce skew.
  2. Broadcast Joins: Use broadcast joins for small datasets to avoid shuffle operations.
  3. Caching: Cache intermediate results to reduce the need for recomputation.
  4. Shuffle Partitions: Increase the number of shuffle partitions to distribute the workload more evenly.
  5. Skew Handling: Identify and handle skewed data by adding salt keys or custom partitioning strategies.
Scenario: You need to migrate an on-premises Hadoop workload to Azure Databricks. Describe your migration strategy.
  • Assessment: Evaluate the existing Hadoop workloads and identify components to be migrated.
  • Data Transfer: Use Azure Data Factory or Azure Databricks to transfer data from on-premises HDFS to ADLS.
  • Code Migration: Convert Hadoop jobs (e.g., MapReduce, Hive) to Spark jobs and test them in Databricks.
  • Optimization: Optimize the Spark jobs for performance and cost-efficiency.
  • Validation: Validate the migrated workloads to ensure they produce the same results as on-premises.
  • Deployment: Deploy the migrated workloads to production and monitor their performance.
Can you explain the difference between running a PySpark workload using a Databricks Notebook versus deploying it as modular Python code via Databricks Jobs? When would you choose one over the other?

Answer: * Databricks Notebooks are excellent for ad-hoc exploration, rapid prototyping, and interactive data analysis. They combine markdown documentation with executable code blocks, making them highly visual.

Decision Criteria: For production ETL pipelines, I advocate for modular code deployed via Databricks Jobs. It allows us to implement proper software engineering practices, such as unit testing (via pytest), static code analysis, and robust CI/CD branch policies. Notebooks are kept strictly for initial R&D or orchestrating lightweight, high-level control flows.

Modular Python Code (e.g., packaged .py files/wheels) breaks logic down into reusable, unit-testable classes and functions.

What is the difference between df.collect() and df.take(n) or df.show()

Answer: * df.collect() pulls every single row from the distributed executors across the network and dumps it into the memory of the single Driver node, converting the Spark DataFrame into a local Python list. It is highly dangerous because if the data volume exceeds the Driver’s available RAM, it triggers an immediate OOM crash.

df.take(n) and df.show(n) only retrieve the first n rows. They are safe because they cap the memory allocation on the Driver, making them ideal for debugging or lightweight data sampling.

Migrate from Hive Metastore to Unity Catalog, what would be your step-by-step strategy to handle data migration, permissions, and governance?

Step 1 — Enable Unity Catalog
Step 2 — Create Catalog and Schema
Step 3 — Configure External Location

Step 4 — Assess Hive Tables: Check:

  • managed vs external tables
  • Delta vs non-Delta
  • table size
  • dependencies
  • downstream jobs
  • permissions

Step 5 — Convert Non-Delta Tables (IMPORTANT)
CONVERT TO DELTA parquet.`abfss://container/path`;
or
CONVERT TO DELTA hive_metastore.sales.orders;

Step 6 — Migrate Tables

CREATE TABLE finance.sales.orders
DEEP CLONE hive_metastore.sales.orders;

or 

CREATE TABLE finance.sales.orders AS
SELECT * FROM hive_metastore.sales.orders;

or 
SYNC TABLE finance.sales.orders
FROM hive_metastore.sales.orders;
SYNC works mainly for: external tables and metadata sync scenarios

Step 7 — Migrate Permissions
GRANT SELECT ON TABLE finance.sales.orders TO analysts;

How do you handle credential rotation and secure workspace access using Databricks Secrets and Azure Key Vault in a heavily locked-down or regulated financial services environment?

Answer: * Hardcoding passwords or keys in code is strictly prohibited. I create an Azure Key Vault-backed Secret Scope within Databricks.

All database passwords, API keys, and service principal secrets live inside Azure Key Vault. When Databricks runs a pipeline, it fetches these secrets securely at runtime using dbutils.secrets.get(). Credential rotation is handled upstream entirely within Azure Key Vault (often via automated Azure Functions), and Databricks automatically reflects the rotated values without requiring code changes.

What is Delta Sharing?have you used it?

Yes. Delta Sharing is an open protocol developed by Databricks for securely sharing data across different organizations, platforms, and cloud environments without requiring the recipient to copy or physically move the underlying data.

I have used Delta Sharing in Databricks environments to share Delta tables and curated datasets with downstream consumers. For example, instead of creating another physical copy of the data for a consumer, we can provide controlled access to the shared data through a Delta Share.

A key advantage is that the provider can control what data is shared and who can access it. We can share specific tables or views rather than giving consumers direct access to the underlying storage.

In a typical implementation, the provider creates a share and adds the required tables or views. The recipient is then granted access and can consume the shared data using supported clients, without needing access to the provider’s underlying ADLS or cloud storage.

I also see Delta Sharing as useful for cross-organization and cross-cloud data sharing, because the consumer doesn’t necessarily need to be on the same Databricks workspace or even the same cloud platform.

So the key point is: Delta Sharing provides governed data sharing without requiring traditional data copying or giving the consumer direct access to the underlying storage.

What is Unity Catalog Volumes?

Unity Catalog Volumes provide a governed way to manage non-tabular files in cloud storage through Unity Catalog.

in short, Delta tables are for structured/tabular data; Volumes are for files, unstructured.

Unity Catalog Volumes provide a governed way to access and manage files in cloud storage that are not necessarily Delta tables.

I have used Volumes in Databricks environments for file-based data such as documents, JSON, CSV, and other files that need to be accessed by data engineering or AI workloads.

There are two main types: managed volumes and external volumes. With a managed volume, Databricks manages the underlying storage. With an external volume, the data remains in an external cloud storage location such as ADLS Gen2, while Unity Catalog provides centralized governance and access control.

One of the main benefits is that users and workloads can access files through a governed Unity Catalog path such as /Volumes/<catalog>/<schema>/<volume>/..., rather than directly accessing cloud storage credentials or storage paths.

This is particularly useful when we need to apply centralized access control, auditing, and governance to file-based data.

So, in simple terms, Unity Catalog tables are primarily for governed structured data, while Volumes provide governed access to files.

What is the difference between a bundle and a Databricks job?

A Databricks Asset Bundle is a way to define, manage, and deploy Databricks resources as code. It uses YAML configuration files to describe resources such as jobs, pipelines, and their settings. It also supports version control and CI/CD across development, test, and production environments.

We define our jobs, notebooks, source files, and environment settings in configuration files. Then we deploy them through the Databricks CLI.

A Databricks Job is used to run and orchestrate tasks. For example, a job might execute a notebook, run a Python script, or trigger a Lakeflow pipeline. It can define task dependencies, schedules, retries, and parameters.

We store the code in Git and use Azure DevOps to automate testing and deployment.

The key difference is that a bundle manages and deploys resources, while a job executes and orchestrates data processing tasks.

This approach improves consistency, version control, and deployment reliability.

What is a Dataframe, RDD, Dataset in Azure Databricks?

Dataframe refers to a specified form of tables employed to store the data within Databricks during runtime. In this data structure, the data will be arranged into two-dimensional rows and columns to achieve better accessibility.

RDD, Resilient Distributed Dataset, is a fault-tolerant, immutable collection of elements partitioned across the nodes of a cluster. RDDs are the basic building blocks that power all of Spark’s computations.

Dataset is an extension of the DataFrame API that provides compile-time type safety and object-oriented programming benefits.


What are Synapse SQL Workspaces and how are they used?

Synapse SQL Workspaces are the environments within Azure Synapse Analytics where users can perform data querying and management tasks. They include:

  • Provisioned SQL Pools: Used for large-scale, high-performance data warehousing. Users can create and manage databases, tables, and indexes, and run complex queries.
  • On-Demand SQL Pools: Allow users to query data directly from Azure Data Lake without creating a dedicated data warehouse. It is ideal for interactive and exploratory queries.
 What is the difference between On-Demand SQL Pool and Provisioned SQL Pool?

The primary difference between On-Demand SQL Pool and Provisioned SQL Pool lies in their usage and scalability:

  • On-Demand SQL Pool: Allows users to query data stored in Azure Data Lake without requiring a dedicated resource allocation. It is best for ad-hoc queries and does not incur costs when not in use. It scales automatically based on query demand.
  • Provisioned SQL Pool: Provides a dedicated set of resources for running data warehousing workloads. It is optimized for performance and can handle large-scale data operations. Costs are incurred based on the provisioned resources and are suitable for predictable, high-throughput workloads.
 How does Azure Synapse Analytics handle data integration?

Azure Synapse Analytics handles data integration through Synapse Pipelines, which is a data integration service built on Azure Data Factory. It enables users to:

  • Ingest Data: Extract data from various sources, including relational databases, non-relational data stores, and cloud-based services.
  • Transform Data: Use data flows and data wrangling to clean and transform data.
  • Orchestrate Workflows: Schedule and manage data workflows, including ETL (Extract, Transform, Load) processes.
  • Data Integration Runtime: Utilizes Azure Integration Runtime for data movement and transformation tasks.

Can you explain the concept of “Dedicated SQL Pool” in Azure Synapse Analytics?

Dedicated SQL Pool is a provisioned, high-performance relational database.

  • Data Storage: Data must be ingested and stored internally in a proprietary columnar format. It follows a Schema-on-Write approach.
  • Architecture: Uses MPP (Massively Parallel Processing) architecture. Data is sharded into 60 distributions and processed by multiple compute nodes in parallel.
  • Cost: Billed by the hour based on the provisioned DWUs. You can pause it when not in use to save costs.
  • Best For: Stable production reporting, TB/PB scale enterprise data warehousing, and high-concurrency queries needing sub-second response.
What is Serverless SQL Pool and when would you use it?

Serverless SQL Pool is an on-demand, compute-only query engine with no internal storage.

  • Data Location: It does not store data. Data remains in the Data Lake (ADLS Gen2) in open formats like Parquet, CSV, or JSON.
  • Mechanism: Uses the OPENROWSET function to query lake files directly. It follows a Schema-on-Read approach.
  • Cost: Billed per query based on data scanned (approx. $5 USD per TB). Cost is $0 if no queries are run.
  • Best For: Rapid data discovery, building a Logical Data Warehouse, and ad-hoc data validation.

It is a managed Apache Spark 3 instance easily created and configured within Azure.

  • Managed Cluster: You don’t manage servers; you just select the node size and the number of nodes.
  • Auto-Scale & Auto-Pause: It automatically scales nodes based on workload and pauses after 5 minutes of inactivity to save costs.
  • Language Support: Supports PySpark (Python), Spark SQL, Scala, and .NET.

Can you give an example of a prompt design you used to help document a complex pipeline or generate validation test cases, including the constraints you applied?

Answer: * Effective prompt design relies on clear persona, context, and explicit constraints.

Example Prompt: “You are an expert Data Architect. Act as a technical documentation writer. Analyze the following PySpark code which performs a Type 2 Slowly Changing Dimension (SCD Type 2) merge. Write a technical markdown document explaining the data lineage, column mappings, and transformation logic. Constraints: Do not use placeholder code. Do not explain standard PySpark syntax. Format the column mappings strictly in a markdown table. Highlight the idempotency mechanics of the code.”

Using Generative AI tools responsibly to improve engineering velocity. How do you use tools like GitHub Copilot or ChatGPT to scaffold notebooks, write unit tests, or optimize slow SQL queries?

I use generative AI tools like GitHub Copilot and ChatGPT as productivity accelerators across development, testing, and optimization, but always within a controlled and validated engineering workflow.

For example, when building Databricks notebooks, I use Copilot to scaffold initial PySpark structures such as data ingestion patterns, Delta table reads/writes, and common transformation templates. This helps me quickly set up a working baseline, especially for standard ETL/ELT pipelines, while I focus on business logic, data modeling, and performance design.

For unit testing, I use ChatGPT or Copilot to generate initial PySpark or SQL test cases, such as null checks, schema validation, row count verification, and data quality rules. I then refine these tests to align with data contracts and production expectations, ensuring they are meaningful and not just syntactically correct.

For SQL optimization, I often use ChatGPT to analyze slow queries and suggest improvements like better join strategies, partition pruning, or indexing considerations. However, I always validate improvements using query execution plans, Databricks Spark UI, and actual runtime benchmarks before applying changes.

In all cases, I treat AI as an assistant rather than an authority. I ensure no sensitive or PII data is included in prompts, and all AI-generated code is reviewed, tested, and validated before production deployment. The goal is to improve engineering velocity without compromising correctness, security, or governance.

What are your strict guardrails regarding Data Governance and Security when using Generative AI tools? How do you ensure that sensitive corporate data, business logic, or PII (Personally Identifiable Information) are never leaked in a prompt?

Answer: * Data privacy is paramount, especially in financial services. My absolute rule is that no actual client data, proprietary database schemas, or PII can ever enter a commercial AI prompt.

When utilizing AI for troubleshooting or code generation, I completely anonymize and abstract the prompt. I swap out proprietary table names for generic placeholders (e.g., Table_A, Table_B), obfuscate custom column names (e.g., changing account_balance_cad to metric_1), and generate synthetic mockup rows if I need to illustrate a data structure issue.

AI can occasionally “hallucinate” code or logic. What is your process for validating AI-assisted code outputs before submitting a Pull Request (PR) for a peer review?

I never take AI-generated code at face value; it must be fully verified. My validation process includes:

Unit Testing: Verify the output against expected boundaries (checking edge cases like handling of Null values or empty DataFrames). Only after it passes automated testing do I integrate it into the codebase and open a PR.

Code Review & Linting: Check for syntax errors, deprecated Spark methods, or non-existent library parameters.

Local/Dev Execution: Run the generated code block inside a isolated scratchpad environment using a small, controlled sample dataset.


Can you talk about database locker?

Database locking is the mechanism a database uses to control concurrent access to data so that transactions stay consistent, isolated, and safe.

Locking prevents:

  • Dirty reads
  • Lost updates
  • Write conflicts
  • Race conditions

Types of Locks:

1. Shared Lock (S)

  • Used when reading data
  • Multiple readers allowed
  • No writers allowed

2. Exclusive Lock (X)

  • Used when updating or inserting
  • No one else can read or write the locked item

3. Update Lock (U) (SQL Server specific)

  • Prevents deadlocks when upgrading from Shared → Exclusive
  • Only one Update lock allowed

4. Intention Locks (IS, IX, SIX)

Used at table or page level to signal a lower-level lock is coming.

5. Row / Page / Table Locks

Based on granularity:

  • Row-level: Most common, best concurrency
  • Page-level: Several rows together
  • Table-level: When scanning or modifying large portions

DB engines automatically escalate:

Row → Page → Table
when there are too many small locks.

Can you talk on Deadlock?

A deadlock happens when:

  • Transaction A holds Lock 1 and wants Lock 2
  • Transaction B holds Lock 2 and wants Lock 1

Both wait on each other → neither can move → database detects → kills one transaction (“deadlock victim”).

Deadlocks usually involve one writer + one writer, but can also involve readers depending on isolation level.

How to Troubleshoot Deadlocks?
A: In SQL Server: Enable Deadlock Graph Capture
run:
ALTER DATABASE [YourDB] SET DEADLOCK_PRIORITY NORMAL;

use:
DBCC TRACEON (1222, -1);
DBCC TRACEON (1204, -1);
B: Interpret the Deadlock Graph

You will see:

  • Processes (T1, T2…)
  • Resources (keys, pages, objects)
  • Types of locks (X, S, U, IX, etc.)
  • Which statement caused the deadlock

Look for:

  • Two queries touching the same index/rows in different order
  • A scanning query locking too many rows
  • Missed indexes
  • Query patterns that cause U → X lock upgrades
C. Identify
  • The exact tables/images involved
  • The order of locking
  • The hotspot row or range
  • Rows with heavy update/contention

This will tell you what to fix.

How to Prevent Deadlocks (Practical + Senior-Level)
  • Always update rows in the same order
  • Keep transactions short
  • Use appropriate indexes
  • Use the correct isolation level
  • Avoid long reads before writes
Can you discuss on database normalization and denormalization

Normalization is the process of structuring a relational database to minimize data redundancy (duplicate data) and improve data integrity.

Normal FormRule SummaryProblem Solved
1NF (First)Eliminate repeating groups; ensure all column values are atomic (indivisible).Multi-valued columns, non-unique rows.
2NF (Second)Be in 1NF, AND all non-key attributes must depend on the entire primary key.Partial Dependency (non-key attribute depends on part of a composite key).
3NF (Third)Be in 2NF, AND eliminate transitive dependency (non-key attribute depends on another non-key attribute).Redundancy due to indirect dependencies.
BCNF (Boyce-Codd)A stricter version of 3NF; every determinant (column that determines another column) must be a candidate key.Edge cases involving multiple candidate keys.

Denormalization is the process of intentionally introducing redundancy into a previously normalized database to improve read performance and simplify complex queries.

  • Adding Redundant Columns: Copying a value from one table to another (e.g., copying the CustomerName into the Orders table to avoid joining to the Customer table every time an order is viewed).
  • Creating Aggregate/Summary Tables: Storing pre-calculated totals, averages, or counts to avoid running expensive aggregate functions at query time (e.g., a table that stores the daily sales total).
  • Merging Tables: Combining two tables that are frequently joined into a single, wider table.
How do you optimize slow SQL queries?

I optimize SQL by:

  • Checking execution plan first
  • Adding proper indexes (if relational DB)
  • Reducing data scanned (filter early)
  • Avoiding unnecessary joins
  • Using partition pruning in Spark/Delta
  • Using caching or materialized views
  • Optimizing joins (broadcast small tables)
What is DBT? How do you use DBT?

DBT stands for Data Build Tool. It is used to transform data in a data warehouse or lakehouse.

I use DBT to transform raw data into clean, trusted data.

First, I connect DBT to the data platform. Then, I write SQL models to clean data, join tables, and apply business rules.

I use tests to check data quality. For example, I check for null values, duplicate records, and missing keys.

I also use DBT to manage dependencies between models and generate documentation.

Finally, I use Git to manage code changes and schedule DBT jobs to run automatically.

This makes data transformation easier to maintain, test, and reuse.






Data Migration Checklist: A Starting Point

Creating a robust data migration checklist can be challenging, particularly for those new to the process. To simplify this, we’ve compiled a core set of essential activities for effective data migration planning. This checklist, designed to support thorough preparation for data migration projects, has been successfully used across diverse migration projects over several years, including those for financial institutions (including banks), insurance companies, consulting firms, and other industries. While not exhaustive, it provides a solid foundation that can be customized with project-specific requirements.

It is available for download as a template.

Please do not hesitate to contact me if you have any questions at William . chen @ mainri.ca

(remove all space from the email account 😊)

Implementing Slowly Changing Dimension Type 2 Using Delta Lake on Databricks

Built on Apache Spark, Delta Lake provides a robust storage layer for data in Delta tables. Its features include ACID transactions, high-performance queries, schema evolution, and data versioning, among others.

Today’s focus is on how Delta Lake simplifies the management of slowly changing dimensions (SCDs).

Quickly review Type 2 of Slowly Changing Dimension 

A quick recap of SCD Type 2 follows:

  • Storing historical dimension data with effective dates.
  • Keeping a full history of dimension changes (with start/end dates).
  • Adding new rows for dimension changes (preserving history).
# Existing Dimension data
surrokey  depID   dep	StartDate   EndDate     IsActivity
1	  1001	  IT	2019-01-01  9999-12-31  1
2	  1002	  Sales	2019-01-01  9999-12-31  1
3	  1003	  HR	2019-01-01  9999-12-31  1

# Dimension changed and new data comes 
depId dep
1003  wholesale   <--- depID is same, name changed from "Sales" to "wholesale"
1004  Finance     <--- new data

# the new Dimension will be:
surrokey  depID	dep	   StartDate   EndDate     IsActivity 
1	  1001	IT	   2019-01-01  9999-12-31  1   <-- No action required
2	  1002	HR	   2019-01-01  9999-12-31  1   <-- No action required
3	  1003	Sales	   2019-01-01  2020-12-31  0   <-- mark as inactive
4         1003  wholesale  2021-01-01  9999-12-31  1   <-- add updated active value
5         1004  Finance    2021-01-01  9999-12-31  1   <-- insert new data

Creating demo data

We’re creating a Delta table, dim_dep, and inserting three rows of existing dimension data.

Existing dimension data

%sql
# Create table dim_dep
%sql
create table dim_dep (
Surrokey BIGINT  GENERATED ALWAYS AS IDENTITY
, depID  int
, dep	string
, StartDate   DATE 
, End_date DATE 
, IsActivity BOOLEAN
)
using delta
location 'dbfs:/mnt/dim/'

# Insert data
insert into dim_dep (depID,dep, StartDate,EndDate,IsActivity) values
(1001,'IT','2019-01-01', '9999-12-31' , 1),
(1002,'Sales','2019-01-01', '9999-12-31' , 1),
(1003,'HR','2019-01-01', '9999-12-31' , 1)

select * from dim_dep
Surrokey depID	dep	StartDate	EndDate	        IsActivity
1	 1001	IT	2019-01-01	9999-12-31	true
2	 1002	Sales	2019-01-01	9999-12-31	true
3	 1003	HR	2019-01-01	9999-12-31	true
%python
dbutils.fs.ls('dbfs:/mnt/dim')
path	name	size	modificationTime
Out[43]: [FileInfo(path='dbfs:/mnt/dim/_delta_log/', name='_delta_log/', size=0, modificationTime=0),
 FileInfo(path='dbfs:/mnt/dim/part-00000-5f9085db-92cc-4e2b-886d-465924de961b-c000.snappy.parquet', name='part-00000-5f9085db-92cc-4e2b-886d-465924de961b-c000.snappy.parquet', size=1858, modificationTime=1736027755000)]

New coming source data

The new coming source data which may contain new record or updated record.

Dimension changed and new data comes 
depId       dep
1002        wholesale 
1003        HR  
1004        Finance     

  • depID 1002, dep changed from “Sales” to “wholesale”, updating dim_dep table;
  • depID 1003, nothing changed, no action required
  • depID 1004, is a new record, inserting into dim_dep

Assuming the data, originating from other business processes, is now stored in the data lake as CSV files.

Implementing SCD Type 2

Step 1: Read the source

%python 
df_dim_dep_source = spark.read.csv('dbfs:/FileStore/dep.csv', header=True)

df_dim_dep_source.show()
+-----+---------+
|depid|      dep|
+-----+---------+
| 1002|Wholesale|
| 1003|       HR|
| 1004|  Finance|
+-----+---------+

Step 2: Read the target

df_dim_dep_target = spark.read.format("delta").load("dbfs:/mnt/dim/")

df_dim_dep_target.show()
+--------+-----+-----+----------+----------+----------+
|Surrokey|depID|  dep| StartDate|   EndDate|IsActivity|
+--------+-----+-----+----------+----------+----------+
|       1| 1001|   IT|2019-01-01|9999-12-31|      true|
|       2| 1002|Sales|2019-01-01|9999-12-31|      true|
|       3| 1003|   HR|2019-01-01|9999-12-31|      true|
+--------+-----+-----+----------+----------+----------+

Step 3: Source Left outer Join Target

We perform a source dataframe – df_dim_dep_source, left outer join target dataframe – df_dim_dep_target, where source depID = target depID, and also target’s IsActivity = 1 (meant activity)

This join’s intent is not to miss any new data coming through source. And active records in target because only for those data SCD update is required. After joining source and target, the resultant dataframe can be seen below.

src = df_dim_dep_source
tar = df_dim_dep_target
df_joined = src.join (tar,\
        (src.depid == tar.depID) \
         & (tar.IsActivity == 'true')\
        ,'left') \
    .select(src['*'] \
        , tar.Surrokey.alias('tar_surrokey')\
        , tar.depID.alias('tar_depID')\
        , tar.dep.alias('tar_dep')\
        , tar.StartDate.alias('tar_StartDate')\
        , tar.EndDate.alias('tar_EndDate')\
        , tar.IsActivity.alias('tar_IsActivity')   )
    
df_joined.show()
+-----+---------+------------+---------+-------+-------------+-----------+--------------+
|depid|      dep|tar_surrokey|tar_depID|tar_dep|tar_StartDate|tar_EndDate|tar_IsActivity|
+-----+---------+------------+---------+-------+-------------+-----------+--------------+
| 1002|Wholesale|           2|     1002|  Sales|   2019-01-01| 9999-12-31|          true|
| 1003|       HR|           3|     1003|     HR|   2019-01-01| 9999-12-31|          true|
| 1004|  Finance|        null|     null|   null|         null|       null|          null|
+-----+---------+------------+---------+-------+-------------+-----------+--------------+

Step 4: Filter only the non matched and updated records

In this demo, we only have depid and dep two columns. But in the actual development environment, may have many many columns.

Instead of comparing multiple columns, e.g.,
src_col1 != tar_col1,
src_col2 != tar_col2,
…..
src_colN != tar_colN
We compute hashes for both column combinations and compare the hashes. In addition of this, in case of column’s data type is different, we convert data type the same one.

from pyspark.sql.functions import col , xxhash64

df_filtered = df_joined.filter(\
    xxhash64(col('depid').cast('string'),col('dep').cast('string')) \
    != \
    xxhash64(col('tar_depID').cast('string'),col('tar_dep').cast('string'))\
    )
    
df_filtered.show()
+-----+---------+------------+---------+-------+-------------+-----------+--------------+
|depid|      dep|tar_surrokey|tar_depID|tar_dep|tar_StartDate|tar_EndDate|tar_IsActivity|
+-----+---------+------------+---------+-------+-------------+-----------+--------------+
| 1002|Wholesale|           2|     1002|  Sales|   2019-01-01| 9999-12-31|          true|
| 1004|  Finance|        null|     null|   null|         null|       null|          null|
+-----+---------+------------+---------+-------+-------------+-----------+--------------+

from the result, we can see:

  • The row, dep_id = 1003, dep = HR, was filtered out because both source and target side are the same. No action required.
  • The row, depid =1002, dep changed from “Sales” to “Wholesale”, need updating.
  • The row, depid = 1004, Finance is brand new row, need insert into target side – dimension table.

Step 5: Find out records that will be used for inserting

From above discussion, we have known depid=1002, need updating and depid=1004 is a new rocord. We will create a new column ‘merge_key’ which will be used for upsert operation. This column will hold the values of source id.

Add a new column – “merge_key”

df_inserting = df_filtered. withColumn('merge_key', col('depid'))

df_inserting.show()
+-----+---------+------------+---------+-------+-------------+-----------+--------------+---------+
|depid|      dep|tar_surrokey|tar_depID|tar_dep|tar_StartDate|tar_EndDate|tar_IsActivity|merge_key|
+-----+---------+------------+---------+-------+-------------+-----------+--------------+---------+
| 1002|Wholesale|           2|     1002|  Sales|   2019-01-01| 9999-12-31|          true|     1002|
| 1004|  Finance|        null|     null|   null|         null|       null|          null|     1004|
+-----+---------+------------+---------+-------+-------------+-----------+--------------+---------+
The above 2 records will be inserted as new records to the target table

The above 2 records will be inserted as new records to the target table.

Step 6: Find out the records that will be used for updating in target table

from pyspark.sql.functions import lit
df_updating = df_filtered.filter(col('tar_depID').isNotNull()).withColumn('merge_key',lit('None')

df_updating.show()
+-----+---------+------------+---------+-------------+-----------+--------------+---------+
|depid|      dep|tar_surrokey|tar_depID|tar_StartDate|tar_EndDate|tar_IsActivity|merge_key|
+-----+---------+------------+---------+-------------+-----------+--------------+---------+
| 1003|Wholesale|           3|     1003|   2019-01-01| 9999-12-31|          true|     None|
+-----+---------+------------+---------+-------------+-----------+--------------+---------+
The above record will be used for updating SCD columns in the target table.

This dataframe filters the records that have tar_depID column not null which means, the record already exists in the table for which SCD update has to be done. The column merge_key will be ‘None’ here which denotes this only requires update in SCD cols.

Step 7: Combine inserting and updating records as stage

df_stage_final = df_updating.union(df_instering)

df_stage_final.show()
+-----+---------+------------+---------+-------+-------------+-----------+--------------+---------+
|depid|      dep|tar_surrokey|tar_depID|tar_dep|tar_StartDate|tar_EndDate|tar_IsActivity|merge_key|
+-----+---------+------------+---------+-------+-------------+-----------+--------------+---------+
| 1002|Wholesale|           2|     1002|  Sales|   2019-01-01| 9999-12-31|          true|     None| <-- updating in SCD table
| 1002|Wholesale|           2|     1002|  Sales|   2019-01-01| 9999-12-31|          true|     1002| <-- inserting in SCD table
| 1004|  Finance|        null|     null|   null|         null|       null|          null|     1004| <-- inserting in SCD table
+-----+---------+------------+---------+-------+-------------+-----------+--------------+---------+
  • records with merge_key as none are for updating in existing dimension table.
  • records with merge_key not null will be inserted as new records in dimension table.

Step 8: Upserting the dim_dep Dimension Table

Before performing the upsert, let’s quickly review the existing dim_dep table and the incoming source data.

# Existing dim_dep table
spark.read.table('dim_dep').show()
+--------+-----+-----+----------+----------+----------+
|Surrokey|depID|  dep| StartDate|   EndDate|IsActivity|
+--------+-----+-----+----------+----------+----------+
|       1| 1001|   IT|2019-01-01|9999-12-31|      true|
|       2| 1002|Sales|2019-01-01|9999-12-31|      true|
|       3| 1003|   HR|2019-01-01|9999-12-31|      true|
+--------+-----+-----+----------+----------+----------+

# coming updated source data
park.read.csv('dbfs:/FileStore/dep_src.csv', header=True).show()
+-----+---------+
|depid|      dep|
+-----+---------+
| 1002|Wholesale|
| 1003|       HR|
| 1004|  Finance|
+-----+---------+

Implementing an SCD Type 2 UpSert on the dim_dep Dimension Table

from delta.tables import DeltaTable
from pyspark.sql.functions import current_date, to_date, lit

# define the source DataFrame
src = df_stage_final  # this is a DataFrame object

# Load the target Delta table
tar = DeltaTable.forPath(spark, "dbfs:/mnt/dim")  # target Dimension table


# Performing the UpSert
tar.alias("tar").merge(
    src.alias("src"),
    condition="tar.depID == src.merge_key and tar_IsActivity = 'true'"
).whenMatchedUpdate( \
    set = { \
        "IsActivity": "'false'", \
        "EndDate": "current_date()" \
        }) \
.whenNotMatchedInsert( \
    values = \
    {"depID": "src.depid", \
    "dep": "src.dep", \
    "StartDate": "current_date ()", \
    "EndDate": """to_date('9999-12-31', 'yyyy-MM-dd')""", \
    "IsActivity": "'true' \
    "}) \
.execute()

all done!

Validating the result

spark.read.table('dim_dep').sort(['depID','Surrokey']).show()
+--------+-----+---------+----------+----------+----------+
|Surrokey|depID|      dep| StartDate|   EndDate|IsActivity|
+--------+-----+---------+----------+----------+----------+
|       1| 1001|       IT|2019-01-01|9999-12-31|      true|
|       2| 1002|    Sales|2019-01-01|2020-01-05|     false| <--inactived
|       4| 1002|Wholesale|2020-01-05|9999-12-31|      true| <--updated status
|       3| 1003|       HR|2019-01-01|9999-12-31|      true|
|       5| 1004|  Finance|2020-01-05|9999-12-31|      true| <--append new record
+--------+-----+---------+----------+----------+----------+

Conclusion

we demonstrated how to unlock the power of Slowly Changing Dimension (SCD) Type 2 using Delta Lake, a revolutionary storage layer that transforms data lakes into reliable, high-performance, and scalable repositories.  With this approach, organizations can finally unlock the full potential of their data and make informed decisions with confidence

Please do not hesitate to contact me if you have any questions at William . chen @ mainri.ca

(remove all space from the email account 😊)

delta: Schema Evolution

Schema Evolution in Databricks refers to the ability to automatically adapt and manage changes in the structure (schema) of a Delta Lake table over time. It allows users to modify the schema of an existing table (e.g., adding or updating columns) without the need for a complete rewrite of the data.

Key Features of Schema Evolution

  1. Automatic Adaptation: Delta Lake can automatically evolve the schema of a table when new columns are added to the incoming data, or when data types change, if certain configurations are enabled.
  2. Backward and Forward Compatibility: Delta Lake ensures that new data can be written to a table without breaking the existing schema. It also ensures that existing queries remain compatible, even if the schema changes.

Configuration for Schema Evolution

mergeSchema

This option allows you to append new data with a schema that differs from the existing table schema. It merges the new schema into the table.

Usage: Typically used when you are appending data.

Schema Merging: Use mergeSchema only for adding new columns, not for incompatible changes.

When new data has additional columns that aren’t present in the target Delta table, Delta Lake can automatically merge the new schema into the existing table schema.


# Append new data to the Delta table with automatic schema merging

df_new_data.write.format("delta").mode("append").option("mergeSchema", "true").save("/path/to/delta-table")


overwriteSchema

This option is used when you want to completely replace the schema of the table with the schema of the new data.

If you want to replace the entire schema (including removing existing columns), you can use the overwriteSchema option.


# Overwrite the existing Delta table schema with new data

df_new_data.write.format("delta").mode("overwrite").option("overwriteSchema", "true").save("/path/to/delta-table")


Configure spark.databricks.delta.schema.autoMerge

You can configure this setting at the following levels:

Usage: Typically used when you are overwriting data

  • Session Level (applies to a specific session or job)
  • Cluster Level (applies to all jobs on the cluster)

Session-Level Configuration (Spark session level)

Once this is enabled, all write and merge operations in the session will automatically allow schema evolution.


# Enable auto schema merging for the session

spark.conf.set("spark.databricks.delta.schema.autoMerge.enabled", "true")

Cluster-Level Configuration

This enables automatic schema merging for all operations on the cluster without needing to set it in each job.

  1. Go to your Databricks Workspace.
  2. Navigate to Clusters and select your cluster.
  3. Go to the Configuration tab.
  4. Under Spark Config, add the following configuration:
    spark.databricks.delta.schema.autoMerge.enabled true

Please do not hesitate to contact me if you have any questions at William . chen @ mainri.ca

(remove all space from the email account 😊)

Delta: Time Travel of Delta Table

Time Travel in Delta Lake allows you to query, restore, or audit the historical versions of a Delta table. This feature is useful for various scenarios, including recovering from accidental deletions, debugging, auditing changes, or simply querying past versions of your data.

Delta Lake maintains a transaction log that records all changes (inserts, updates, deletes) made to the table. Using Time Travel, you can access a previous state of the table by specifying a version number or a timestamp.

By default, data file retention is 7 days, log file retention is 30 days. After 7 days, file will delete, but log file still there.

You can access historical versions of a Delta table using two methods:

  1. By Version Number
  2. By Timestamp

Viewing Table History

# sql
DESCRIBE HISTORY my_delta_table;

Query a certain version Table

You can query a Delta table based on a specific version number by using the VERSION AS OF clause. Or timestamp using the TIMESTAMP AS OF clause.


# sql
SELECT * FROM my_delta_table VERSION AS OF 5;


#Python
spark.sql("SELECT * FROM my_delta_table VERSION AS OF 5")

Restore the Delta Table to an Older Version

You can use the RESTORE command to revert the Delta table to a previous state permanently. This modifies the current state of the Delta table to match a past version or timestamp. Delta Lake maintains the transaction log retention period set for the Delta table (by default, 30 days)

#sql
--restore table to earlier version 4
-- by version
RESTORE TABLE delta.`abfss://container@adlsAccount.dfs.windows.net/myDeltaTable` TO VERSION OF 4;

-- by timestamp
RESTORE TABLE my_delta_table TO TIMESTAMP AS OF '2024-10-07T12:30:00';

#python
spark.sql("RESTORE TABLE my_delta_table TO VERSION AS OF 5")
spark.sql("RESTORE TABLE my_delta_table TO TIMESTAMP AS OF '2024-10-07T12:30:00'")

Vacuum Command

The VACUUM command in Delta Lake is used to remove old files that are no longer in use by the Delta table. When you make updates, deletes, or upserts (MERGE) to a Delta table, Delta Lake creates new versions of the data while keeping older versions for Time Travel and data recovery. Over time, these old files can accumulate, consuming storage. The VACUUM command helps clean up these files to reclaim storage space.

This command will remove all files older than 7 days (by Default)


# sql
VACUUM my_delta_table;

# python
spark.sql("VACUUM my_delta_table")

Retention Duration Check

The configuration property


%sql
SET spark.databricks.delta.retentionDurationCheck.enabled = false / true;

spark.databricks.delta.retentionDurationCheck.enable in Delta Lake controls whether Delta Lake enforces the retention period check for the VACUUM operation. By default, Delta Lake ensures that data files are only deleted after the default retention period (typically 7 days) to prevent accidentally deleting files that might still be required for Time Travel or recovery.

When VACUUM is called, Delta Lake checks if the specified retention period is shorter than the minimum default (7 days). If it is, the VACUUM command will fail unless this safety check is disabled.

You can disable this check by setting the property spark.databricks.delta.retentionDurationCheck.enable to false, which allows you to set a retention period of less than 7 days or even vacuum data immediately (0 hours).

Disable the Retention Duration Check


#sql
SET spark.databricks.delta.retentionDurationCheck.enabled = false;

#python
spark.conf.set("spark.databricks.delta.retentionDurationCheck.enabled", "false")

set log Retention Duration


#sql 
# Set the log retention duration to 7 days
SET spark.databricks.delta.logRetentionDuration = '7 days';

# python 
# Set the log retention duration to 7 days
spark.conf.set("spark.databricks.delta.logRetentionDuration", "7 days")


Custom Retention Period


# sql
VACUUM my_delta_table RETAIN 1 HOURS;

# python
spark.sql("VACUUM my_delta_table RETAIN 1 HOURS")

Force Vacuum (Dangerous)


# sql
VACUUM my_delta_table RETAIN 0 HOURS;

Conclusion:

Delta Lake’s Time Travel feature is highly beneficial for data recovery, auditing, and debugging by enabling access to historical data versions. It provides flexibility to query and restore previous versions of the Delta table, helping maintain the integrity of large-scale data operations.

Please do not hesitate to contact me if you have any questions at William . chen @ mainri.ca

(remove all space from the email account 😊)

Delta Table, Delta Lake

A Delta table is a type of table that builds on the Delta Lake storage layer and brings ACID (Atomicity, Consistency, Isolation, Durability) transactions, schema enforcement, and scalable metadata management to traditional data lakes. It is designed for large-scale, reliable data processing and analytics. Delta tables enable you to manage both batch and streaming data with ease, and they are ideal for environments where data integrity and consistency are critical, such as in data lakes, data warehouses, and machine learning pipelines.

What is Delta Lake

Delta lake is an open-source technology, we use Delta Lake to store data in Delta tables. Delta lake improves data storage by supporting ACID transactions, high-performance query optimizations, schema evolution, data versioning and many other features.

FeatureTraditional Data LakesDelta Lake
Transaction SupportNo ACID transactionsFull ACID support
Data ConsistencyWeak guaranteesStrong guarantees with serializable isolation
Schema EnforcementNoneEnforced and allows schema evolution
Handling StreamingRequires separate infrastructureUnified batch and streaming
Data ManagementProne to issues like data corruptionReliable with audit trails and versioning
key differences

There is detail information at “Data lake vs delta lake vs data lakehouse, and data warehouses comparison”

Key Features of Delta Tables

  1. ACID Transactions: Delta Lake ensures that operations like reads, writes, and updates are atomic, consistent, isolated, and durable, eliminating issues of partial writes and data corruption.
  2. Schema Enforcement: When writing data, Delta ensures that it matches the table’s schema, preventing incorrect or incomplete data from being written.
  3. Time Travel: Delta tables store previous versions of the data, which allows you to query, rollback, and audit historical data (also known as data versioning).
  4. Unified Streaming and Batch Processing: Delta tables allow you to ingest both batch and streaming data, enabling you to work seamlessly with either approach without complex rewrites.
  5. Efficient Data Upserts: You can perform MERGE operations (UPSERTS) efficiently, which is especially useful in scenarios where you need to insert or update data based on certain conditions.
  6. Optimized Performance: Delta Lake supports optimizations such as data skipping, Z-order clustering, and auto-compaction, improving query performance.

Using Delta Tables in PySpark or SQL

If we directly query a existing delta table from ADLS using SQL, always use

 --back single quotation mark `
delta.`abfss://contain@account.dfs.windows.net/path_and_table`

Register, Create, Write a Delta table

Register a table point it to existing Delta table location

# sql
-- register a table point it to existing Delta table location
delta_table_path = "dbfs:/mnt/delta/table_path"
# Register the Delta table in the metastore
spark.sql(f"""
CREATE TABLE table_name
USING DELTA
LOCATION '{delta_table_path}'
""")

Creating a Delta Table

-- Creating a Delta Table
%sql
CREATE TABLE my_delta_table (
id int,
name string
)
USING delta
LOCATION '/mnt/delta/my_delta_table';

Write to delta table

# python
# Write a DataFrame to a Delta table
df.write.format("delta").save("/mnt/delta/my_delta_table")

# sql
-- Insert data
INSERT INTO my_delta_table VALUES (1, 'John Doe'), (2,
'Jane Doe');

Reading from a Delta table


#python
delta_df = spark.read.format("delta").load("/mnt/delta/my_delta_table")
delta_df.show()


#sql
-- Query Delta table
SELECT * FROM my_delta_table;

-- directly query delta table from adls.
-- use  ` back single quotation mark
SELECT * 
FROM 
delta.`abfss://adlsContainer@adlsAccount.dfs.windows.net/Path_and_TableName`
VERSION AS OF 4;

Managing Delta Tables

Optimizing Delta Tables

To improve performance, you can run an optimize operation to compact small files into larger ones.

# sql 
OPTIMIZE my_delta_table;

Z-order Clustering

Z-order clustering is used to improve query performance by colocating related data in the same set of files. it is a technique used in Delta Lake (and other databases) to optimize data layout for faster query performance.

# sql
OPTIMIZE my_delta_table ZORDER BY (date);

Upserts (Merge)

Delta Lake makes it easy to perform Upserts (MERGE operation), which allows you to insert or update data in your tables based on certain conditions.

using SQL scripts is the same as TSQL merge statement

% sql
MERGE INTO my_delta_table t
USING new_data n
ON t.id = n.id
WHEN MATCHED THEN UPDATE SET t.value = n.value
WHEN NOT MATCHED THEN INSERT (id, value) VALUES (n.id, n.value); 

In PySpark with Delta Lake:

The target table must be a Delta table and the source data is typically in a DataFrame.

Example Scenario
  • Target Table: target_table; Contains existing records.
  • Source DataFrame: source_df; Contains new or updated records.
  • Goal: Update existing rows if a match is found or insert new rows if no match exists.
from delta.tables import DeltaTable
from pyspark.sql.functions import current_date, lit

# Define paths
target_table_path = "dbfs:/mnt/delta/target_table"

# Load the Delta table as a DeltaTable object
target_table = DeltaTable.forPath(spark, target_table_path)

# Source DataFrame (new data to upsert)
source_data = [
    (1, "Alice", "2023-01-01"),
    (2, "Bob", "2023-01-02"),
    (4, "Eve", "2023-01-04")  # New record
]
columns = ["id", "name", "date"]
source_df = spark.createDataFrame(source_data, columns)

# Perform the merge operation
target_table.alias("t").merge(
    source_df.alias("s"),
    "t.id = s.id"  # Join condition: match rows based on `id`
).whenMatchedUpdate(
    set={
        "name": "s.name",  # Update `name` column
        "date": "s.date"   # Update `date` column
    }
).whenNotMatchedInsert(
    values={
        "id": "s.id",      # Insert `id`
        "name": "s.name",  # Insert `name`
        "date": "s.date"   # Insert `date`
    }
).execute()

# Verify the result
result_df = spark.read.format("delta").load(target_table_path)
result_df.show()
Explanation of the Code
  1. Target Table (target_table):
    • The Delta table is loaded using DeltaTable.forPath.
    • This table contains existing data where updates or inserts will be applied.
  2. Source DataFrame (source_df):
    • This DataFrame contains new or updated records.
  3. Join Condition ("t.id = s.id"):
    • Rows in the target table (t) are matched with rows in the source DataFrame (s) based on id.
  4. whenMatchedUpdate:
    • If a matching row is found, update the name and date columns in the target table.
  5. whenNotMatchedInsert:
    • If no matching row is found, insert the new record from the source DataFrame into the target table.
  6. execute():
    • Executes the merge operation, applying updates and inserts.
  7. Result Verification:
    • After the merge, the updated Delta table is read and displayed.

Conclusion

Delta Lake is a powerful solution for building reliable, high-performance data pipelines on top of data lakes. It enables advanced data management and analytics capabilities with features like ACID transactions, time travel, and schema enforcement, making it an ideal choice for large-scale, data-driven applications.

Delta tables are essential for maintaining high-quality, reliable, and performant data processing pipelines. They provide a way to bring transactional integrity and powerful performance optimizations to large-scale data lakes, enabling unified data processing for both batch and streaming use cases.

Please do not hesitate to contact me if you have any questions at William . chen @ mainri.ca

(remove all space from the email account 😊)

Partition in databricks

In Databricks, partitioning is a strategy used to organize and store large datasets into smaller, more manageable chunks based on specific column values. Partitioning can improve query performance and resource management when working with large datasets in Spark, especially in distributed environments like Databricks.

Key Concepts of Partitioning in Databricks

Partitioning in Tables:

When saving a DataFrame as a table or Parquet file in Databricks, you can specify partitioning columns to divide the data into separate directories. Each partition contains a subset of the data based on the values of the partitioning column(s).

Partitioning in DataFrames

Spark partitions data in-memory across nodes in the cluster to parallelize processing. Partitioning helps distribute the workload evenly across the cluster.

Types of Partitioning

Static Partitioning (Manual Partitioning)

When saving or writing data to a file or table, you can manually specify one or more columns to partition the data by. This helps when querying large tables, as Spark can scan only the relevant partitions instead of the entire dataset.

Dynamic Partitioning (Automatic Partitioning)

Spark automatically partitions a DataFrame based on the size of the data and available resources. The number of partitions is determined by Spark’s internal algorithm based on the data’s size and complexity.

Let’s say, there is dataframe

Partitioning in Databricks File System (DBFS)

When writing data to files in Databricks (e.g., Parquet, Delta), you can specify partitioning columns to optimize reads and queries. For example, when you partition by a column, Databricks will store the data in different folders based on that column’s values.


# Example of saving a DataFrame with partitioning
df.write.partitionBy("year", "month").parquet("/mnt/data/name_partitioned")

In this example, the data will be saved in a directory structure like:

/mnt/data/name_partitioned/gender=F
/mnt/data/name_partitioned/gender=M

Partitioning in Delta Tables

In Delta Lake (which is a storage layer on top of Databricks), partitioning is also a best practice to optimize data management and queries. When you define a Delta table, you can specify partitions to enable efficient query pruning, which results in faster reads and reduced I/O.


# Writing a Delta table with partitioning
df.write.format("delta").partitionBy("gender", "age").save("/mnt/delta/partitioned_data")

In this example, the data will be saved in a directory structure like:

/mnt/delta/partitioned_data/gender=F/age=34
/mnt/delta/partitioned_data/gender=F/age=45
/mnt/delta/partitioned_data/gender=M/age=23
/mnt/delta/partitioned_data/gender=M/age=26
/mnt/delta/partitioned_data/gender=M/age=32
/mnt/delta/partitioned_data/gender=M/age=43

Optimizing Spark DataFrame Partitioning

When working with in-memory Spark DataFrames in Databricks, you can manually control the number of partitions to optimize performance.

Repartition

This increases or decreases the number of partitions.
This operation reshuffles the data, redistributing it into a new number of partitions.


df = df.repartition(10)  # repartition into 10 partitions

Coalesce

This reduces the number of partitions without triggering a shuffle operation (which is often more efficient than repartition).
This is a more efficient way to reduce the number of partitions without triggering a shuffle.


df = df.coalesce(5) # reduce partitions to 5

When to Use Partitioning

  • Partitioning works best when you frequently query the data using the columns you’re partitioning by. For example, partitioning by date (e.g., year, month, day) is a common use case when working with time-series data.
  • Don’t over-partition: Too many partitions can lead to small file sizes, which increases the overhead of managing the partitions.

Key Notes

  • Partitioning Cannot Change: If partitioning changes are needed, you must recreate the table.

Summary

  • Partitioning divides data into smaller, more manageable chunks.
  • It improves query performance by allowing Spark to read only relevant data.
  • You can control partitioning when saving DataFrames or Delta tables to optimize storage and query performance.
  • Use repartition() or coalesce() to manage in-memory partitions for better parallelization.
  • Use coalesce() to reduce partitions without shuffling.
  • Use repartition() when you need to rebalance data.

Please do not hesitate to contact me if you have any questions at William . chen @ mainri.ca

(remove all space from the email account 😊)

Comparison between All-Purpose Cluster, Job Cluster, SQL Warehouse and Instance Pools

side-by-side comparison of “All-Purpose Cluster”, “Job Cluster”, “SQL Warehouse” and Instance Pools in Azure Databricks, covering their key features, use cases, and differences:

Key Differences

  • All-Purpose Cluster: Best for interactive workloads, collaborative notebooks, and exploration. It stays running until you manually stop it or it hits the idle timeout. Not as cost-effective for long-running or scheduled tasks.
  • Job Cluster: Best for scheduled and automated jobs. It starts automatically when the job begins and shuts down after the job finishes, which makes it cost-efficient and ideal for production ETL or data processing jobs.
  • SQL Warehouse: Best for SQL analytics and BI tool integration. It is specifically optimized for SQL queries, offering auto-scaling based on query load and cost-efficient SQL query execution on Delta Lake tables.
  • Instance Pools: Reducing startup times for frequently created clusters. Sharing resources among multiple teams or clusters.

Side by side comparison

All-Purpose ClusterJob ClusterSQL Warehouse (formerly SQL Endpoints)Instance Pools
PurposeGeneral-purpose compute environment for interactive workloads.Dedicated to run a specific job or task. Automatically terminates after the job.Optimized for running SQL queries, dashboards, and BI analytics on Delta Lake.resource management feature that pre-allocate virtual machines (VMs) to reduce cluster startup times and optimize costs.
UsageFor interactive development in notebooks, collaboration, and ad-hoc analysis.For scheduled or automated jobs (e.g., ETL tasks) that need to run Spark-based processing.For SQL-based workloads, querying data in Delta Lake, and BI tools (e.g., Power BI, Tableau).Supporting clusters
Primary WorkloadInteractive development (notebooks, data exploration, ad-hoc queries).Automated Spark jobs with dedicated, isolated clusters for each job.SQL analytics and dashboards, running SQL queries against Delta Lake tables.Resource optimization
Cluster LifecycleRemains active until manually terminated or idle timeout is reached.Created automatically when a job is triggered, and terminated when the job is done.SQL Warehouses scale up/down based on query demand; remain active based on usage settings.Pre-warmed VMs (idle terminate)
Resource AllocationConfigurable resources, manual start/stop, and autoscaling available.Dynamically allocated resources based on job requirements, with autoscaling.Autoscaling based on SQL query demand; optimized for SQL workloads.
CostAlways running unless manually stopped or auto-terminated, can be expensive if left running.More cost-efficient for scheduled jobs, as the cluster runs only during the job execution.Efficient for SQL queries with autoscaling; cost based on query execution.Optimizes cluster creation
PerformanceGood for interactive, collaborative workloads but may incur higher costs if not optimized.Highly performant for running isolated, parallel jobs without interference from other workloads.Optimized for low-latency SQL query performance and concurrent query execution.
ScalingCan scale automatically based on workload demand (within limits set by the user).Scales based on the job’s needs; new clusters can be created for each job.Scales automatically to accommodate concurrent SQL queries.
IsolationNot isolated — multiple users can share the cluster, which may impact performance.Fully isolated — each job runs on a separate cluster.Isolated SQL queries but shared resources for concurrent workloads.Shared resource pool
Ideal ForData exploration, notebook development, machine learning experiments, ad-hoc queries.Scheduled ETL/ELT jobs, production jobs, or one-time data processing tasks.SQL analytics, dashboards, and BI tool integration for querying Delta Lake.Supporting clusters
Supported LanguagesPython, Scala, R, SQL, and more via notebooks.Python, Scala, R, SQL (job-specific).SQL only.
ManagementRequires manual monitoring and termination.Automatic termination after job completion.Automatically managed scaling and uptime based on usage.Faster cluster launches
Example Use CaseRunning notebooks to explore and analyze data, performing machine learning experiments.Running a scheduled Spark job that processes data in a pipeline or transformation.Running SQL queries on Delta Lake, powering dashboards, or connecting to BI tools.
Restart BehaviorCan be manually stopped and restarted; the Cluster ID remains the same.Automatically created and terminated for each job run; new Cluster ID for each job.SQL Warehouse remains active based on usage, auto-scaling handles load; Warehouse ID remains the same.Faster cluster launches
Side by side clusters comparisons.

Summary:

  • All-Purpose Clusters are ideal for interactive data exploration and multi-user environments, but they can be costly if left running for too long.
  • Job Clusters are used for single, isolated tasks (like scheduled ETL jobs) and are cost-effective since they are automatically created and terminated.
  • SQL Warehouses are specialized for SQL queries and business intelligence reporting, offering cost efficiency through on-demand scaling for SQL analytics.

Please do not hesitate to contact me if you have any questions at William . chen @ mainri.ca

(remove all space from the email account 😊)