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

  1. 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

    1. 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 by invoice_id. We also handle mutable foreign keys (an existing invoice's account_id reassigned from A1 to A2), which is the subtlest correctness edge case; if account_id is immutable, Stage 1 below becomes even simpler.
    2. Source change-stream contract: Rather than polling updated_at timestamps (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_id or invoice_id), operation (INSERT | UPDATE | DELETE), and post-change row values (after; on DELETE, 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_ts timestamp (for lag monitoring) and schema_id.
    3. Cross-source consistency: Because accounts-db and invoices-db commit independently without a shared clock or distributed lock, the baseline guarantee is eventual convergence: if both sources pause at log offsets P_acct and P_inv and the pipeline drains, the destination table equals the exact inner join invoices@P_inv JOIN accounts@P_acct. Stronger cross-database snapshot semantics are analyzed in Step 8.
    4. Destination contract: The queryable serving store must support keyed conditional upserts—updating an invoice_id row only when the incoming version pair is strictly newer than the stored version pair—plus soft-delete tombstones (rows marked is_deleted = true so replayed older updates cannot resurrect deleted records). Append-only analytical sinks are addressed in the follow-ups.
  2. 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.
  3. Data contracts: change events, version tuples, and tombstones

    Every event emitted by a CDC capture worker carries a deterministic, comparable version derived 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);
    
  4. 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.

  5. 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 READ transaction 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 at pH equals what SELECT observed, so emitting it at version pH is exact; any subsequent mutation carries position > pH and supersedes it cleanly.
    • Mutated during [pL, pH] (I7): Evicting I7 from the chunk buffer prevents the stale $50 snapshot row from overwriting live WAL event e2 ($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_id tracked 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.
  6. Deep dive 2: two-stage stateful join, parent deletes, and reassignments

    Because accounts.cdc and invoices.cdc originate from separate databases, events arrive in per-key commit order within one source, with no ordering guarantee across the two sources. Moreover, invoices.cdc is partitioned by invoice_id (and a DELETE record may carry only invoice_id, omitting account_id!), whereas the join must co-locate records by account_id.

    A two-stage stateful processor handles both constraints cleanly:

    • Stage 1 (partitioned by invoice_id): Deduplicates invoice events by inv_ver and tracks invoice_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): Maintains accounts[aid] alongside a reverse index invoices_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!
    
  7. 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 physical DELETE 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! Retaining is_deleted = true tombstones until age > log_retention + max_replay_window blocks 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 = N in 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 DELETE causes 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.

  8. 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-db and invoices-db as 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.

  9. Scaling, skew, retention, monitoring, and reconciliation

    • Co-partitioning & rescaling: Partition Stage 1 by hash(invoice_id) and Stage 2 by hash(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 over invoices_by_acct[aid] that reads the latest accounts[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 hashes invoice_id into 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 against invoices_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.

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:

  1. Out-of-order arrival (I10 arrives at inv_ver = 1 referencing A1): A1 is not in local state yet. Because this is an inner join, the processor stores I10 inside invoices_by_acct[A1][I10] and writes nothing to the destination yet.
  2. Join match (A1 = "Northwind" arrives at acct_ver = 5): The processor stores A1, scans invoices_by_acct[A1], finds waiting I10, and writes (invoice_id=I10, ver=(1, 5), is_deleted=false, company_name="Northwind") to the destination.
  3. Parent deletion (A1 is deleted at acct_ver = 6): Even though I10 still sits in the invoices database, an inner join requires I10 to disappear from query results! Scanning invoices_by_acct[A1] emits a tombstone (a soft-deleted record marked is_deleted = true that 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 marks I10 deleted while I10 stays in processor state in case A1 is restored later.
  4. 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_at misses 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_accounts turns 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 A1 routinely arrives ahead of A1 itself; 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_ids reverse 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 DELETE records always carry non-key columns like account_id. Many databases log only the primary key (invoice_id) on deletes by default, which is why Stage 1 partitioned by invoice_id must remember invoice_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, ignore last_login_at updates); second, execute large fan-outs asynchronously in chunks while reading the latest accounts[aid] state so 10 rapid edits coalesce into 1 scan instead of 10 million writes; third, salt known whale accounts across K sub-keys (account_id, 0..K-1) spread across Stage 2 tasks while broadcasting their account updates to all K shards; 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) per invoice_id via a SQL window function (a function such as ROW_NUMBER() that ranks rows within each invoice_id partition) filtered by WHERE NOT is_deleted. To keep read latency bounded as the log grows, run periodic background compaction that materializes the latest record per invoice_id into a base snapshot table queried together with the recent uncompacted delta tail. Crucially, compaction must retain is_deleted = true tombstones 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 v1 writing live mutations into invoices_accounts_v1 (transform_ver = 1), which currently backs the reader view invoices_accounts_v, while launching pipeline v2 (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 table invoices_accounts_v2. Once v2 catches 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, keeping v1 warm briefly for instant rollback before dropping it.

Follow-up questions

Similar questions

More Autodesk interview questions

All 2 Autodesk questions →