Low-Latency Multi-Database Change Capture and Streaming Join Pipeline
Medium · System Design · Software Engineer · Onsite
Prompt
Architect a low-latency streaming data pipeline that captures ongoing row-level mutations from multiple independent operational databases, joins related entities across them, and serves a continuously refreshed, queryable derived table.
Keep the design vendor-neutral and parameterized:
- Capability contracts over brand names: Neither the upstream operational stores nor the downstream analytical/serving store are pre-selected. Spell out the exact log-capture, ordering, key, and write primitives your architecture requires from each tier.
- Parameterized sizing & SLAs: Volume, latency targets, retention horizons, source counts, and recovery objectives are intentionally left open. Frame them as clarifying questions and algebraic sizing formulas rather than assuming arbitrary fixed numbers.
- Concrete join scenario: To make mutation, deletion, and arrival-order mechanics concrete, walk through two independent upstream databases—one storing accounts keyed by account_id and another storing invoices keyed by invoice_id with an account_id foreign key—feeding a live inner-joined invoices_accounts dataset.
- Consistency model: State clearly whether readers observe eventual convergence across independent databases or cross-source point-in-time snapshots, and explain what stronger guarantees would demand.
Scope & Expectations
- Gap-free backfill & decoupled capture: Coordinate initial table snapshots with live transaction-log streams without dropping or reverting mutations, while isolating operational databases from downstream backpressure.
- Stateful multi-source join mechanics: Handle inserts, updates, parent/child deletes, foreign-key reassignments, and arbitrary cross-database arrival orders using appropriate local state and reverse lookups.
- Crash recovery & sink idempotency: Align source log positions, stateful checkpoints, and destination writes across crashes, lost network acknowledgments, duplicate replays, and poison events—and state the honest limits of "exactly once."
- Partitioned scale & correctness auditing: Address key co-location, resharding, hot-key fan-out skew, correctness-driven state retention, online query visibility, and how to distinguish low lag from true data accuracy.
Step-by-step walkthrough
Clarify requirements, capabilities, and consistency model
Because specific database engines, SLAs, and table volumes are intentionally unspecified, begin by turning open design dimensions into explicit capability contracts—framing numeric targets (throughput, latency, retention, recovery objectives) as sizing inputs to confirm with the interviewer rather than hardcoding arbitrary constraints.
Clarifying questions and capability contracts
- Combination semantics: Using the concrete scenario, we maintain a continuously refreshed inner join
invoices INNER JOIN accounts ON invoices.account_id = accounts.account_id, keyed in the destination byinvoice_id. We also handle mutable foreign keys (an existing invoice'saccount_idreassigned fromA1toA2), which is the subtlest correctness edge case; ifaccount_idis immutable, Stage 1 below becomes even simpler. - Source change-stream contract: Rather than polling
updated_attimestamps (which misses hard deletes and intermediate mutations), we require log-based CDC (Change Data Capture, streaming committed row changes directly from each database's write-ahead log, binlog, or redo log). Every change event must provide:- Primary key (
account_idorinvoice_id), operation (INSERT | UPDATE | DELETE), and post-change row values (after; onDELETE, only the primary key is assumed because many databases omit full pre-images by default). - A strictly monotonic source position (such as a PostgreSQL LSN or MySQL GTID + statement index) that orders commits within that single source, alongside a source
commit_tstimestamp (for lag monitoring) andschema_id.
- Primary key (
- Cross-source consistency: Because
accounts-dbandinvoices-dbcommit independently without a shared clock or distributed lock, the baseline guarantee is eventual convergence: if both sources pause at log offsetsP_acctandP_invand the pipeline drains, the destination table equals the exact inner joininvoices@P_inv JOIN accounts@P_acct. Stronger cross-database snapshot semantics are analyzed in Step 8. - Destination contract: The queryable serving store must support keyed conditional upserts—updating an
invoice_idrow only when the incoming version pair is strictly newer than the stored version pair—plus soft-delete tombstones (rows markedis_deleted = trueso replayed older updates cannot resurrect deleted records). Append-only analytical sinks are addressed in the follow-ups.
- Combination semantics: Using the concrete scenario, we maintain a continuously refreshed inner join
Sizing method: why join fan-out dominates sink capacity
Express capacity algebraically in terms of source cardinalities and mutation rates first, then plug in a clearly labeled illustrative worked example to expose where bottlenecks live.
Sizing Formulas CDC ingest bandwidth = (R_acct + R_inv) x avg_event_bytes Destination write rate = R_inv + (R_acct x avg_invoices_per_account) <-- 1-to-N join fan-out! Processor join state = (N_acct x acct_state_bytes) + (N_inv x (inv_state_bytes + owner_map_bytes)) Log storage = CDC_ingest_bandwidth x retention_seconds x replication_factor Illustrative Worked Example (to expose the dominant bottleneck, NOT a fixed SLA) Suppose N_acct = 10M rows (R_acct = 200 changes/s), N_inv = 500M rows (R_inv = 2,000 changes/s), average = 50 invoices/account, largest enterprise account = 1,000,000 invoices, 5x peak traffic: 1. CDC log ingest (200 + 2,000) x 1 KB = 2.2 MB/s avg (~11 MB/s peak) -> ~190 GB/day 7-day retention x 3 replicas = ~4 TB total disk (modest for Kafka) 2. Output write rate 2,000/s (from invoices) + 200/s x 50 (from accounts) = 12,000 writes/s avg (~60,000 writes/s peak; ONE update to the 1M-invoice account = 1M writes!) 3. Join state size 10M x 500 B (accounts) + 500M x 200 B (invoices) + 500M x 40 B (owner map) = 5 GB + 100 GB + 20 GB = ~125 GB total (~4 GB/task across 32 tasks on SSD) 4. Initial backfill 500M rows / 50,000 rows/s = 10,000 s (~2.8 hours while live edits continue)Three architectural takeaways from the math
- Join fan-out—not CDC ingestion—is the #1 bottleneck: Account updates multiply 50x into destination writes, and one mega-account profile edit triggers 1,000,000 sink writes.
- Join state (~125 GB) outgrows single-node RAM and belongs in a partitioned, embedded on-disk key-value store (such as RocksDB) backed by incremental checkpoints to object storage.
- Initial snapshots span hours, so backfilling cannot hold multi-hour locks or read transactions on production databases.
Data contracts: change events, version tuples, and tombstones
Every event emitted by a CDC capture worker carries a deterministic, comparable
versionderived exclusively from the source database's transaction log—never from processor wall-clock time:ChangeEvent { source_id: "invoices-db" | "accounts-db", source_epoch: 1, // incremented only if a source log resets / re-snapshots commit_pos: 9841204, // monotonic WAL / binlog offset tx_index: 2, // statement index inside the source transaction tx_id: 44109, commit_ts_ms: 1732950002123, // used for lag monitoring, NEVER for event ordering op: "INSERT" | "UPDATE" | "DELETE" | "SNAPSHOT", key: { invoice_id: 770 }, after: { invoice_id: 770, account_id: 42, amount_cents: 24000 } | null, schema_id: 12 // resolved via Schema Registry } // Deterministic per-source version tuple (compared lexicographically left-to-right): version = (source_epoch, commit_pos, tx_index)Queryable destination schema and idempotent conditional upsert
Table: invoices_accounts invoice_id BIGINT PRIMARY KEY, inv_ver BYTEA NOT NULL, -- big-endian encoded (epoch, commit_pos, tx_index) of invoice acct_ver BYTEA NOT NULL, -- big-endian encoded version of account (or MIN_VER on detach) is_deleted BOOLEAN NOT NULL, -- true = tombstone (hidden from queries, retained >= replay window) account_id BIGINT, company_name TEXT, plan_tier TEXT, amount_cents BIGINT, transform_ver INT NOT NULL -- tracks pipeline logic version during blue/green rebuilds Reader View: CREATE VIEW invoices_accounts_v AS SELECT invoice_id, account_id, company_name, plan_tier, amount_cents FROM invoices_accounts WHERE NOT is_deleted;Every sink write executes a conditional upsert that mutates a row only if
(incoming.inv_ver, incoming.acct_ver)is strictly greater than(stored.inv_ver, stored.acct_ver):INSERT INTO invoices_accounts AS t (invoice_id, inv_ver, acct_ver, is_deleted, account_id, company_name, plan_tier, amount_cents, transform_ver) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) ON CONFLICT (invoice_id) DO UPDATE SET inv_ver = EXCLUDED.inv_ver, acct_ver = EXCLUDED.acct_ver, is_deleted = EXCLUDED.is_deleted, account_id = EXCLUDED.account_id, company_name = EXCLUDED.company_name, plan_tier = EXCLUDED.plan_tier, amount_cents = EXCLUDED.amount_cents, transform_ver = EXCLUDED.transform_ver WHERE (t.inv_ver, t.acct_ver) < (EXCLUDED.inv_ver, EXCLUDED.acct_ver);High-level architecture and state layout
To shield operational databases from downstream stalls, a durable partitioned log (such as Apache Kafka) sits between lightweight CDC capture workers and the stateful stream processor.
+---------------+ WAL +---------------+ | accounts-db |------->| CDC Capture A |---+ | (+signal tbl) | +---------------+ | +------------------------------------+ +---------------+ +--->| Durable Partitioned Log | | | - accounts.cdc (key: account_id) | +---------------+ WAL +---------------+ | | - invoices.cdc (key: invoice_id) | | invoices-db |------->| CDC Capture B |---+ +-----------------+------------------+ | (+signal tbl) | +---------------+ | +---------------+ Schema Registry <--------------------------+ replayable boundary v +-------------------------------------------+ | Stateful Stream Processor (e.g., Flink) | | Stage 1 (partitioned by invoice_id): | | invoice_owner[inv_id] -> {ver, aid} | | | shuffle by account_id | | v | | Stage 2 (partitioned by account_id): | | accounts[aid] -> {ver, row | None} | | invoices_by_acct[aid][iid] -> {ver,..} | +---------------------+---------------------+ | batched + coalesced writes Checkpoints (offsets + RocksDB diffs) v -----------------> Object Storage +------------------------------------+ | Sink Writers (conditional upsert) | Continuous Bucket Reconciler +-----------------+------------------+ (verifies replicas vs destination) | -------------------------------------+ v +-------------------------------------+ | Destination Store: invoices_accounts| | Queries ---> invoices_accounts_v | +-------------------------------------+Why decoupling capture from processing is vital: Engines like PostgreSQL retain WAL segments in a replication slot until the CDC reader acknowledges them. If the join processor read directly from the operational database and paused during a destination outage, unpurged WAL files would exhaust the operational database's disk and take down production! Landing raw events in the durable log lets capture advance freely while downstream backpressure absorbs safely in cheap log storage.
Deep dive 1: watermark snapshots that meet the live log without gaps
When bootstrapping the pipeline, historical transactions have already aged out of the WAL, so we must merge an initial table scan into the live WAL stream without missing concurrent mutations or letting a stale snapshot read overwrite a newer live update.
Holding a single
REPEATABLE READtransaction for 2.8 hours blocks MVCC (Multi-Version Concurrency Control, where a long-open read snapshot prevents the database from reclaiming dead row versions) and restarts from zero on failure. Instead, we run an incremental watermark-based snapshot (the DBLog algorithm):Live WAL stream runs continuously while a chunk reader scans primary-key ranges [k_start, k_end): Source WAL timeline: ... --(e1: I5=$20)--> [pL: LOW_WATERMARK] --(e2: I7=$99)--> [pH: HIGH_WATERMARK] --> \ / Chunk SELECT (no lock): SELECT * FROM invoices WHERE invoice_id IN [1..1000) returns { I5=$20, I7=$50 (stale!), I8=$30 } Stream Merger rule between pL and pH: 1. Forward all live WAL events (like e2: I7=$99 at pos > pL) immediately. 2. Buffer the chunk SELECT rows in memory; evict any key from the buffer if that key appeared in the WAL between pL and pH (drops I7=$50 because e2 mutated I7!). 3. When pH arrives in the WAL, emit remaining buffered chunk rows (I5=$20, I8=$30) stamped with version = pH, checkpoint chunk progress, and advance to chunk [1000..2000).Why every key is exact:
- Unchanged during
[pL, pH](I8): Its state atpHequals whatSELECTobserved, so emitting it at versionpHis exact; any subsequent mutation carries position> pHand supersedes it cleanly. - Mutated during
[pL, pH](I7): EvictingI7from the chunk buffer prevents the stale$50snapshot row from overwriting live WAL evente2 ($99). - Crash-resumable & surgical: Checkpointing per 1,000-row chunk bounds crash rework to at most 1,000 rows, and the identical watermark mechanism can re-snapshot targeted key ranges later for automated drift repair.
- Connector offset commit & DDL: Capture workers advance their WAL offset only after the durable log acknowledges the batch (yielding harmless duplicates on crash, never missing changes). Every event carries
schema_idtracked from DDL statements in WAL order; additive columns pass seamlessly, whereas incompatible type or key changes halt that connector with an alert before corrupting downstream state.
- Unchanged during
Deep dive 2: two-stage stateful join, parent deletes, and reassignments
Because
accounts.cdcandinvoices.cdcoriginate from separate databases, events arrive in per-key commit order within one source, with no ordering guarantee across the two sources. Moreover,invoices.cdcis partitioned byinvoice_id(and aDELETErecord may carry onlyinvoice_id, omittingaccount_id!), whereas the join must co-locate records byaccount_id.A two-stage stateful processor handles both constraints cleanly:
- Stage 1 (partitioned by
invoice_id): Deduplicates invoice events byinv_verand tracksinvoice_owner[invoice_id] = {ver, account_id}so invoice deletes and foreign-key reassignments (A1 -> A2) know which account partition(s) to notify. - Stage 2 (partitioned by
account_id): Maintainsaccounts[aid]alongside a reverse indexinvoices_by_acct[aid][iid](stored as composite RocksDB key(aid, iid)so finding every invoice owned by a deleted or updated account is a fast local prefix scan).
MIN_VER = (0, 0, 0) # source_epoch starts at 1, so MIN_VER is strictly below all real versions # Stage 1 state (partitioned by invoice_id) invoice_owner = {} # invoice_id -> {"ver": tuple, "aid": int | None} def on_invoice_event(iid, inv_ver, row, send_to_stage2): """row is None on DELETE. Routes attach/detach commands to Stage 2 by account_id.""" prev = invoice_owner.get(iid) if prev is not None and inv_ver <= prev["ver"]: return # ignore duplicate or older replay from CDC connector old_aid = prev["aid"] if prev is not None else None new_aid = row["account_id"] if row is not None else None if old_aid is not None and old_aid != new_aid: # Invoice was deleted OR reassigned to another account -> retract from old_aid send_to_stage2(old_aid, ("DETACH", iid, inv_ver)) if new_aid is not None: send_to_stage2(new_aid, ("ATTACH", iid, inv_ver, row)) # Retain tombstone (aid=None) on delete so older replays are still rejected invoice_owner[iid] = {"ver": inv_ver, "aid": new_aid} # Stage 2 state (partitioned by account_id) accounts = {} # aid -> {"ver": tuple, "row": dict | None} invoices_by_acct = {} # aid -> {iid: {"ver": tuple, "row": dict | None}} (reverse index) def on_account_event(aid, acct_ver, acct_row, sink): """acct_row is None when an account is deleted.""" prev_acct = accounts.get(aid) if prev_acct is not None and acct_ver <= prev_acct["ver"]: return accounts[aid] = {"ver": acct_ver, "row": acct_row} # Scan reverse index: refresh or retract every active invoice belonging to aid for iid, inv_entry in invoices_by_acct.get(aid, {}).items(): if inv_entry["row"] is None: continue # already detached from this account if acct_row is None: # Account deleted while invoice still exists in source -> emit tombstone, # while keeping inv_entry in state so if the account is restored, it rejoins! sink.write_tombstone(iid, inv_ver=inv_entry["ver"], acct_ver=acct_ver) else: joined = { **inv_entry["row"], "company_name": acct_row["company_name"], "plan_tier": acct_row["plan_tier"], } sink.write_upsert(iid, inv_ver=inv_entry["ver"], acct_ver=acct_ver, row=joined) def on_stage2_message(aid, message, sink): kind = message[0] iid = message[1] inv_ver = message[2] bucket = invoices_by_acct.setdefault(aid, {}) prev_inv = bucket.get(iid) if prev_inv is not None and inv_ver <= prev_inv["ver"]: return # idempotent guard if Stage 1 -> Stage 2 replays across a shuffle topic if kind == "DETACH": bucket[iid] = {"ver": inv_ver, "row": None} # MIN_VER ensures that if iid reassigned A1 -> A2 at the same inv_ver, A2's upsert wins! sink.write_tombstone(iid, inv_ver=inv_ver, acct_ver=MIN_VER) elif kind == "ATTACH": inv_row = message[3] bucket[iid] = {"ver": inv_ver, "row": inv_row} acct = accounts.get(aid) if acct is not None and acct["row"] is not None: joined = { **inv_row, "company_name": acct["row"]["company_name"], "plan_tier": acct["row"]["plan_tier"], } sink.write_upsert(iid, inv_ver=inv_ver, acct_ver=acct["ver"], row=joined) elif acct is not None and acct["row"] is None: # Joined against a known deleted account -> ensure output is retracted sink.write_tombstone(iid, inv_ver=inv_ver, acct_ver=acct["ver"])Trace of tricky arrival and deletion races
1. Out-of-order insert: Invoice I10 (ver=1, aid=A1) arrives BEFORE Account A1. -> ATTACH saves I10 in invoices_by_acct[A1]; inner join emits nothing yet. -> Later, A1 ("Northwind", ver=5) arrives -> reverse-index scan emits Upsert(I10, ver=(1, 5), "Northwind"). 2. Account deletion while invoices remain: A1 is deleted at acct_ver=6. -> Reverse-index scan finds I10 and emits Tombstone(I10, ver=(1, 6), is_deleted=true). -> Destination updates because (1, 5) < (1, 6); I10 disappears from invoices_accounts_v! -> I10 stays in invoices_by_acct[A1] so if A1 is restored at acct_ver=7, I10 re-appears automatically. 3. Foreign-key reassignment race: I10 moves from A1 to live A2 (ver=9) at inv_ver=2. -> Task(A1) emits Tombstone(I10, ver=(2, MIN_VER)); Task(A2) emits Upsert(I10, ver=(2, 9)). -> Even when Task(A1) and Task(A2) write concurrently in arbitrary network order, (2, MIN_VER) < (2, 9), so the destination deterministically converges to A2's joined row!- Stage 1 (partitioned by
Deep dive 3: crash boundary, checkpoints, and "exactly once" limits
Four progress markers exist at runtime: source WAL offsets, Kafka consumer offsets, RocksDB join state, and destination rows. Our recovery invariant is:
Committed input offsets never advance ahead of durable state and durable destination writes.
We enforce this with checkpoint barriers (Chandy-Lamport markers injected periodically across all log partitions):
Checkpoint N lifecycle: 1. Barrier N flows through Stage 1 -> Stage 2; each task snapshots its RocksDB delta at Barrier N. 2. Sink writers flush all pending upserts/tombstones preceding Barrier N and await DB ACKs. 3. ONLY AFTER all state deltas upload and all sink writes ACK, the coordinator seals Checkpoint N (recording input Kafka offsets + state manifest in object storage).Crash trace: processor crashes after destination write succeeds, before Checkpoint N seals
Before crash: 1. Event (Invoice I10, inv_ver=2) joins A1 (acct_ver=5) -> Sink writes (I10, ver=(2, 5)) -> DB ACKs! 2. Processor pod crashes 10 ms BEFORE Checkpoint N commits. On recovery: 3. Processor restores Checkpoint N-1 (where I10 was still at inv_ver=1) and rewinds Kafka offsets. 4. Replay deterministically derives the EXACT same version tuple (2, 5) from source log offsets. 5. Sink re-sends conditional upsert for I10 with ver=(2, 5). 6. Destination evaluates WHERE (stored 2, 5) < (incoming 2, 5) -> FALSE! Write is a safe no-op!Why soft-delete tombstones at the destination are mandatory: If
Tombstone(I10, ver=(1, 6))ran a physicalDELETE FROM invoices_accounts WHERE invoice_id = 10, the destination would forget(1, 6)—and a delayed duplicate or replay of(1, 5)would re-insert the deleted row! Retainingis_deleted = truetombstones untilage > log_retention + max_replay_windowblocks zombie resurrections.Two-phase commit (transactional sink) option: Where readers need per-checkpoint batch atomicity and the sink supports transactions, writers stage pre-barrier rows and commit them together with
last_committed_checkpoint_id = Nin one sink transaction once Checkpoint N seals (trading ~1 checkpoint interval of extra read latency).Poison records & honest "exactly once" boundaries: Never silently drop a malformed event (dropping a
DELETEcauses permanent silent drift). Route poison records to a Dead-Letter Queue (DLQ) with an immediate alert, mark that primary key quarantined in ops metadata while allowing newer valid versions for that key to flow (pausing the partition only if the key itself cannot be parsed). Finally, be explicit that "effectively once" covers only deterministic processor state and versioned destination rows—network retries still transmit duplicates on the wire, external side effects (such as outbound webhooks) are not automatically deduplicated, and readers see intermediate row updates between commits.Consistency ladder: convergence vs. cross-source atomicity
Walk through the consistency vs. latency spectrum explicitly:
Guarantee Level What Readers See Extra Mechanism & Cost 1. Per-row convergence Each invoice_id converges to truth; a Default design above; lowest (Default) 50-invoice account edit flips over a few ms latency, highest throughput 2. Single-source tx atomicity Multi-row edits from ONE source tx appear Regroup Stage 2 outputs by tx_id together until end-of-tx marker + DB tx 3. Fan-out atomicity 1M invoices of a whale account flip in one Single 1M-row destination tx -> instant severe lock contention; avoid! 4. Cross-source "as-of T" Accounts and invoices aligned to wall-clock T Heartbeats on idle DBs + global within NTP clock-skew bound watermark min(commit_ts) + epoch view swap (adds watermark latency)Fundamental distributed-systems boundary: When an application commits to
accounts-dbandinvoices-dbas two independent local transactions without a shared transaction coordinator or globally synchronized commit clock (such as Spanner TrueTime), no downstream CDC pipeline can reconstruct an atomic cross-database boundary that never existed at commit time.Scaling, skew, retention, monitoring, and reconciliation
- Co-partitioning & rescaling: Partition Stage 1 by
hash(invoice_id)and Stage 2 byhash(account_id)across a fixed power-of-two count of key groups (for instance, 4,096 virtual buckets assigned across 32–128 worker tasks). Rescaling reassigns whole key-group RocksDB slices from the latest checkpoint without re-hashing individual keys. - Hot-key skew (the 1M-invoice enterprise account): (1) Skip Stage 2 fan-out whenever non-projected account columns change (such as
last_login_at); (2) coalesce rapid account updates by running large fan-outs as an asynchronous cursor overinvoices_by_acct[aid]that reads the latestaccounts[aid]record and restarts if superseded; (3) salt known whale accounts across(aid, bucket_0..63)sub-partitions and broadcast their account updates across all 64 sub-partitions. - Backpressure & correctness-driven retention: Bounded queues propagate slow sink writes back through Stage 2 -> Stage 1 -> Kafka consumer pause, leaving operational DB capture untouched. Never attach an arbitrary time-to-live (TTL) to live join state: a 5-year-old unpaid or active invoice must still update when its owning account renames itself today! Only tombstones expire (after the replay horizon).
- Separating freshness from correctness (continuous reconciliation): Zero consumer lag only proves freshness (
now - oldest_unapplied_commit_ts, kept live during quiet periods via 10-second source heartbeat writes), never correctness. A background Reconciler hashesinvoice_idinto 4,096 buckets and audits several buckets per minute: it reads the bucket's rows and log positions(P_inv, P_acct)from source read replicas, waits for pipeline watermarks to pass(P_inv, P_acct), compares row hashes againstinvoices_accounts(skipping rows whose stored(inv_ver, acct_ver)already advanced past(P_inv, P_acct)), alerts on drift, and self-heals mismatched keys via targeted watermark chunk re-snapshots.
Summary of trade-offs
- WAL CDC + durable Kafka log shields operational DBs and captures deletes in commit order, trading extra log infrastructure against lossy polling or dual writes.
- DBLog watermark snapshots avoid multi-hour source MVCC locks and support per-chunk crash resumption and surgical repairs, adding chunk-merge state in the connector.
- Denormalized Stage 2 join + reverse index turns reader queries into fast single-table lookups, trading ~125 GB of RocksDB state and account-update write amplification (fan-out) against query-time joins.
- Lexicographic
(inv_ver, acct_ver)conditional upserts + tombstones provide lock-free idempotency across crashes, replays, and task races without distributed 2PC locks, requiring tombstone retention and compare-and-set support at the sink.
- Co-partitioning & rescaling: Partition Stage 1 by
Intuition & how it works
Imagine maintaining a live, printed billing ledger derived from two separate filing cabinets managed by two independent teams: an Accounts cabinet (account IDs, company names, plan tiers) and an Invoices cabinet (invoice IDs, account IDs, amounts). Because the two teams update their cabinets at their own pace without locking both cabinets together, you keep two local organizers on your desk: a holding folder for invoices whose account card has not arrived yet, and a lookup card per account listing every invoice ID owned by that account—a reverse index (a lookup structure mapping each parent key to all child keys that reference it)—so whenever an account renames itself or closes down, you immediately know which ledger lines to update or strike out.
Obvious shortcuts break quickly on live multi-database joins. Periodically running a batch SELECT * FROM invoices JOIN accounts or polling an updated_at timestamp column hammers operational databases, misses hard-deleted rows altogether, and skips intermediate mutations. Conversely, piping raw change events straight into a destination table without local join state and source-log version numbers corrupts results whenever an invoice arrives ahead of its account, a deleted account leaves orphaned joined invoices behind, or a crash replay overwrites newer values with stale events.
Trace four concrete events on Account A1 and Invoice I10 to see how CDC (Change Data Capture, streaming committed row mutations from each database's write-ahead transaction log), local join state, and (inv_ver, acct_ver) version pairs preserve exactness:
- Out-of-order arrival (
I10arrives atinv_ver = 1referencingA1):A1is not in local state yet. Because this is an inner join, the processor storesI10insideinvoices_by_acct[A1][I10]and writes nothing to the destination yet. - Join match (
A1 = "Northwind"arrives atacct_ver = 5): The processor storesA1, scansinvoices_by_acct[A1], finds waitingI10, and writes(invoice_id=I10, ver=(1, 5), is_deleted=false, company_name="Northwind")to the destination. - Parent deletion (
A1is deleted atacct_ver = 6): Even thoughI10still sits in the invoices database, an inner join requiresI10to disappear from query results! Scanninginvoices_by_acct[A1]emits a tombstone (a soft-deleted record markedis_deleted = truethat retains its version tuple)(invoice_id=I10, ver=(1, 6), is_deleted=true). Because(1, 5) < (1, 6)under lexicographic comparison (comparing the first element first, breaking ties with the second), the destination marksI10deleted whileI10stays in processor state in caseA1is restored later. - Crash & replay: Suppose the processor crashes before committing its checkpoint and replays Step 2 (
ver=(1, 5)). The destination's conditional upsert (an atomic insert-or-update that applies only when the incoming version exceeds the stored version) evaluates(stored 1, 6) < (incoming 1, 5)-> false, discarding the stale replay automatically!
Key trade-offs
- Log-based CDC vs. timestamp polling vs. application dual writes. Tailing the database WAL (write-ahead log, the append-only log where a database records every committed mutation before modifying data pages) captures every insert, update, and hard delete in commit order without touching application code. Polling
updated_atmisses hard deletes and taxes operational tables, while dual-writing to the database and Kafka from application code causes permanent drift whenever one write succeeds and the other fails. - Durable partitioned log in the middle vs. streaming straight from DB to processor. Placing Kafka between capture connectors and stateful processors adds a broker cluster to operate, but shields operational databases from downstream backpressure (throttling upstream readers when a downstream sink slows down). Without that buffer, a slow sink stalls WAL consumption and fills up production database disks.
- Watermark-based incremental snapshot (DBLog) vs. single long snapshot transaction. Scanning initial tables in small primary-key chunks bracketed by low/high watermark markers written into the WAL avoids multi-hour read transactions that stall MVCC cleanup (database garbage collection of dead row versions) and supports per-chunk crash recovery and surgical key repairs, in exchange for chunk-deduplication state inside the connector.
- Pre-joined denormalized output vs. normalized tables joined at query time. Materializing
invoices_accountsturns reader queries into fast single-table lookups, but creates join fan-out (write amplification where editing one account with 50 invoices triggers 50 sink writes—or 1,000,000 writes for an enterprise whale account). Normalized sink tables avoid fan-out at the expense of slower query-time joins. - Versioned conditional upserts + tombstones vs. distributed two-phase commit (2PC) sinks. Comparing
(inv_ver, acct_ver)at the destination delivers lock-free idempotency across retries, replays, and concurrent worker tasks with millisecond sink latency. Transactional 2PC sinks offer atomic per-checkpoint batch visibility, but add at least one full checkpoint interval to end-to-end latency. - Per-row eventual convergence vs. cross-source point-in-time snapshots. Per-row convergence is fast and coordination-free, whereas serving a cross-database
"as of timestamp T"snapshot requires source heartbeats, global minimum watermarks across all sources, staged epoch swaps, and bounded clock skew—and still cannot fabricate cross-database transaction atomicity when the upstream databases committed independently.
Common mistakes
- Assuming a global timestamp order across independent databases. Clock skew and network jitter mean an invoice referencing
A1routinely arrives ahead ofA1itself; only per-key log position order within a single upstream database holds. - Starting a table snapshot and a WAL stream "around the same time" without coordinating log offsets. Uncoordinated handoffs either drop mutations committed in the gap or overwrite fresh live edits with stale snapshot rows.
- Omitting the
account_id -> invoice_idsreverse index or physically deleting destination rows. Without the reverse index, deleting an account cannot retract its joined invoices; without versioned tombstones at the sink (is_deleted = true), replaying an older upsert resurrects deleted rows. - Assuming source
DELETErecords always carry non-key columns likeaccount_id. Many databases log only the primary key (invoice_id) on deletes by default, which is why Stage 1 partitioned byinvoice_idmust rememberinvoice_owner[invoice_id] -> account_id. - Using processor wall-clock timestamps or random UUIDs as output versions. During crash replay, wall-clock versions mint brand-new timestamps that defeat destination version guards and overwrite newer live rows with stale replayed values; versions must derive strictly from source log positions.
- Attaching an arbitrary TTL (time-to-live expiration) to processor join state to cap disk usage. Expiring a multi-year active invoice from RocksDB silently stops updating that invoice whenever its account changes tier or gets deleted; join state must persist as long as the source record exists.
- Monitoring consumer lag alone and declaring the pipeline healthy. Low lag only measures freshness, not correctness—a logic bug or dropped delete creates permanent silent divergence unless caught by continuous bucketed hash reconciliation against source replicas.
Follow-up questions
- What happens when a single enterprise account owns millions of invoices and updates its profile—how do you prevent join fan-out from stalling that partition? Because Stage 2 partitions state by
account_id, updating a "whale" account with 1,000,000 invoices forces one worker task to emit 1,000,000 sink writes—creating a hot-partition stall that delays every other account hashed to that task. Mitigate this across four progressive layers: first, skip fan-out whenever none of the projected account attributes changed (for example, ignorelast_login_atupdates); second, execute large fan-outs asynchronously in chunks while reading the latestaccounts[aid]state so 10 rapid edits coalesce into 1 scan instead of 10 million writes; third, salt known whale accounts acrossKsub-keys(account_id, 0..K-1)spread across Stage 2 tasks while broadcasting their account updates to allKshards; or fourth, keep whale-account attributes normalized in a small side table joined at query time. - How does your sink design adapt if the target analytical store only permits append-only inserts rather than keyed upserts or deletes? Append every output upsert and tombstone as an immutable changelog row
(invoice_id, inv_ver, acct_ver, is_deleted, columns...)and expose a reader view that selects the highest(inv_ver, acct_ver)perinvoice_idvia a SQL window function (a function such asROW_NUMBER()that ranks rows within eachinvoice_idpartition) filtered byWHERE NOT is_deleted. To keep read latency bounded as the log grows, run periodic background compaction that materializes the latest record perinvoice_idinto a base snapshot table queried together with the recent uncompacted delta tail. Crucially, compaction must retainis_deleted = truetombstones until they age past the maximum replay horizon—otherwise, dropping a deleted key lets a delayed duplicate or crash replay of an older upsert become the sole surviving row and resurrect the deleted invoice!
sql
SELECT invoice_id, account_id, company_name, plan_tier, amount_cents
FROM (
SELECT c.*,
ROW_NUMBER() OVER (
PARTITION BY invoice_id
ORDER BY inv_ver DESC, acct_ver DESC
) AS rn
FROM invoices_accounts_changelog c
) ranked
WHERE rn = 1 AND NOT is_deleted;
- When business logic in the join transformation changes, how can you recompute the entire derived dataset from history while serving queries uninterrupted against a well-defined version? Run a parallel blue/green shadow rebuild behind a stable database view or table alias. Keep pipeline
v1writing live mutations intoinvoices_accounts_v1(transform_ver = 1), which currently backs the reader viewinvoices_accounts_v, while launching pipelinev2(transform_ver = 2) with isolated processor state reading from the start of log-compacted CDC topics (or executing a non-locking incremental watermark snapshot) into a separate tableinvoices_accounts_v2. Oncev2catches up to live lag targets and passes bucket-by-bucket hash reconciliation against the updated transformation spec, run a single atomic DDL swap (CREATE OR REPLACE VIEW invoices_accounts_v AS SELECT ... FROM invoices_accounts_v2 WHERE NOT is_deleted) so queries cut over instantaneously without ever reading a half-rebuilt table, keepingv1warm briefly for instant rollback before dropping it.
Follow-up questions
- What happens when a single enterprise account owns millions of invoices and updates its profile—how do you prevent join fan-out from stalling that partition?
- How does your sink design adapt if the target analytical store only permits append-only inserts rather than keyed upserts or deletes?
- When business logic in the join transformation changes, how can you recompute the entire derived dataset from history while serving queries uninterrupted against a well-defined version?
Similar questions
- Working with 3D Geometry Data
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform
- Prior Authorization Status Engine, Clinical Worklists, and Digests
- Diagnosing and Optimizing Full-Stack Web Request Latency