Medallion Architecture with DLT
Earn 25 points (50 with Pro) in two steps
- ① Read through the lesson — each section gets a ✓ as you scroll through it.
- ② When every section has a ✓, tap Complete lesson.
0 of 11 read · keep scrolling
✦ See fewer ads and earn double points — 50 a lesson instead of 25 — with Pro
Medallion Architecture with Delta Live Tables (DLT)
Introduction: The Evolution of Data Pipeline Engineering
In the modern data landscape, the primary challenge is no longer just storing massive amounts of information; it is maintaining the quality, reliability, and accessibility of that information as it flows through an organization. When we talk about data pipelines, we are essentially talking about the plumbing of a business. If the plumbing is clogged, leaky, or poorly organized, the data consumers—data scientists, business analysts, and decision-makers—cannot do their jobs effectively. This is where the Medallion Architecture, implemented through Delta Live Tables (DLT), becomes a transformative approach for data engineers.
The Medallion Architecture is a data design pattern used to logically organize data in a Lakehouse. It is structured in three distinct layers: Bronze, Silver, and Gold. Each layer represents an increase in data quality, refinement, and business readiness. By using Delta Live Tables, we move away from the traditional, brittle method of writing manual scripts to handle dependencies and retries. Instead, DLT allows us to define the desired state of our data, and the system automatically handles the orchestration, infrastructure management, and state tracking.
Understanding this architecture is critical because it forces a discipline of incremental refinement. Instead of dumping raw data into a dashboard, we treat data like a product that goes through a manufacturing process. By the time it reaches the Gold layer, it is clean, aggregated, and ready for consumption. This lesson will guide you through the theory, implementation, and best practices of building this architecture using DLT, ensuring your pipelines are not just functional, but maintainable and scalable.
Not read yet
The Core Concept: Understanding the Three Layers
To build effective pipelines, you must first understand the purpose of each layer in the Medallion architecture. Each layer serves a specific stakeholder and addresses a specific set of data quality problems.
1. The Bronze Layer: The Raw Landing Zone
The Bronze layer is where data first lands in your lakehouse. It is a direct copy of the source systems, whether those systems are relational databases, IoT sensors, or external APIs. The goal here is to keep the data as close to the original format as possible. We do not apply heavy business logic here because we want to maintain an audit trail and the ability to reprocess data if requirements change later.
2. The Silver Layer: The Refined Foundation
The Silver layer is where the heavy lifting happens. Here, we perform data cleansing, schema enforcement, and deduplication. We join disparate data sources to create a unified view. This is the "single source of truth" for the organization. Data at this stage should be ready for exploration and ad-hoc analysis, but it may not yet be aggregated into the specific metrics needed for executive reporting.
3. The Gold Layer: The Business Logic Layer
The Gold layer is the final destination. This data is highly refined, aggregated, and organized into star schemas or other structures optimized for business intelligence tools. Gold tables are often specific to departments or use cases, such as "Monthly Sales Forecasts" or "Customer Churn Metrics." By the time data hits this layer, it has passed all quality checks and is ready for production consumption.
Callout: Why DLT Changes the Game Traditional ETL pipelines often suffer from "dependency hell," where a failure in one script breaks everything downstream. Delta Live Tables removes this burden by automatically building a dependency graph. When you define a table in DLT, the system knows exactly what data it needs and in what order it must be processed. It manages the underlying infrastructure, allowing you to focus on the business logic rather than the plumbing of cluster management and checkpointing.
Not read yet
Setting Up Delta Live Tables
Delta Live Tables is a declarative framework. You don't tell the system how to move data; you tell it what the data should look like. To get started, you will typically use SQL or Python. While both are powerful, Python is often preferred for complex transformations because it allows for better code reuse and modularity.
Step-by-Step: Initializing a DLT Pipeline
- Define the Pipeline: In your data platform, create a new DLT pipeline. You will need to specify the storage location for the data (the "storage root") and the target database (the "schema").
- Choose the Mode: You can choose between "Triggered" (batch) or "Continuous" (streaming) mode. For most Medallion setups, triggered mode is sufficient unless you have strict sub-second latency requirements.
- Write the Code: Create a notebook or a file that defines your tables. Each table is defined using the
@tabledecorator in Python or theCREATE LIVE TABLEstatement in SQL.
Example: A Bronze-to-Silver Transformation
In the following example, we take raw JSON data from a source, clean it, and save it into a Silver table.
import dlt
from pyspark.sql.functions import col, current_timestamp
# Define the Bronze table
@dlt.table(
comment="Raw landing zone for customer data"
)
def raw_customers():
return spark.readStream.format("cloudFiles") \
.option("cloudFiles.format", "json") \
.load("/databricks-datasets/retail-org/customers/")
# Define the Silver table with quality checks
@dlt.table(
comment="Cleaned customer data with quality constraints"
)
@dlt.expect_or_drop("valid_email", "email IS NOT NULL")
def silver_customers():
return dlt.read("raw_customers") \
.select(
col("customer_id"),
col("name"),
col("email"),
current_timestamp().alias("processed_at")
)
In this code, notice the @dlt.expect_or_drop decorator. This is one of the most powerful features of DLT. Instead of writing complex if-else blocks to handle bad data, you define a quality constraint. If a row fails this constraint, the system automatically drops it and logs the violation, keeping your pipeline running smoothly.
Not read yet
Advanced Data Quality Management
One of the biggest pitfalls in data engineering is "silent failures," where bad data enters the system and corrupts downstream reports. DLT provides a built-in mechanism to prevent this through expectations.
Managing Expectations
Expectations allow you to define data quality rules that the system enforces during the pipeline execution. You have three primary choices for how to handle violations:
expect: Records the violation in the metrics but allows the row to pass through. This is useful for monitoring data quality trends without stopping the pipeline.expect_or_drop: Automatically discards rows that violate the rule. This is ideal for cleaning up obvious errors like null primary keys or invalid timestamps.expect_or_fail: Stops the entire pipeline if a violation occurs. Use this for critical business rules where data integrity is non-negotiable.
Warning: The Cost of "Fail" Be very careful with
expect_or_fail. While it ensures 100% data integrity, it can lead to pipeline downtime if a single malformed record appears. Always prioritizeexpect_or_dropfor standard data cleaning and reserveexpect_or_failfor catastrophic data issues that require manual intervention.
Monitoring Quality
DLT automatically tracks the metrics for every expectation you define. You can query the system.event_log to create a dashboard that shows your data quality over time. This provides visibility into how much data is being dropped and why, allowing you to go back to the source systems and fix the root cause of the bad data.
Not read yet
Orchestrating the Medallion Flow
To build a robust Medallion pipeline, you must ensure that your tables are linked correctly. DLT uses the dlt.read() function to create an implicit dependency. When you call dlt.read("raw_customers") inside the silver_customers function, DLT automatically understands that silver_customers depends on raw_customers.
Building the Gold Layer
Once you have your Silver layer cleaned and joined, you move to the Gold layer. The Gold layer is where you generate the final business metrics. This is often where you perform aggregations or apply complex business logic that spans multiple domains.
@dlt.table(
comment="Aggregated sales metrics for the executive dashboard"
)
def gold_sales_summary():
return dlt.read("silver_sales") \
.groupBy("region", "product_category") \
.agg(
sum("amount").alias("total_revenue"),
count("transaction_id").alias("transaction_count")
)
By keeping the Gold layer separate from the Silver layer, you gain two major advantages:
- Flexibility: You can recreate your Gold tables without re-processing the entire Bronze layer, which saves significant time and compute costs.
- Performance: Gold tables are smaller and more structured, making them extremely fast for BI tools like Tableau or PowerBI to query.
Not read yet
Comparison: DLT vs. Traditional ETL
It is helpful to compare the DLT approach to the traditional manual ETL approach to understand why the industry is shifting toward this pattern.
| Feature | Traditional Manual ETL | Delta Live Tables |
|---|---|---|
| Orchestration | Manual (Airflow, Cron) | Automatic (DAG built from code) |
| Data Quality | Manual checks/scripts | Declarative Expectations |
| Infrastructure | Manual cluster tuning | Auto-scaling/Auto-tuning |
| Dependency Management | Error-prone/Fragile | Implicit/Automated |
| Versioning | Hard to track | Built-in versioning (Delta Lake) |
The transition from manual ETL to DLT is essentially moving from "imperative" programming (telling the computer every step to take) to "declarative" programming (defining the desired end state). This shift reduces the "cognitive load" on data engineers, allowing them to focus on the logic of the data transformations rather than the mechanics of the execution.
Not read yet
Best Practices for Production Pipelines
Even with a powerful tool like DLT, you can still build a poor pipeline if you don't follow established patterns. Here are some industry-standard recommendations for managing production-grade Medallion pipelines.
1. Modularize Your Code
Don't put your entire pipeline in a single massive file. Break your code into separate notebooks or files based on the layer or the subject area. For example, have a bronze_ingestion.py, silver_transformations.py, and gold_metrics.py. This makes the code easier to test, version control, and maintain.
2. Use Schema Evolution
Data sources change over time. If a new column is added to your source database, your pipeline should ideally handle it automatically. DLT supports schema evolution, which allows the target table to adapt to changes in the source without needing a full rebuild. Ensure this is enabled in your production settings.
3. Implement Proper Monitoring
Do not wait for a user to report that a dashboard is empty. Set up alerts on your DLT pipelines. Most platforms allow you to send notifications to Slack, Email, or PagerDuty if a pipeline fails or if a quality expectation threshold is exceeded.
4. Optimize for Compute Costs
DLT can be expensive if you run large clusters 24/7. Use the "Enhanced Autoscaling" feature to allow the system to shrink your cluster when it is idle. Additionally, consider the "Photon" engine if your transformations involve complex joins or heavy aggregations, as it can significantly reduce execution time.
5. Keep the Bronze Layer Immutable
Never modify data in the Bronze layer. If you discover a bug in your Silver or Gold transformation, you want to be able to re-process the raw data from scratch. If you have modified the raw data, you lose the ability to perform a reliable "re-run."
Not read yet
Common Pitfalls and How to Avoid Them
Even experienced data engineers fall into common traps. Let's look at a few of the most frequent ones and how to navigate them.
Pitfall 1: Over-Engineering the Bronze Layer
Some engineers try to clean the data before it gets to the Bronze layer. This is a mistake. The Bronze layer should be your "system of record." If you apply transformations early, you lose the raw context. If you find out later that the transformation was incorrect, you cannot go back to the source, and you are forced to re-ingest all your historical data.
- The Fix: Keep Bronze raw. Apply all logic in Silver.
Pitfall 2: Ignoring State Management
In streaming pipelines, state management (knowing which records have already been processed) is crucial. If you don't use the built-in streaming features of DLT correctly, you might end up processing the same records twice, leading to inflated metrics.
- The Fix: Always use
spark.readStreamandcloudFiles(Auto Loader) to ensure that the system tracks which files have been processed.
Pitfall 3: Failing to Clean Up
Over time, your storage can become cluttered with temp files and old versions of tables. While Delta Lake handles vacuuming, you should ensure that your DLT pipeline has the appropriate retention policies configured.
- The Fix: Regularly review your storage root and ensure that you are not keeping unnecessary intermediate tables or temporary data.
Pitfall 4: Mixing Logic Types
Some developers try to cram complex machine learning models directly into a DLT pipeline. While you can do this, it often makes the pipeline brittle and hard to debug.
- The Fix: Use DLT for data movement and cleaning. If you have complex ML model inference, perform that in a separate service or a separate, dedicated DLT stage, and keep the data pipeline clean.
Not read yet
Advanced Feature: Handling Slowly Changing Dimensions (SCD)
One common requirement in the Medallion architecture is handling "Slowly Changing Dimensions" (SCD). For example, if a customer changes their address, you might want to keep the history of the old address while updating the current one. DLT simplifies this through the apply_changes function.
# Example of using apply_changes to handle SCD Type 1 or 2
dlt.apply_changes(
target="silver_customers",
source="raw_customers",
keys=["customer_id"],
sequence_by="updated_at",
stored_as_scd_type=1
)
This function automatically handles the deduplication and the logic of whether to update an existing record or insert a new one. This is a massive time-saver compared to writing the SQL logic for SCD manually.
Quick Reference: DLT Key Concepts
| Term | Definition |
|---|---|
| Pipeline | The container for your data processing logic. |
| Expectation | A constraint defining the quality of your data. |
dlt.read() |
A function to reference another DLT table, creating a dependency. |
| Storage Root | The location where DLT stores metadata and checkpoint information. |
| Auto Loader | A tool to incrementally ingest files from cloud storage. |
| SCD | Slowly Changing Dimension; tracking changes in data over time. |
Not read yet
Frequently Asked Questions (FAQ)
Q: Can I use DLT with non-Delta formats? A: DLT is designed specifically for the Delta Lake format. It leverages the ACID properties of Delta to ensure consistency. You should convert your raw data to Delta as part of the Bronze ingestion process.
Q: How do I handle secrets like API keys in my DLT code?
A: Never hardcode secrets. Use the built-in secret management tools of your cloud provider or data platform (like Databricks Secrets) and reference them using dbutils.secrets.get().
Q: Is DLT only for streaming? A: No, DLT supports both batch and streaming. Even if you use batch, DLT provides the same benefits of dependency tracking and infrastructure management.
Q: Can I share tables between different DLT pipelines? A: Yes, you can reference tables created in one DLT pipeline from another, provided they share the same metastore. This allows for modular, multi-team development.
Not read yet
Key Takeaways
- The Medallion Approach is Foundational: By separating data into Bronze (raw), Silver (cleaned), and Gold (aggregated), you create a clear path for data refinement that supports both technical reliability and business reporting.
- Declarative Over Imperative: DLT allows you to define what your data should look like, leaving the complex orchestration to the system. This reduces the surface area for bugs and maintenance overhead.
- Data Quality is a First-Class Citizen: Using
expectationsis not optional. It is the best way to ensure that bad data does not permeate your entire organization. Useexpect_or_dropliberally to keep your Silver and Gold layers clean. - Automation is the Goal: Use features like Auto Loader and
apply_changesto automate the most repetitive parts of data engineering, such as file ingestion and SCD management. - Modularization Matters: Even in a declarative framework, organization is key. Keep your pipelines modular, separate logic by layer, and use source control to manage your pipeline code.
- Monitoring is Essential: Use the event log to track data quality trends and pipeline health. Proactive monitoring prevents the "silent failure" of data products.
- Infrastructure Efficiency: Leverage auto-scaling and intelligent compute engines (like Photon) to ensure your pipelines are cost-effective as they grow in volume.
By mastering the Medallion Architecture with Delta Live Tables, you are not just writing code; you are building a reliable data product. This architecture is designed to grow with your business, providing the agility to handle new data sources while maintaining the rigor required for high-stakes decision-making. As you continue your journey, focus on the quality of the data flowing through the layers, and your users will thank you for the consistency and reliability of the insights you provide.
Not read yet
Each section gets a ✓ as you scroll through it. Tap the button to jump to the next one.
- VNet Injection and Private Link
- VNet Injection and Private Link Quiz5q
- Access Control and Authentication
- Access Control and Authentication Quiz5q
- Secret Management with Azure Key Vault
- Secret Management with Azure Key Vault Quiz5q
- Workspace Administration Best Practices
- Workspace Administration Best Practices Quiz5q
- Exam Domain Review
- Exam Domain Review Quiz5q
- Azure Databricks Best Practices
- Best Practices Quiz5q
- Troubleshooting Databricks Issues
- Troubleshooting Quiz5q
- Cost Optimization Strategies
- Cost Optimization Quiz5q
- DP-750 Practice Exam
- DP-750 Practice Exam Quiz5q
- Databricks SQL Warehouses
- SQL Warehouses Quiz5q
- Lakehouse Architecture Concepts
- Lakehouse Architecture Quiz5q
- Final Comprehensive Review
- Final Comprehensive Quiz5q
Spend your points to unlock exam-style practice questions
Spend points to unlock DP-750 exam-style practice questions.
Practice for DP-750