Introduction: The Monolith Migration Challenge
One of the most common system design questions in Senior Data Engineer interviews is: “Design a pipeline that continuously replicates data from a monolithic PostgreSQL database into a modern lakehouse.” This question tests your knowledge of Change Data Capture (CDC), stream processing, schema evolution, and data lake architecture.
In this post, we walk through a production-grade CDC pipeline design that handles 200+ PostgreSQL tables, delivers sub-5-minute end-to-end latency, supports schema evolution, and operates with zero downtime.
Problem Statement
You inherit a monolithic application backed by a single PostgreSQL 14 instance containing 200+ tables, roughly 8 TB of data, handling 15,000 transactions per second at peak. The business needs this data in a lakehouse for analytics, ML feature stores, and regulatory reporting.
- Latency: Changes must appear in the lakehouse within 5 minutes.
- Schema evolution: Teams add columns, rename fields, and drop tables — the pipeline must not break.
- Zero downtime: The source PostgreSQL must not experience performance degradation.
- Exactly-once semantics: No duplicates or missing records in the target.
- Cost efficiency: Operate within a reasonable cloud budget.
High-Level Architecture
The pipeline follows a proven pattern used at Netflix, Uber, and Airbnb:
+--------------+ +------------+ +----------+ +-----------------+ +---------------+
| PostgreSQL |--->| Debezium |--->| Kafka |--->| Spark Struct. |--->| Delta Lake |
| (Source) | | Connector | | Cluster | | Streaming | | (Lakehouse) |
+--------------+ +------------+ +----------+ +-----------------+ +---------------+
| | | | |
WAL logs CDC Events Schema Reg. MERGE INTO Bronze/Silver
(logical) (Avro/JSON) (Confluent) Delta tables /Gold layers
Initial Snapshot Strategy
Before streaming CDC events, you need a consistent baseline. Debezium supports two snapshot modes:
- Initial snapshot (default): Debezium reads the entire table using
SELECT * FROM tablewithin a repeatable-read transaction, then switches to WAL tailing. For 200 tables at 8 TB, this takes 12-24 hours. - Parallel snapshot: Run multiple Debezium tasks with
snapshot.max.threads=4to cut time to 4-6 hours.
Key design decision: Use snapshot.mode=initial for first deployment. For re-snapshots of individual tables, use snapshot.mode=when_needed with signaling tables.
{
"name": "pg-cdc-connector",
"config": {
"connector.class": "io.debezium.connector.postgresql.PostgresConnector",
"database.hostname": "pg-primary.internal",
"database.port": "5432",
"database.dbname": "monolith_db",
"plugin.name": "pgoutput",
"slot.name": "debezium_cdc_slot",
"snapshot.mode": "initial",
"snapshot.max.threads": 4,
"table.include.list": "public.*",
"heartbeat.interval.ms": 10000,
"tombstones.on.delete": true
}
}
Ongoing CDC: Debezium WAL Tailing
After the snapshot, Debezium switches to PostgreSQL logical replication using pgoutput:
- Logical Replication Slot: PostgreSQL retains WAL segments until Debezium acknowledges them.
- Publication:
CREATE PUBLICATION dbz_publication FOR ALL TABLESfilters participating tables. - Event Format: Each event contains
before/afterimages, operation type (c/u/d/r), source metadata (LSN, timestamp, table), and transaction ID.
{
"op": "u",
"ts_ms": 1695000000000,
"before": {"id": 42, "name": "Alice", "email": "old@test.com"},
"after": {"id": 42, "name": "Alice", "email": "new@test.com"},
"source": {
"connector": "postgresql",
"db": "monolith_db",
"schema": "public",
"table": "users",
"lsn": 234567890
}
}
Critical: Monitor replication slot lag. If Debezium falls behind, WAL segments accumulate and can fill the PostgreSQL volume. Alert when lag exceeds 1 GB.
Kafka Topic Design and Schema Registry
Topic naming: cdc.monolith.{schema}.{table} (e.g., cdc.monolith.public.users)
Partitioning:
- Primary key as message key for per-entity ordering.
- High-volume tables: 12-24 partitions; reference tables: 3-6.
- Enable log compaction for latest-state availability.
Schema Registry:
- Confluent Schema Registry with Avro. Debezium auto-registers schemas.
BACKWARDcompatibility handles column additions gracefully.- Schema IDs embedded in messages enable seamless deserialization.
Retention: 7 days (retention.ms=604800000), cleanup.policy=compact,delete. ~100 GB/day, ~700 GB total.
Stream Processing: Spark Structured Streaming MERGE
The consumer reads Kafka and applies changes to Delta Lake using MERGE:
from pyspark.sql import SparkSession
from pyspark.sql.functions import col, from_json
from delta.tables import DeltaTable
spark = SparkSession.builder .appName("CDC-Ingestion") .config("spark.sql.extensions",
"io.delta.sql.DeltaSparkSessionExtension") .getOrCreate()
cdc_stream = (spark.readStream
.format("kafka")
.option("kafka.bootstrap.servers", "kafka:9092")
.option("subscribe", "cdc.monolith.public.users")
.option("startingOffsets", "earliest")
.option("maxOffsetsPerTrigger", 100000)
.load())
parsed = (cdc_stream
.selectExpr("CAST(value AS STRING) as json_str")
.select(from_json(col("json_str"), cdc_schema).alias("data"))
.select(
col("data.after.*"),
col("data.op").alias("_op"),
col("data.ts_ms").alias("_cdc_timestamp")))
def upsert_to_delta(micro_batch_df, batch_id):
if micro_batch_df.isEmpty():
return
target = DeltaTable.forPath(spark, "s3://lakehouse/bronze/users")
(target.alias("t")
.merge(micro_batch_df.alias("s"), "t.id = s.id")
.whenMatchedDelete(condition="s._op = 'd'")
.whenMatchedUpdateAll(condition="s._op = 'u'")
.whenNotMatchedInsertAll(condition="s._op != 'd'")
.execute())
(parsed.writeStream
.foreachBatch(upsert_to_delta)
.option("checkpointLocation", "s3://lakehouse/checkpoints/users")
.trigger(processingTime="60 seconds")
.start()
.awaitTermination())
Why foreachBatch? Delta MERGE requires a batch DataFrame. The 60-second trigger balances latency against small-file overhead.
Medallion Architecture for CDC Data
Bronze Layer (Raw Ingestion)
- Store raw CDC events with the full Debezium envelope.
- Partitioned by
_ingestion_datefor time-travel and replay. - No transformations — audit trail and recovery point. Retain 90+ days.
Silver Layer (Cleaned, Conformed)
- Apply MERGE: upserts and deletes produce current-state tables.
- Cast to standard types (timestamps UTC, strings trimmed).
- PII tokenized via column-level encryption.
- Schema enforcement:
mergeSchema=truefor additive changes.
Gold Layer (Business Aggregates)
- Materialized views:
daily_order_summary,customer_lifetime_value. - Batch Spark jobs on 15-minute or hourly schedule.
- Z-ORDER on frequently filtered columns for query performance.
Handling Deletes and Schema Changes
Deletes:
- Bronze: store delete events as-is (
op=dwithbeforeimage). - Silver: soft delete (
_is_deleted=true) for audit domains, or hard delete via MERGEwhenMatchedDelete. - Enable tombstones for Kafka log compaction.
Schema evolution:
- Column additions: Debezium detects them, Schema Registry registers new version, Spark uses
mergeSchema=true. - Column renames: Break CDC — use ADD + DEPRECATE instead of RENAME.
- Column deletions: Existing columns get nulls going forward. No breakage.
- Table drops: Alert on zero-throughput topics (no events in 30 min).
Data Validation and Reconciliation
- Row count reconciliation: Every 6 hours, source vs target counts. 0.01% tolerance.
- Checksum validation: MD5 on random 10K-row samples daily for critical tables.
- Freshness monitoring:
MAX(_cdc_timestamp)per Silver table. Alert if > 5 min stale.
WITH source_counts AS (
SELECT table_name, row_count FROM pg_stat_user_tables
WHERE schemaname = 'public'
),
target_counts AS (
SELECT table_name, COUNT(*) as row_count
FROM delta_silver.all_tables
WHERE _is_deleted = false GROUP BY table_name
)
SELECT s.table_name, s.row_count AS src, t.row_count AS tgt,
ABS(s.row_count - t.row_count) AS diff
FROM source_counts s JOIN target_counts t ON s.table_name = t.table_name
WHERE ABS(s.row_count - t.row_count) > 0 ORDER BY diff DESC;
Monitoring and Alerting
| Metric | Source | Threshold |
|---|---|---|
| Replication slot lag | PostgreSQL | > 1 GB |
| Consumer group lag | Kafka/Burrow | > 100K msgs |
| Connector status | Kafka Connect | != RUNNING |
| Batch duration | Spark/Prometheus | > 55 sec |
| Table freshness | Custom query | > 5 min |
| Schema failures | Schema Registry | Any |
| Row count drift | Recon job | > 0.01% |
Stack: Prometheus + Grafana with dedicated CDC dashboard. PagerDuty for P1 (connector down, slot lag critical).
Trade-offs
| Decision | Alternative | Rationale |
|---|---|---|
| Debezium (log-based) | Query-based (Airbyte) | No DB impact, captures deletes |
| Kafka | Direct-to-S3 | Decoupling, replay, multi-consumer |
| Spark Streaming | Flink | Unified batch+stream, Delta MERGE |
| Delta Lake | Iceberg | Databricks native, mature MERGE |
| foreachBatch MERGE | Append+compact | Simpler, immediate current state |
Interviewer Q&A
Q1: Why not nightly batch ETL instead of CDC?
Batch ETL introduces 24-hour latency, violating sub-5-minute requirements. It requires full table scans causing lock contention. CDC via WAL tailing has near-zero source impact — it reads the replication stream, not tables. Batch also misses intermediate changes: 5 updates between extractions yield only the final state, losing audit trails for compliance.
Q2: How do you snapshot without overwhelming the source?
Three strategies: schedule during low-traffic windows; use parallel snapshot (
snapshot.max.threads=4) with limited connections; snapshot large tables from a read replica then switch to primary WAL for ongoing CDC. This requires LSN coordination but eliminates primary impact.
Q3: What if Debezium goes down for 2 hours?
No data loss — PostgreSQL retains WAL for the replication slot until acknowledged. Debezium resumes from the last committed LSN. Risk is WAL accumulation (20-50 GB at 15K TPS). Mitigate with slot lag alerts (1 GB, 5 GB),
max_slot_wal_keep_sizein PG 13+, and treating connector health as P1.
Q4: How to migrate from Delta Lake to Iceberg?
Architecture is modular — Kafka is format-agnostic. Replace
DeltaTable.merge()with Iceberg SQL MERGE INTO (since 0.14). Dual-write during migration. Key diffs: hidden partitioning, catalog-based references, different compaction (rewrite_data_files). Plan 4-6 weeks parallel with reconciliation.
Q5: How to ensure exactly-once end-to-end?
Idempotent operations at each stage: Debezium uses KIP-618 transactional producers; Spark checkpointing records offsets atomically with output; MERGE is inherently idempotent since the same event produces identical results. Combined offset tracking + checkpointing + idempotent MERGE delivers effectively exactly-once.
Conclusion
A well-designed CDC pipeline bridges operational databases and analytical platforms with minimal latency and zero source impact. In interviews, explain why each component exists, anticipate failure modes, and show how you would operate in production. This architecture — PostgreSQL WAL, Debezium, Kafka with Schema Registry, Spark Structured Streaming, and Delta Lake medallion layers — is battle-tested at scale across the industry.