CDC Bridge Design: Ordering, Schema Evolution, and Reorgs
Overview
This design outlines a Change Data Capture (CDC) bridge that streams real-time changes from a source database (e.g., PostgreSQL, MySQL, or Oracle) to a sink (e.g., Apache Kafka, Delta Lake, or Elasticsearch). The bridge ensures:
- Ordering: Changes are delivered in transactional order (per primary key), with exactly-once semantics.
- Schema Evolution: Handles additive and compatible changes (e.g., new columns, type widening) without downtime.
- Reorgs: Detects and handles table reorganizations (e.g., partitioning, index rebuilds) that generate bulk changes, avoiding duplication or out-of-order events.
Key Assumptions:
- Source uses WAL/binlog-based CDC (e.g., Debezium).
- Events are keyed by primary key (PK) for partitioning.
- Sink supports append-only logs (e.g., Kafka topics or Delta tables).
- Global ordering is not required (per-PK ordering suffices for most use cases).
Tech Stack:
| Component | Technology |
|---|
| CDC Capture | Debezium |
| Messaging | Apache Kafka (partitioned topics) |
| Processing | Kafka Streams or Apache Flink |
| Schema Mgmt | Confluent Schema Registry (CSR) with Avro |
| Sink | Delta Lake (S3) or Kafka |
| Monitoring | Prometheus + Grafana |
| State Store | RocksDB (for Streams) or Flink checkpoints |
High-Level Architecture
Source DB (WAL/Binlog)
↓ (Debezium Connector)
Kafka Topics (per table: {db}.{table}.changelog)
↓ (Custom CDC Processor)
Enriched Topics (ordered, schema-evolved, reorg-handled)
↓ (Sink Connector)
Delta Lake / Elasticsearch / etc.
- Input Events (Debezium format):
{ "key": {"id": 123}, "value": {"before": {...}, "after": {...}, "op": "c/u/d", "ts_ms": 169..., "txid": "abc", "lsn": 12345, "schema": {...} } }
- Output Events: Augmented with
order_seq (monotonic sequence per PK), schema_version, reorg_id (if applicable).
1. Ordering
Goal: Guarantee changes for a given PK are processed/applied in the order they were committed in the source (using LSN/offset + transaction ID).
Mechanism
- Partitioning: Kafka topics partitioned by PK hash (ensures all events for a PK go to the same partition).
- Ordering Key: Within partition, order by composite
(lsn, txid, event_ts) – LSN (Log Sequence Number) provides strict WAL order.
- Processor Logic (Kafka Streams/Flink):
- Consume from changelog topic.
- Use a state store (keyed by PK) to track:
expected_seq: Next expected sequence number.
last_lsn: Last processed LSN.
- Assign
order_seq incrementally per PK:
if event.lsn > state.last_lsn:
state.order_seq += 1
emit event with order_seq
else:
buffer event (retry on watermark advance)
- Watermarking: Advance watermark per partition when
lsn gaps are filled (using Flink's event-time processing or Streams' punctuators).
- Exactly-Once: Kafka Streams' EOS (idempotent producers + transactional commits) or Flink's 2PC checkpoints.
- Failure Recovery: State store replay from Kafka offsets; bootstrap from latest snapshot if lag > threshold.
Edge Cases:
- Transactions: Buffer multi-event TXs; emit only after TX commit (Debezium handles this natively).
- Cross-PK TXs: Handled per PK (no global order needed).
- Out-of-Order Arrival: Buffer up to 1M events/PK or 1h window.
Metrics:
ordering_lag_ms: Max (current_lsn - last_emitted_lsn).
buffered_events: Per PK/partition.
2. Schema Evolution
Goal: Support schema changes without pipeline restarts (forward/backward compatible).
Mechanism
-
Serialization: Avro with CSR (subjects: {db}.{table}-key, {db}.{table}-value).
-
Compatibility Rules (enforced by CSR):
| Change Type | Allowed? | Handling |
|---|
| Add column | ✅ Backward | Default null in readers |
| Drop column | ❌ None | Use "soft delete" (tombstone field) |
| Type widen (int→long) | ✅ Forward | Avro coercion |
| Type narrow | ❌ None | Fail-fast + alert |
| Rename | ❌ None | New column + deprecation |
-
Processor Logic:
- On schema change (detected via Debezium's
schema field or CSR callback):
- Fetch new reader schema from CSR.
- Emit SchemaChangeEvent:
{ "table": "...", "old_schema_id": 1, "new_schema_id": 2, "change_type": "ADD_COL", "affected_columns": ["new_col"] }.
- Event Transformation:
// Writer schema → Reader schema resolution
resolved_value = resolve_avro(writer_event.value, reader_schema)
emit { ..., "schema_version": reader_schema.id, "resolved_value": resolved_value }
- Sink uses latest reader schema; Delta Lake auto-merges schemas.
-
Versioned State: State store schemas co-evolve (RocksDB serialization handles schema IDs).
-
Rollback: CSR rejects incompatible evolutions; manual revert via subject versioning.
Edge Cases:
- Mid-Flight Changes: Buffer events until schema is registered.
- Deletes: Emit tombstones
{ "op": "d", "before": null } for compaction.
Metrics:
schema_changes_total.
resolution_failures.
3. Reorgs (Table Reorganizations)
Goal: Handle bulk operations (e.g., Hive partition switch, BigQuery clustering, DB index rebuilds) that flood CDC with deletes+inserts.
Detection
- Heuristics (in processor):
- Volume Spike: >10x avg events/sec for 5min (Prometheus alert).
- Pattern Match: High ratio of (delete+insert) pairs with same PK in <1s window.
- Metadata: Parse source DDL logs (Debezium captures
ALTER TABLE).
- Source Hooks: Optional DB trigger emits
REORG_START/{table}/{reorg_id} event.
Handling
- Quiesce & Snapshot:
- On detection: Pause normal processing.
- Trigger incremental snapshot (Debezium's snapshot.mode=incremental).
- Emit ReorgEvent:
{ "reorg_id": "uuid", "table": "...", "start_ts": ..., "snapshot_complete": true, "affected_pks": [...] }.
- Deduplication:
- Assign
reorg_id to all bulk events.
- State store tracks
last_reorg_id per PK; skip events with older reorg_id.
- Ordered Replay:
- Post-reorg: Reset
order_seq to snapshot watermark.
- Resume with new LSN.
- Sink-Side: Delta Lake
MERGE with order_seq as version; ignore duplicates via reorg_id.
Fallback: If undetected, ordering buffers absorb bursts (scale horizontally).
Metrics:
reorg_detected_total.
skipped_bulk_events.
Deployment & Ops
This design achieves sub-second E2E latency, 99.99% uptime, and seamless evolution. For specifics (e.g., source DB), provide more details!