How Do You Synchronize a Continuously Updated Database into a Warehouse with a Full Snapshot and CDC?

August 15, 2025

At nine in the morning, you start copying a lab order table into an empty data warehouse. Doctors can still modify orders you've already read. Orders in the final batch may be canceled before you reach them. If copying takes two hours and you start listening for changes at eleven, what picks up the modifications between nine and eleven?

This was the question I wanted to understand when researching hospital data synchronization. Clinical systems need to continue accepting orders, and analysts want a complete dataset. Start with a current-state table. Once it catches up to a given source commit, every primary key's value and deletion status should match the source. Answering “How many times did this order change?” requires retaining event history separately. Copying all of today's rows cannot recover yesterday's change if it has already been reversed.

Why does reading the log only after the full scan miss updates?

Suppose a row has already been copied when the source changes it. If you wait until the entire scan is over and read the log from that moment onward, you miss that UPDATE, leaving the old value in the warehouse.

Let's work through three fictional lab orders. Numbers such as 100 and 101 are log positions. Order 17's update, for example, was committed at 09:10 and recorded at position 101.

Commit time and log positionWhat happened on the sourceWhat an ordinary pagination script saw
09:00, position 100Order 17 awaits results. Order 42 awaits specimen collection.Reads page one and writes the old state of order 17 to the warehouse.
09:10, position 101Updates order 17 to “results available.”The script is already on the next page.
09:12, position 102Cancels order 42 and deletes the row.By the time the script scans this range, the row is gone.
09:15, position 103Adds order 56, “awaiting collection.”The script subsequently reaches order 56 and copies it.
11:00, scan completeAssume no further changes.A subscription starting now never receives the update at 101.

At eleven, both sides have two rows, 17 and 56. The source has results for 17, while the warehouse still shows it waiting. Comparing row counts won't reveal the missed update.

Order 42 was deleted before the script read it, so it never entered the warehouse. By coincidence neither side has that row. If the deletion had happened after copying order 42, the same gap would have lost the DELETE and left an extra row in the warehouse.

Where should the snapshot meet the log?

A consistent snapshot lets readers continue to see the database as of one logical point. Change data capture (CDC) captures subsequent committed inserts, updates, and deletes. The database and connector must coordinate a shared boundary between the two. Here's how to verify the three orders step by step.

  1. Establish a read view at log position 100 and ensure that the logs needed after it will remain available. The full scan reads this view throughout, yielding order 17 awaiting results and order 42 awaiting collection. Even if it reads 42 at 10:00, it sees the row as it stood when the snapshot was taken.
  2. Once the baseline is loaded, apply changes after the boundary in source order. Position 101 updates 17, 102 deletes 42, and 103 inserts 56. A connector may collect changes during the scan and make the new values effective once the old rows have been loaded.
  3. When the destination has committed through 103, verification against the source at that position should find only 17 with results available and 56 awaiting collection. The warehouse may take a few extra minutes to reach 103. A few minutes' lag and a permanently missed 101 are different failures.

Debezium's PostgreSQL connector documentation describes the handoff as “the exact point at which the snapshot was made.” Ask which log position the baseline corresponds to. Taking the current source position after the scan finishes leaves a gap containing all the intervening changes. The connector manages the actual read position, and products have distinct boundary and recovery protocols.1

Can a large table be read in parallel chunks?

Yes, provided the snapshot of each chunk can be reconciled with changes during the scan. Flink CDC's MySQL connector supports chunked incremental snapshots. It divides records by primary key or a designated chunk key. Before reading each chunk, the connector records the current MySQL binary log (binlog) position, called the LOW offset. After reading it, it records the HIGH offset. These delimit the part of the log produced during the scan. The connector merges changes and deletions for that chunk into its scan results. Chunks can run in parallel, each with its own log boundaries.2

Two uses of “watermark” can be confusing. Flink CDC documentation also calls a chunk's log boundaries its low/high watermarks. An event-time watermark in Flink stream processing carries a timestamp. A watermark of 10:00, for instance, means that under the current policy, lab results with event times up to and including 10:00 are expected to have arrived. A window can trigger on it, although late results may still arrive.23

Spark can also speed up copying by opening several JDBC connections and executing parallel SELECT queries over primary-key ranges. Partition columns and connection counts only assign the rows to readers. Whether connections share a snapshot and how to recover deletes during the scan still depend on the database or synchronization protocol. When increasing concurrency, observe source connection load, disk load, and latency for online queries.4

Poll timestamps, subscribe to the log, or get updates from FHIR?

What the source exposesSuitable useAdditional requirements
Read-only SQL and an updated_at fieldPeriodically reread recently changed rows for tables allowing lag and later reconciliation.Use primary keys for stable pagination within a timestamp. Late commits and backfilled old timestamps can still be missed. Combine overlapping windows with idempotent merging and collect deletion markers separately or compare the full table periodically.
Database logs and a supported connectorMaintain a current-state replica, including physical deletes. Raw changes can be retained for replay.Stable row identities, an explicit retention period, and a restartable log position. Check supported changes, privileges, and schema evolution against the database version.15
Application events or a FHIR serviceSubscribe to meaningful business changes, or use resource history to obtain patient resource versions and expand them into analytical tables.FHIR is a healthcare data exchange standard. The service must support the relevant history interaction, and consumers must handle pagination, deleted entries, and the available history horizon. One resource update may not correspond one-to-one with an underlying relational row change.6

Another question I asked was what to do when a source updates the same row repeatedly throughout the day and no connector supports the vendor's log format. Start with the answer the analyst needs. For “What is order 17's current state?”, reread the row, overwrite the previous value by primary key, and reconcile deletions separately. For “How many times did it change this morning?”, polling once a minute may reveal only the last change. Ask the supplier for versioned business events. If changes to the writing application are authorized, commit each business update and a sequential change record in the same transaction, then read that table in order. With only read access to current rows and no history, the promise can cover reconciliation as of a point in time. The destination cannot reconstruct intermediate versions the source never retained or delivered.

In August I compared another situation. A legacy system might send HL7 v2 messages or provide CDA clinical documents, while a research application needs data through FHIR. One option is an external conversion layer. InterSystems first transforms the message or document into its own clinical data format, SDA, then maps it to FHIR resources collected in a Bundle, a set of resources transmitted together.7

My research draft also asked how a Patient resource update reaches the warehouse. Suppose a patient moves and the application submits the new address through PUT /Patient/42. If resource history is supported, the warehouse can page through GET /Patient/_history, find the destination record by resource ID, and write the new address. The two address versions belong to one patient and count as one person. Resuming after an interruption depends on which versions the service retains and whether deletions from that period are available. To reconstruct Caché/IRIS source tables row by row, the starting point is still a table snapshot and a resumable database change record.6

Here's a change you can miss. A follow-up system subscribes to “patients living in A.” Patient 42 moves to B and the updated record no longer matches. This kind of FHIR R4 subscription does not issue a departure notification. If the consumer can access change history, it should resume reading at its saved position. If it can only retrieve the current roster, it must perform periodic full reconciliation. The latter can correct today's list but cannot recover every version between reads.86

For batches of patient records, FHIR also offers bulk export. On August 14 I read HAPI FHIR's export parameters class and found resource type and start time fields. A service supporting bulk export can export patients with _type=Patient. NDJSON is the default file format, one resource per line. In the next batch, pass the last manifest's transactionTime to _since to request resources changed since then. This gives the warehouse a continuation point based on server time. The manifest's deleted field is optional. If a previously exported patient record is deleted, check whether the service actually delivers that deletion.9

For imaging reports, check what the source sends when a report is signed, corrected, or withdrawn. Suppose a metric counts currently signed reports. A corrected report still counts as one, whereas a withdrawn one should leave the count. Consumers should update current state by stable report ID and source version. Replaying the same correction or withdrawal should leave the count unchanged. If upstream only sends the initial sign-off, reconcile later status separately. For the relationship between orders, reports, and raw images, see Why count CT orders without reading DICOM images?.

Even with a baseline and an incremental source, write order matters. Suppose the source captured 101, but the destination lost power immediately after writing it. What would remain?

What happens on replay if the system crashes just after writing the destination?

Suppose the warehouse has committed the update at log position 101, but the process exits before recording “processed through 101.” On restart, it receives 101 again. If the operation is “increment the results-available counter,” the report will count an extra order. If it sets order 17's state by primary key to “results available,” repeating it gives the same row. This is idempotence. Debezium's JDBC sink supports key-based upsert (update if present, insert otherwise), and deletion handling needs explicit configuration.10

Idempotence handles duplicates. Older events arriving late also raise an ordering issue. If 42 was deleted at 102 and an older snapshot row reappears, an ordinary upsert resurrects it. One option is strict ordering per primary key, publishing changes only after the baseline is complete. If interleaved writes are allowed, retain a comparable source version per key, keep a versioned deletion marker even for deletes, and accept only newer events. The version must distinguish multiple changes to the same key within a transaction. A business timestamp alone may be ambiguous.

Recovery progress has an ordering constraint too. Saving “processed through 101” before writing the destination risks skipping 101 permanently if the system crashes in between. Ideally commit result and progress in one transaction. Across systems, a common approach is to confirm the destination commit before advancing progress and allow replay at the boundary. End-to-end “exactly once” depends on the source's replayability, processor state recovery, and transactional commits or idempotent writes at the sink. A checkpoint restores computational state. It cannot automatically recall an email already sent or undo a repeated external operation.11

If a failed message reaches a dead-letter queue, can we declare the report successful?

Return to position 101. Suppose the transformer cannot recognize the lab's new status code even after retries. A dead-letter queue (DLQ) retains failures for inspection and reprocessing. Kafka Connect sinks, for example, can configure error tolerance and a dead-letter topic. Which errors can be isolated depends on the connector and processing stage.12

At 101, the transformer either recognizes order 17's status and writes the analytical table by order ID and source version, or retains the original message and error in the DLQ. Once the mapping is fixed, 101 goes back through the transformer.

flowchart LR
    E["101:17 号检验单更新"] --> M["转换状态码"]
    M -->|"识别成功"| T["按单号和源版本写分析表"]
    M -->|"无法识别"| Q["死信队列:保留原消息和错误"]
    Q -->|"修正映射后重放 101"| M

The source already shows results for 17 while the report still shows it waiting. Successfully processing 102 and 103 cannot certify report completeness through 103. Carry the original primary key and version into the repair. If 17 already has a newer change at 104, retain that state when replaying 101. Publish the reports only after verifying that isolated events have been processed and the orders and counts meet their definitions.

What must be checked for Oracle, Caché, and IRIS?

SourceConnecting full and incremental readsEvidence to check before launch
PostgreSQL / MySQLPostgreSQL logical decoding reads the write-ahead log (WAL), with a log sequence number (LSN) identifying a WAL position. A MySQL binlog position can be represented by filename and offset. Use the corresponding connector to coordinate the initial snapshot and log position.For PostgreSQL, inspect replication slots and disk space occupied by retained logs. For MySQL, check log format, retention, snapshot mode, and lock requirements. Measure acceptable pauses and load for continuous business writes on the actual version and configuration.15
OracleDebezium's Oracle connector establishes a system change number (SCN), runs Flashback Query at that SCN to read the tables, then captures changes from redo logs. The LogMiner path needs archiving and supplemental logging.Check two retention windows. Old row versions must survive a long historical read, or ORA-01555 may occur. Redo must remain available until incremental consumers catch up. Being able to read old rows does not replay new transactions.13
InterSystems Caché / IRISLegacy Caché supports journal-based shadowing. IRIS reporting async mirror members can serve reporting queries. A replica reduces contention between historical scans and live queries, but can lag or advance during a scan.Ask operations how to establish a fixed read view, which recoverable boundary it represents, and how updates and deletes map to business-keyed events. If all you can read is a continuously changing replica, relative query times cannot prove that full and incremental reads meet.14

My research considered reading terabyte-scale Caché/IRIS tables from replicas and continuously writing them to a lake. I'd first verify the approach on one test table. Fix a boundary, start a scan, update one row and delete another with a test account midway through, and deliberately restart the consumer. Show where both rows end up and which position recovery resumes from before choosing how many Spark partitions to open. If the business only exposes FHIR, test history coverage and retention instead. The hospital's existing TiDB synchronization project already supported cross-system queries. Ingesting a replica into a lake was a design I compared later.

With multiple Iceberg tables, when is a report ready to read?

Parquet is a columnar file format suited to scanning selected columns. Iceberg is a table format that records which data files and deletion information belong to the current table version. Upload files directly to object storage and a reader may see a half-written batch. A single-table Iceberg commit can switch metadata atomically, exposing a complete before or after snapshot. Maintaining one current row per order also requires a write mode that handles updates and deletes. For example, the Iceberg 1.9.2 Flink documentation requires v2 tables and a primary key or identifier fields for upsert. For partitioned tables, the equality fields must include the partition fields.1516

Suppose orders and results commit separately. Orders may have reached 103 while results remain at 100. Both tables are queryable, but calculating “percentage of lab orders with results” now mixes two batches. If they share a transaction log, wait until both have processed an agreed boundary, then publish the two corresponding table snapshot IDs together for reporting. Oracle and IRIS positions cannot be compared directly across sources. Define a business cutoff, record progress separately, and specify how late data revises a report.

Frequent small batches and writes across many tables and partitions leave large numbers of small files, slowing queries and metadata operations. During a trial run, record source load, oldest unconsumed log position, per-table lag, most recent successful commit, and file size distribution. Adjust concurrency and commit frequency using those numbers, and compact small files when necessary. If a table encounters a schema change, pause it and retain pending events. Reports depending on it should remain pinned to the last verified version.17

Back to the three orders. For acceptance testing, fix an auditable source boundary and matching destination version, then reconcile primary-key sets, order 17's result status, order 42's deletion, and departmental counts. Interrupt the pipeline during its full scan, then separately after destination commit but before saving progress. Restart and repeat the checks. If the required logs have expired, recovery must detect the gap and establish a new baseline. When a pipeline can account for all these outcomes, the business can independently verify what “synchronization succeeded” means.

Footnotes

  1. Debezium authors. (n.d.). Debezium connector for PostgreSQL, “How the connector works,” paragraph on changes after the initial snapshot. Debezium Documentation. Snapshots. PostgreSQL Global Development Group. (n.d.). Logical decoding concepts. PostgreSQL Documentation. Replication slots. ↩ ↩2 ↩3

  2. Apache Software Foundation. (n.d.). MySQL. Apache Flink CDC Documentation. Chunk Reading Algorithm, steps 1–5 · Problem Scenario, low and high watermark. ↩ ↩2

  3. Apache Software Foundation. (n.d.). Timely stream processing. Apache Flink Documentation. Event time and watermarks. ↩

  4. Apache Software Foundation. (n.d.). JDBC to other databases. Apache Spark 3.5.6. Data source options, including numPartitions. ↩

  5. Debezium authors. (n.d.). Debezium connector for MySQL. Debezium Documentation. Initial snapshots and locks. ↩ ↩2

  6. Health Level Seven International. (2019). RESTful API. FHIR Release 4, v4.0.1. History interaction. ↩ ↩2 ↩3

  7. InterSystems. (n.d.). About SDA. SDA: InterSystems Clinical Data Format. Opening example from CDA to SDA to FHIR. InterSystems. (n.d.). SDA-FHIR transformations. Using FHIR Productions. Opening HL7 v2 example and Bundle output in “SDA to FHIR Productions”. ↩

  8. Health Level Seven International. (2019). Subscription. FHIR R4 v4.0.1. §2.46.1 Scope and Usage, matching after updates, leaving the set, and deletion · rest-hook notifications and payload. ↩

  9. HAPI FHIR contributors. (n.d.). BulkExportJobParameters.java (v8.2.0). GitHub. Resource type and start time fields. Health Level Seven International. (n.d.). Bulk data export. FHIR Bulk Data Access Implementation Guide, v2.0.0. Request parameters, continuing from the previous returned time, and the optional deleted field in the completion manifest. ↩

  10. Debezium authors. (n.d.). Debezium connector for JDBC. Debezium Documentation. Idempotent writes and delete mode. ↩

  11. Apache Software Foundation. (2025). Kafka Connect user guide. Apache Kafka 4.0 Documentation. Error reporting, quarantining messages, and dead-letter topics. ↩

  12. Debezium authors. (n.d.). Debezium connector for Oracle. Debezium Documentation. SCN and initial snapshot · Database configuration. ↩

  13. InterSystems. (n.d.). Shadowing. Caché Data Integrity Guide, 2018.1. Shadow databases and journaling. InterSystems. (n.d.). Mirroring architecture and planning. InterSystems IRIS High Availability Guide. Asynchronous members and reporting reads. ↩

  14. Apache Software Foundation. (n.d.). Reliability. Apache Iceberg 1.9.2. Atomic table updates. ↩

  15. Apache Software Foundation. (n.d.). Flink writes. Apache Iceberg 1.9.2. Upsert. ↩

  16. Apache Software Foundation. (n.d.). Maintenance. Apache Iceberg 1.9.2. Compact data files. ↩

© 2025 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2025-08-15). How Do You Synchronize a Continuously Updated Database into a Warehouse with a Full Snapshot and CDC?. https://caiborui.com/blog/2025-08-15-zh-database-snapshot-cdc-iceberg-entrans

@misc{borui2025-b93135ef,
  author = {borui},
  title = {{How Do You Synchronize a Continuously Updated Database into a Warehouse with a Full Snapshot and CDC?}},
  year = {2025},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2025-08-15-zh-database-snapshot-cdc-iceberg-entrans}
}