Building a Medallion Architecture with Delta Lake and Apache Spark

Building a Medallion Architecture with Delta Lake and Apache Spark

Why the Medallion Architecture?

As data teams scale from handling megabytes to terabytes of daily ingestion, the flat data lake approach quickly becomes unmanageable. Data arrives in inconsistent formats, quality degrades over time, and downstream consumers lose trust in the pipeline outputs. The Medallion Architecture, also known as the Bronze-Silver-Gold pattern, solves this by introducing explicit, progressive layers of data refinement.

Originally popularized by Databricks, this architecture has become the de facto standard for building lakehouse platforms. Each layer serves a distinct purpose:

  • Bronze Layer: Raw, immutable data as-is from the source system. This is your system of record.
  • Silver Layer: Cleansed, conformed, and deduplicated data with enforced schemas.
  • Gold Layer: Business-level aggregates optimized for analytics and reporting.

Setting Up Delta Lake with Spark

Delta Lake sits on top of your existing data lake storage (S3, ADLS, GCS) and adds ACID transactions, schema enforcement, and time travel on top of Parquet files. Here's how to initialize a Spark session with Delta Lake support:

from pyspark.sql import SparkSession

spark = (SparkSession.builder
    .appName("MedallionArchitecture")
    .config("spark.sql.extensions", "io.delta.sql.DeltaSparkSessionExtension")
    .config("spark.sql.catalog.spark_catalog", 
            "org.apache.spark.sql.delta.catalog.DeltaCatalog")
    .config("spark.databricks.delta.retentionDurationCheck.enabled", "false")
    .getOrCreate())

The Bronze Layer: Ingesting Raw Data

The Bronze layer is where all raw data lands. The key principle here is append-only, schema-on-read. You capture everything exactly as it arrives. No transformations, no filtering. This gives you a complete audit trail and the ability to reprocess from scratch if needed.

# Bronze layer ingestion. Raw JSON events
from pyspark.sql.functions import current_timestamp, input_file_name

raw_events = (spark.read
    .format("json")
    .option("multiLine", "true")
    .load("/mnt/sources/events/streaming/"))

bronze_df = (raw_events
    .withColumn("_ingested_at", current_timestamp())
    .withColumn("_source_file", input_file_name())
    .withColumn("_event_date", 
        F.to_date(F.col("timestamp"))))

(bronze_df.write
    .format("delta")
    .mode("append")
    .partitionBy("_event_date")
    .save("/mnt/lakehouse/bronze/events"))

Bronze Layer Best Practices

  • Always add metadata columns: _ingested_at, _source_file, _event_date
  • Partition by date for efficient data pruning and retention management
  • Use append-only mode. Never overwrite Bronze data
  • Enable Delta Lake change data feed (CDF) for downstream lineage tracking

The Silver Layer: Cleansing and Conforming

The Silver layer applies business rules to produce a clean, validated dataset. This is where you enforce schemas, remove duplicates, handle null values, and conform data from multiple sources into a unified model.

# Silver layer. Deduplicate and cleanse
from pyspark.sql.window import Window

# Read from Bronze
bronze_events = spark.read.format("delta").load("/mnt/lakehouse/bronze/events")

# Define window for deduplication
dedup_window = Window.partitionBy("event_id").orderBy(F.desc("_ingested_at"))

silver_events = (bronze_events
    .withColumn("_row_num", F.row_number().over(dedup_window))
    .filter(F.col("_row_num") == 1)
    .drop("_row_num")
    .filter(F.col("event_id").isNotNull())
    .filter(F.col("timestamp").isNotNull())
    .withColumn("event_type", F.upper(F.col("event_type")))
    .withColumn("processed_at", current_timestamp()))

# Write with merge for idempotent processing
from delta.tables import DeltaTable

delta_table = DeltaTable.forPath(spark, "/mnt/lakehouse/silver/events")

(delta_table.alias("target")
    .merge(silver_events.alias("source"),
           "target.event_id = source.event_id")
    .whenMatchedUpdateAll()
    .whenNotInsertAll()
    .execute())

The Gold Layer: Business Aggregates

The Gold layer contains business-ready aggregates that power dashboards, reports, and ML features. These tables are optimized for query performance with materialized aggregates, pre-computed joins, and appropriate partitioning strategies.

# Gold layer. Daily revenue aggregation
silver_orders = spark.read.format("delta").load("/mnt/lakehouse/silver/orders")
silver_products = spark.read.format("delta").load("/mnt/lakehouse/silver/products")

gold_daily_revenue = (silver_orders
    .join(silver_products, "product_id", "left")
    .groupBy(
        F.to_date("order_date").alias("date"),
        F.col("category"),
        F.col("region")
    )
    .agg(
        F.sum("amount").alias("total_revenue"),
        F.count("order_id").alias("order_count"),
        F.avg("amount").alias("avg_order_value"),
        F.countDistinct("customer_id").alias("unique_customers")
    ))

(gold_daily_revenue.write
    .format("delta")
    .mode("overwrite")
    .partitionBy("date")
    .save("/mnt/lakehouse/gold/daily_revenue"))

Advanced Patterns: Time Travel and Schema Evolution

One of Delta Lake's most powerful features is time travel. The ability to query any historical version of your data. Combined with schema evolution, this makes the Medallion architecture incredibly resilient:

# Query data as it was 3 days ago
historical_df = (spark.read
    .format("delta")
    .option("versionAsOf", "2026-06-05")
    .load("/mnt/lakehouse/silver/events"))

# Schema evolution. Add new columns safely
new_events = spark.read.json("/mnt/sources/new_events_v2/")
(new_events.write
    .format("delta")
    .mode("append")
    .option("mergeSchema", "true")
    .save("/mnt/lakehouse/bronze/events"))

Performance Optimization

To keep your lakehouse performant at scale, implement these optimization strategies:

  • Z-Ordering: Co-locate related data for faster point lookups. Apply Z-Order on columns commonly used in WHERE clauses.
  • VACUUM: Remove old file versions to reclaim storage. Set a retention period (e.g., 168 hours) and run VACUUM on a schedule.
  • Auto-Optimize: Enable automatic file compaction to maintain optimal file sizes (target: 128MB-1GB per file).
  • Liquid Clustering: The next evolution beyond partitioning. Automatically organizes data based on query patterns.

Conclusion

The Medallion Architecture provides a proven, scalable framework for building lakehouse platforms that teams can trust. By separating concerns into Bronze, Silver, and Gold layers, you create clear data contracts, enable parallel development across teams, and build a foundation that scales from gigabytes to petabytes. Combined with Delta Lake's ACID guarantees and time-travel capabilities, this pattern eliminates the "data swamp" problem and brings warehouse-level reliability to your data lake.

Share this article

Back to Blog See Projects