Ingestion Patterns: Intermediate
Netflix keeps search indexes in sync with production databases. When a title is pulled from the catalog, a poller asking for recently changed rows never learns the row was deleted, so the title stays searchable. Re-dumping the table under a lock would stall writes. Netflix engineers published a framework that reads the database's change log and dumps existing rows without locks. This lesson builds that design for an orders table.
Full load: read everything, replace everything
A full load runs a SELECT over the whole table and overwrites the target. Correctness comes built in. Every change shows up, hard deletes included, because the target becomes an exact copy as of the read, and the next run repairs a bad one. The cost grows with the size of the table, whatever the amount of change. The stores table has 1,800 rows; the orders table has 40 million, and a nightly full load reads all of them even on a day when only 300,000 changed.
Incremental load: read only what changed
An incremental load needs a column that moves forward every time a row changes: usually updated_at, set by the application on each write, or an ever-growing id for tables that only receive inserts. Each run reads rows past the point the previous run reached and upserts them by primary key. The column needs an index on the source, or every small run still scans the whole table to find its rows.
Incremental loads have 2 blind spots. A hard delete removes the row, so its updated_at never moves again and the target keeps the order forever. A write that skips updated_at, such as a bulk fix run by hand, is invisible too. Teams cover both with a periodic full comparison, or by moving to change data capture, the next section's subject.
- Reads every row on every run
- Catches every change, hard deletes included
- Needs no change-tracking column
- The next run repairs a bad run
- Cost grows with table size
- Reads rows changed since the bookmark
- Misses hard deletes and untracked writes
- Needs a reliable updated_at or growing id
- Needs a bookmark store and a keyed upsert
- Cost grows with change volume
The bookmark store
Write the bookmark last
The bounded query
The tempting query filters WHERE updated_at > :bookmark and saves the largest updated_at it saw as the next bookmark. That loses rows. The application stamps updated_at when the statement runs, but other sessions see the row only once its transaction commits. A transaction that stamps 09:59:58 and commits at 10:00:03 is invisible to a query running at 10:00:01. That query saves a bookmark about 10:00:00, and every later run starts after the late row.
The fix is a window whose ends are both fixed before the read starts. The lower bound is the stored bookmark. The upper bound is the run's start time minus a safety lag longer than the source's longest transaction. With a 5-minute lag, the 10:00 run stops at 09:55, and the row stamped 09:59:58 lands in the 11:00 run's window, long after its commit. An id bookmark has the same gap, because id 5001 can commit after id 5002; for insert-only tables, bound a created_at timestamp with the same lag instead.
| Run starts | Lower bound (excluded) | Upper bound (included) | Bookmark saved |
|---|---|---|---|
| 10:00 | 08:55 | 09:55 | 09:55 |
| 11:00 | 09:55 | 10:55 | 10:55 |
| 12:00 | 10:55 | 11:55 | 11:55 |
The strict > on the lower bound and <= on the upper make consecutive windows meet with no gap and no overlap, so a row stamped exactly 09:55:00 belongs to the 10:00 run alone. The lag costs freshness: a row reaches the warehouse 5 to roughly 65 minutes after it is stamped, the lag plus up to one hourly interval.
An hourly job on orders was changed to insert its bookmark row first and load the window second. Tonight the worker is killed right after the bookmark insert. What does the next run do?
Trigger-based: the database copies each change
A trigger is a function the database runs inside the same transaction as a write. A CDC trigger on orders inserts a row into orders_changes for every write to it, deletes included. Each of those rows records which operation ran and when, along with the key and the new values. Ingestion reads orders_changes with a bounded window and prunes what it has loaded. Deletes are captured, and so is every intermediate value.
The source pays for it. Every write to orders now performs a second write, which adds write latency and storage. Every column change to orders also needs a matching change to the trigger and the side table. Trigger-based CDC fits databases that expose no change log, or tables with modest write rates where nobody can get log access.
Query-based: poll the table for changes
Query-based CDC is the bounded incremental pull run on a timer of 10 minutes, or as little as 1 minute. It needs only a read-only login and an updated_at column. It sees each row as it stands at poll time, so 2 updates between polls arrive as a single change, and a hard-deleted row never arrives at all. Every poll is also a query on the source, so a shorter interval means more load.
Log-based: read the replication log
The animation runs 4 changes to orders between 10:00 and 10:11: order 1001's total rises to 13000 at 10:03, order 1003 is inserted at 10:05, order 1002 is deleted at 10:06, and 1001 rises again to 13500 at 10:08. Play both variants and compare the replica at the end.
| Family | Hard deletes | Intermediate states | Extra source writes | Access needed | Latency |
|---|---|---|---|---|---|
| Trigger-based | Captured | Captured | A second write per change | Create triggers and tables | Poll interval of the side table |
| Query-based | Missed | Collapsed to the latest | None | Read-only login | Poll interval |
| Log-based | Captured | Captured | None | Replication privilege, log config | Seconds |
Choosing a family
When deletes or every intermediate state matter and you can get replication access, log-based wins. When the source is a vendor-hosted database that grants a read-only login, query-based is the only family on offer, and you ask the owners for soft deletes, a deleted_at column, so a delete becomes an update the poll can see. Trigger-based is the fallback for when deletes matter but log access is impossible, provided the write rate can absorb a second write.
A fraud model needs every status a payment passes through (authorized, captured, refunded), and some payments move through all 3 within a minute. Hard deletes never happen. The source is a self-hosted Postgres your team administers. Which family fits?
Change records move left to right. The slot keeps WAL on the source until the connector confirms each position.
The initial snapshot
The WAL keeps recent history, usually hours to days, and never the whole life of a table. A connector started today on orders would see today's changes and none of the 40 million rows already there. So every log-based pipeline begins with a snapshot: a full copy of the table, stitched to a position in the log.
Replication slot lag
The slot retains WAL for the whole database cluster, every table, even when the pipeline reads only orders. Suppose the cluster writes 6 GB of WAL an hour and its disk has 150 GB free. A connector that dies on Friday evening fills that disk by Saturday night, and a Postgres primary that cannot write WAL shuts down, taking the application with it.
- ▸Alert when
retained_bytespasses 20 GB and page at 50 GB, so someone acts with hours to spare. - ▸Set
max_slot_wal_keep_size(Postgres 13 and later) well below free disk, such as 100 GB, so Postgres invalidates the slot before the disk fills. - ▸Drop the slot when its pipeline is retired. An inactive slot retains WAL exactly like a stalled one.
When the table's definition changes
Postgres logical decoding carries row changes and no DDL. After someone runs ALTER TABLE orders ADD COLUMN currency text, the connector finds out from the next change to orders, which arrives with a relation message describing the new column list. Records from then on carry the extra field, and records already in the stream keep the old shape.
| Change on the source | What the stream shows | Who breaks |
|---|---|---|
| Add a nullable column | A new field from the next change on | Nobody, if readers ignore unknown fields |
| Rename a column | Old field gone, new field present | Every reader of the old name |
| Drop a column | Field missing from new records | Readers that require it |
| Widen `integer` to `bigint` | Same field, larger values possible | Sinks typed to the narrow type |
The orders connector crashed 9 hours ago. Retained WAL is 54 GB, the slot has no max_slot_wal_keep_size cap, and the disk has 96 GB free. The connector fix is ready. What should happen first?
- Crash in between: the batch is read again
- Cost: duplicate records in the sink
- Called at-least-once delivery
- Crash in between: the batch is never written
- Cost: records silently missing
- Called at-most-once delivery
Dedupe by key
When each record carries a stable id, keep a single row per id. A queue event usually has a producer-assigned event_id. A CDC change is identified by its primary key plus its LSN: a replay repeats both, while 2 real updates to order 1001 have different LSNs. Dedupe each staged batch before it touches the target.
| order_id | lsn | op | total |
|---|---|---|---|
| 1001 | 41210 | update | 13000 |
| 1003 | 41388 | insert | 4200 |
| 1001 | 41210 | update | 13000 |
| 1002 | 41502 | delete | null |
| 1001 | 41640 | update | 13500 |
| order_id | lsn | op | total |
|---|---|---|---|
| 1001 | 41210 | update | 13000 |
| 1003 | 41388 | insert | 4200 |
| 1002 | 41502 | delete | null |
| 1001 | 41640 | update | 13500 |
LSNs appear here as small integers. Real ones are 64-bit log positions that Postgres prints as 2 hex numbers, such as 0/16B3748.
Uniqueness enforced at the sink
A current-state table, with a row per order, also needs a version rule: upsert by order_id, and apply a change only when its LSN is higher than the stored one. A replay of the 10:03 change (total 13000) arriving after the 10:08 change (total 13500) compares lower and is skipped, so the replica keeps 13500 instead of rolling back. Apply a delete as a tombstone, a row flagged deleted that keeps the delete's LSN; otherwise a late replay of an older update to 1002 finds no stored row and revives the order. Purge tombstones once replays can no longer arrive.
Content-hash ids
| Hash input | Same file retried | 2 identical purchases on different lines | Verdict |
|---|---|---|---|
| `raw_line` | Same id | Same id, a purchase lost | Too few inputs |
| `raw_line` + `ingested_at` | New id, duplicate loaded | Different ids | Too many inputs |
| `file_name` + `line_number` + `raw_line` | Same id | Different ids | Right |
ab followed by c and a followed by bc build the same string and the same id.The third row holds while the partner never resends a file under the same name with its lines reordered. If they do, ask them for a row id.
A consumer reads a queue, writes each batch to the warehouse with an anti-join on event_id, then acknowledges the batch. A teammate proposes acknowledging before the write to stop redeliveries. What does the change do?
| Strategy | How it reads | Scale | Hard deletes | Freshness | Team cost |
|---|---|---|---|---|---|
| Nightly full snapshot | `SELECT` the whole table, replace the target | Up to a few million rows | Caught | Once a day | A scheduled job |
| Incremental pull | Bounded window on `updated_at`, keyed upsert | Large tables with an indexed change column | Missed | Run interval plus safety lag | Bookmark store and idempotent sink |
| Log-based CDC | Logical replication slot, snapshot then stream | Any size, high change rates | Caught | Seconds | Slot monitoring, re-snapshot runbook, DBA access |
Three tables in a single database
stores has 1,800 rows and changes a few times a week. A nightly full snapshot copies it in under a second, catches the occasional closed store that someone deletes, and has no bookmark to corrupt.
products has 2 million rows and about 50,000 updates a day, and is never hard-deleted: a discontinued product gets discontinued_at set, which also moves updated_at. The catalog team reads it hourly. An hourly incremental pull with a 5-minute lag meets every requirement, and it can run against a read replica so the primary never sees the query.
orders has 40 million rows and 300,000 changes a day, and the application hard-deletes orders that customers cancel within 10 minutes of placing them. Finance wants revenue within 5 minutes. An incremental pull would keep every cancelled order in revenue forever, and the nightly full copy takes 25 minutes and leaves the warehouse a day behind. Log-based CDC meets both needs, and that is why the team takes on its slot monitoring and re-snapshot runbook.
When the team cannot run CDC
Team capacity can overrule the table. Log-based CDC needs wal_level = logical on the source, a setting that takes a database restart, plus a role with replication privilege and an on-call engineer who knows what a stalled slot does to the primary's disk. A 2-person team without DBA access can serve orders with a hybrid: an incremental pull every 15 minutes, and a nightly job that lists every order_id in the source, compares the list with the replica, and deletes the orders that are gone.
The pull carries changed rows every 15 minutes. The diff carries deletes once a night, and blocks itself when the gap looks like a broken read.
- Decide per table, weighing size and change rate against delete and freshness needs and who will run it
- Keep full snapshots for small tables even when big ones move to CDC
- Save the bookmark only after the data commits
- Make every sink absorb repeats, whether by dedupe or by a uniqueness or version check
- Alert on retained WAL long before it threatens the source disk
- Run CDC on a 1,800-row table that a full copy refreshes in a second
- Trust updated_at before confirming every writer sets it
- Leave a replication slot behind when its pipeline is retired
- Let a key diff delete a large share of rows without a threshold check
A refunds table has 6 million rows and gains 20,000 a day. Rows are never updated or deleted; corrections arrive as new rows. Analysts need it hourly, and your team has no replication access. Which strategy fits?
> A food-delivery marketplace feeds its warehouse from a single Postgres cluster. stores reloads in full each night, products arrives through an hourly bounded pull, and orders streams through a logical replication slot so finance sees revenue within 5 minutes, cancellations included. One Saturday the connector's credential expires. Retained WAL climbs past the 20 GB alert, the on-call renews the credential, and the connector drains 4 hours of backlog, some of it applied once already before the stall.
Pick full, incremental or log-based loads per table, keep bookmarks honest, and land every retried change once.
- Category
- Pipeline Architecture
- Difficulty
- intermediate
- Duration
- 32 minutes
- Challenges
- 12 hands-on challenges
Topics covered: Full, Incremental, and Bookmarks, CDC: The Three Families, Operating Log-Based CDC, Idempotent At-Least-Once Ingest, Three Ways to Ingest from Postgres
Lesson Sections
- Full, Incremental, and Bookmarks (concepts: Full vs Incremental Load)
Every ingestion run against a database first decides which rows to read. A full load reads every row and replaces the target copy. An incremental load reads only rows changed since the previous run and merges them into the target by primary key, which depends on a small piece of saved state. Full load: read everything, replace everything Incremental load: read only what changed The bookmark store The point an incremental load has reached is its bookmark, also called its high-water mark. It is th
- CDC: The Three Families (concepts: Change Data Capture)
Change data capture (CDC) turns each write to a source table, deletes included, into a change record the pipeline can apply downstream. The bounded pull from the previous section is already a crude form of it. The 3 families of CDC differ in where they find the changes: in a side table the database fills, in the table itself, or in the database's own log. Trigger-based: the database copies each change Query-based: poll the table for changes Log-based: read the replication log Every relational da
- Operating Log-Based CDC (concepts: Change Data Capture)
A log-based pipeline on Postgres needs ongoing care in 3 places: the first copy of rows that existed before it started, the replication slot that holds its place in the log, and table definitions that change while it runs. The initial snapshot Postgres makes that stitch exact. Creating a logical replication slot fixes its starting position, an LSN (log sequence number), and can export a transaction snapshot that sees the database as of that LSN. The connector copies the table through that snapsh
- Idempotent At-Least-Once Ingest (concepts: Idempotency)
Every ingestion consumer does 2 things per batch, whatever it reads from: it writes the records to the sink, and it saves its position (an offset for a queue, an LSN for a replication slot, a file name when it reads a folder of files) so it can resume after a restart. A crash can land between the 2 steps, and their order decides what that crash costs. Ingestion picks at-least-once, because a duplicate can be found and removed while a missing record leaves no trace. A restarted CDC connector rere
- Three Ways to Ingest from Postgres (concepts: Change Data Capture)
Postgres supports all 3 strategies from this lesson, and a single database often uses all 3, table by table. The choice for each table comes down to 4 questions: how big is the table and how fast does it change, are rows hard-deleted, how fresh must the copy be, and who will be on call for it. Three tables in a single database When the team cannot run CDC The hybrid has a price. Revenue can trail the source by 20 minutes instead of 5, since the pull interval stacks on top of the lag. A cancelled