Skip to main content
← PROBLEMS / DATA-ENGINEERING
An end-to-end domain learning journey

Design a Real-Time Lakehouse
& Medallion Pipeline.

A real-time Medallion Lakehouse ingests 100k–300k Kafka events/sec into Bronze, deduplicates with bounded watermarks and Iceberg MERGE INTO for Silver (< 2 min freshness), and compacts small files asynchronously.
Start the journey5 stages
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

When a single bottleneck threatens end-to-end availability, use Spark Structured Streaming with bounded watermarks, checkpointed foreachBatch Iceberg MERGE INTO for exactly-once Silver upserts, and background bin-pack compaction to prevent small-file explosion.

TL;DR30-second simplified summary
▾

Core Mechanics: Modern BI dashboards and ML feature stores require fresh, deduplicated data (<= 2 min Bronze-to-Silver freshness) at 100,000 events/sec (bursting to 300,000 events/sec).

Visual & Structural Flow: Depicts Kafka -> Bronze (Append) -> Silver (Watermark + Iceberg MERGE) -> Gold (Kafka 300k/s -> Spark Streaming -> Iceberg Silver -> Compaction); 30s Micro-Batch Commit & Compaction Flow (Kafka -> Spark Driver -> Executors -> Iceberg Catalog).

Trade-Offs & Production: A naive pipeline runs df.writeStream.format('parquet').start('s3://silver/'): No Upserts or GDPR Deletes: Parquet files are immutable; CDC updates and row-level deletes require rewriting entire partitions manually. Enterprise Lakehouses pair Spark Structured Streaming with Apache Iceberg (or Delta Lake): Bronze: Append raw Kafka payloads with kafka_offset and ingest_ts every 30 s.

Failure Modes & Application: The Bronze/Silver/Gold Lakehouse pattern unifies streaming and batch analytics: ML Feature Stores: Serving < 2 min fresh user-session aggregates for real-time fraud and ranking models.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
Lakehouse Table Formats (Iceberg, Delta, Hudi)
Open table formats (Delta Lake, Apache Iceberg, Apache Hudi) add an ACID transaction log and metadata layer on top of cloud object storage (S3/GCS/ADLS) and Parquet files, enabling time travel, schema evolution, concurrent writes, and Medallion (Bronze/Silver/...
Spark Structured Streaming & Watermarking
Spark Structured Streaming models unbounded streams as continuously appended tables. Event-time watermarks bound how long in-memory or RocksDB state is retained for late-arriving records, enabling fault-tolerant stateful aggregations and Kafka-to-Lakehouse pip...
Batch & Streaming Architectures (Lambda vs. Kappa)
Modern data platforms balance freshness and correctness using Lambda (dual batch + speed layers), Kappa (single streaming log + replay), Change Data Capture (CDC), DAG orchestration with idempotent backfills, and SCD Type 2 dimensional modeling.
Apache Spark Data Engineering
Apache Spark processes petabyte-scale batch and streaming data across distributed clusters using lazy DAG execution, the Catalyst query optimizer, Tungsten off-heap memory, and Adaptive Query Execution (AQE) over columnar formats like Parquet, Delta Lake, and...
Full walkthrough · 5 stages
01
STAGE 01 · WHY IT MATTERSL4 · FUNDAMENTALS

Why a Real-Time Medallion Lakehouse matters at 100k+ events/sec.

Why this matters: The mechanism: understand how Why a Real-Time Medallion Lakehouse matters at 100k+ events/sec works from first principles.

Think of Why a Real-Time Medallion Lakehouse matters at 100k+ events/sec as the intuition layer for Design a Real-Time Lakehouse & Medallion Pipeline: The mechanism: understand how Why a Real-Time Medallion Lakehouse matters at 100k+ events/sec works from first principles.

Modern BI dashboards and ML feature stores require fresh, deduplicated data (<= 2 min Bronze-to-Silver freshness) at 100,000 events/sec (bursting to 300,000 events/sec). Traditional nightly batch ETL is hours too slow, while writing raw Kafka streams directly to object storage without table-format ACID transactions produces duplicates, broken schemas, and unqueryable small files.

02
STAGE 02 · IMPACTL5 · APPLIED DESIGN

What happens without watermarks, ACID upserts, and compaction.

Why this matters: The problem: see what breaks without What happens without watermarks, ACID upserts, and compaction under real concurrency or scale.

Streaming directly into raw Parquet on S3/GCS causes three cascading data failures:

  1. Duplicate Silver Rows: Micro-batch retries after an executor crash append duplicate records unless upserts are idempotent.
  2. Small-File Explosion: Writing 30-second micro-batches across 200 partitions creates ~17M tiny files/month, crushing S3 LIST and query planning.
  3. Unbounded State OOM: Deduplicating event_id without withWatermark() grows RocksDB/JVM state indefinitely until executors OOM.
Medallion ACID Streaming

Kafka -> Bronze (Append) -> Silver (Watermark + Iceberg MERGE) -> Gold

Kafka 300k/sClickstream + CDCSpark StreamingWatermark + CheckptIceberg SilverSnapshot MVCC MERGECompactionBin-pack 512MB files

1.Bronze Layer: Raw immutable append with Kafka offset metadata for replay.

2.Watermark Dedup: Bounds state store memory by dropping late keys past the 10-min window.

3.Iceberg MVCC: Atomic snapshot commits in foreachBatch guarantee exactly-once Silver.

4.Async Compaction: Rewrites small micro-batch files into 512 MB Parquet targets.

Iceberg MVCC snapshots + Spark checkpoints provide exactly-once upserts while async compaction keeps S3 read latency fast.

Engineering Decision Framework
Problem
How to implement Design a Real-Time Lakehouse & Medallion Pipeline without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
When a single bottleneck threatens end-to-end availability, use Spark Structured Streaming with bounded watermarks, checkpointed foreachBatch Iceberg MERGE INTO for exactly-once Silver upserts, and background bin-pack compaction to prevent small-file explosion.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Design a Real-Time Lakehouse & Medallion Pipeline experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
STAGE 03 · NAIVE SOLUTIONL5 · APPLIED DESIGN

Naive solution (and why raw Parquet append breaks).

Why this matters: The problem: see what breaks without Naive solution under real concurrency or scale.

A naive pipeline runs df.writeStream.format('parquet').start('s3://silver/'):

  • No Upserts or GDPR Deletes: Parquet files are immutable; CDC updates and row-level deletes require rewriting entire partitions manually.
  • At-Least-Once Duplicates: Task retries leave partial/duplicate files visible to readers.
  • Schema Breakage: Adding a new JSON field crashes downstream BI queries.
Design Trade-Off

Naive solution (and why raw Parquet append breaks)

Before · Unbounded Coupling
  • No backpressure on spikes
  • Implicit shared state
  • Cascading tail latency
After · Bounded & Observable
  • Explicit capacity budgets
  • Isolated failure domains
  • Predictable p99 latency
04
STAGE 04 · ENTERPRISE SOLUTIONL6 · SCALE & TRADE-OFFS

Enterprise solution: Spark Structured Streaming + Apache Iceberg + AQE.

Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.

Enterprise Lakehouses pair Spark Structured Streaming with Apache Iceberg (or Delta Lake):

  • Bronze: Append raw Kafka payloads with kafka_offset and ingest_ts every 30 s.
  • Silver: Apply withWatermark('event_ts', '10 minutes') + dropDuplicates(['event_id']), then execute MERGE INTO inside foreachBatch using checkpointLocation for exactly-once commits.
  • Maintenance & Governance: Run periodic rewrite_data_files (bin-pack to 512 MB), expire_snapshots, and Iceberg time-travel / GDPR row-level DELETE.
Exactly-Once Micro-Batch

30s Micro-Batch Commit & Compaction Flow

KafkaSpark DriverExecutorsIceberg Catalog1. Read offsets [N..M] + watermark2. Write new Parquet data files3. Atomic snapshot swap (MERGE)4. Commit Spark checkpoint offset5. Async bin-pack -> 512MB files

Readers see atomic Iceberg snapshots only after MERGE commits, preventing dirty reads or duplicate rows.

query = (silver_df.writeStream
    .foreachBatch(upsert_to_iceberg_silver)
    .option('checkpointLocation', 's3://checkpoints/silver_orders')
    .trigger(processingTime='30 seconds')
    .start())
StreamingQuery query = silverDf.writeStream()
    .foreachBatch((batchDf, batchId) -> upsertToIceberg(batchDf, batchId))
    .option("checkpointLocation", "s3://checkpoints/silver_orders")
    .trigger(Trigger.ProcessingTime("30 seconds"))
    .start();
05
STAGE 05 · SYSTEM DESIGN APPLICATIONSL7 · STAFF / PRINCIPAL

Where Real-Time Medallion Lakehouses are used.

Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

The Bronze/Silver/Gold Lakehouse pattern unifies streaming and batch analytics:

  • ML Feature Stores: Serving < 2 min fresh user-session aggregates for real-time fraud and ranking models.
  • E-Commerce Order & Inventory BI: Merging Debezium CDC streams into queryable Iceberg tables with time-travel audits.
  • GDPR / CCPA Compliance: Executing row-level deletes across petabyte object storage without full-table rewrites.
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why must a streaming Silver pipeline pair Iceberg MERGE INTO with a Spark watermark and background file compaction?

Recommended Learning Flow