System Design

Core Concepts

Change Data Capture

A job that polls updated_at can't see a delete. Change data capture reads the database's own log instead, which makes every consumer a replica of your tables: it has to start from a snapshot that matches its place in the log, and it depends on your columns.

Why you are doing this at all

You need to keep a search index in step with Postgres. The first idea is often a job that runs every minute and asks for rows whose updated_at is newer than last time. That job can't see a delete. A deleted row has no updated_at left to read, so a product you removed stays searchable.

Shopify ran a system like this, called Longboat, over the MySQL shards behind its core monolith. It could query each table at most once an hour, because querying more often hurt the source databases, and it missed every hard delete.

The other obvious answer is to have the application write to both, the database and then the index. That's a dual write, and it fails without an error when the process dies between the two writes. The outbox pattern explains why a retry can't repair it.

Change data capture (CDC) reads the database's own log instead. Every change a database commits is also written to a log. In Postgres it's the write-ahead log (WAL), written before any data changes, and write-ahead logs covers what it is and how recovery uses it. In MySQL it's the binary log, or binlog, kept for replication.

A CDC connector such as Debezium reads the log and turns each committed row change into an event. The event holds the row before and after the change, and the connector publishes it, usually to one Kafka topic per table.

A consumer of that stream isn't asking your tables what changed. It's doing what a replica does.

A CDC consumer is a replica of your tables in a different shape: it loads a consistent snapshot, then applies the log from exactly the position that snapshot saw.

So the hard parts of CDC are the hard parts of a replica. The snapshot and the log position have to match, or rows go missing or move backwards. A replica applies each row's changes in the order they committed, and promises no order across rows. It copies your tables, so every consumer depends on your columns. And after a restart it applies some changes again, so applying a change twice has to do no harm.

What it feeds

Four kinds of consumer come up again and again.

Search indexes. An inverted index in Elasticsearch, kept in step with the rows it was built from. Worked example 1.

Analytics. Every change, deletes included, landing in a warehouse such as BigQuery or Snowflake. Worked example 2.

Caches. A delete for every cache key whose row changed, sent from the log instead of from the application. Worked example 4.

Migrations. A new data store fed from the old one's log while both are live. Dual-write migration covers the phases.

When you don't need it

You don't need CDC when the reader can query the source directly, such as a report that runs against a read replica. You don't need it to publish a business event that other teams build against: that's an outbox, though CDC can carry it, as worked example 3 shows.

How log-based capture works

What polling can't see

A poll asks the table for rows changed since its last run. The table holds only the latest version of each row, so the poll can only report what's there now. It misses four kinds of change.

  • Deletes. The row is gone, so no query finds it. A soft delete, a deleted_at column set instead of a DELETE, works around this, and leaves the dead rows in the table and in every index.
  • Intermediate states. An order that goes from placed to paid to refunded between two polls shows up once, as refunded. No consumer ever learns it was paid.
  • Writes that skip updated_at. A bulk fix in a migration script, or any UPDATE that forgets the column, is invisible.
  • Rows that commit late. Transaction A sets updated_at to 12:00:00.900 and transaction B sets 12:00:00.950, and B commits first. A poll between the two commits returns B and remembers .950 as the newest timestamp it has seen. Every later poll asks for rows newer than that, so A is never returned.
One row between two polls
Row 42 is inserted (1), updated twice and then deleted (2), all inside one minute. The poll at the end of the minute (3) finds no row 42 at all, so the consumer never hears about it, in red. The log holds all four changes in commit order, in green, and the delete arrives as an event with the old key.Row 42 is inserted (1), updated twice and then deleted (2), all inside one minute. The poll at the end of the minute (3) finds no row 42 at all, so the consumer never hears about it, in red. The log holds all four changes in commit order, in green, and the delete arrives as an event with the old key.
The poll sees the table; the log sees every change. Row 42 is inserted (1), updated twice and then deleted (2), all inside one minute. The poll at the end of the minute (3) finds no row 42 at all, so the consumer never hears about it, in red. The log holds all four changes in commit order, in green, and the delete arrives as an event with the old key.

The log has none of these gaps. It holds every committed change in commit order, deletes included, whether or not the change touched updated_at.

Reading the Postgres log

Postgres turns its WAL into row changes through logical decoding. An output plugin formats each change, and the built-in one is pgoutput. Logical decoding needs wal_level set to logical, which takes a server restart and makes the WAL larger.

A connector reads through a replication slot, a named position in the WAL that Postgres keeps for one reader. The slot survives crashes, and Postgres keeps every byte of WAL the reader hasn't confirmed, even when nothing is connected. If the captured tables are quiet while other tables in the same database are busy, the connector confirms nothing and that WAL piles up, so Debezium's heartbeat confirms its position on a timer. The outbox pattern covers what a slot does to the disk, how to measure its lag, and the failover slots that Postgres 17 added.

Logical decoding hands out only committed transactions, in commit order, each one whole. A transaction that rolled back never appears.

Each event carries the new row. How much it carries of the old row depends on the table's replica identity, the setting that decides which old values Postgres writes to the WAL. By default, a delete carries the old primary key, and an update carries no old values unless a key column changed. REPLICA IDENTITY FULL gives the old values of every column, and writes more WAL on every update and delete. A consumer needs FULL when it acts on the old value of a column outside the key, such as a cache keyed by email that has to delete the old address.

Reading the MySQL log

MySQL writes each transaction to the binlog whole, just before it commits, so the binlog is in commit order. For CDC it has to be in row format, which records the changed rows rather than the SQL statements. Row format is the default, and MySQL plans to remove the others. Debezium also needs binlog_row_image set to full, so every update carries all the columns of the old and the new row.

The connector keeps its own place in the binlog: a file name and an offset. That pair means nothing on another server, so on its own it can't follow a failover. With GTIDs turned on, every transaction also gets a global transaction identifier (GTID): the id of the server where it committed, plus a sequence number. A reader that moves to another server sends the set of GTIDs it has seen, and the server sends the rest.

MySQL deletes binlog files older than 30 days by default. A connector stopped for longer than that finds its position gone, and has to start again from a new snapshot. Postgres fails the other way: the slot keeps the WAL, and the primary's disk fills instead.

Back of envelopeHow long can the connector be down?
The question is how much binlog MySQL has to keep, and
what it costs to keep less. A MySQL database commits
2,000 row changes a second, mostly updates to 500 B rows.
With binlog_row_image=full an update logs the old and the
new row.

Binlog written
  per change      500 B old + 500 B new      ≈  1 KB
  per second      2,000 × 1 KB               =  2 MB
  per day         2 MB × 86,400              ≈  173 GB
  30 days, the default expiry                ≈  5.2 TB

Expiry cut to 3 days                         ≈  520 GB
  a connector stops Friday 18:00 and nobody
  notices until Monday 09:00                 =  63 h
  margin left     72 h − 63 h                =  9 h

Each day of expiry costs 173 GB of disk on the primary,
and buys a day in which a stopped connector can still
resume. Set the expiry from how long it takes you to
notice a stopped connector, and alarm well inside it.

A change event

Here is one update to an order, as Debezium publishes it. This table has REPLICA IDENTITY FULL; with the default, before would be null, because no key column changed.

key:   { "id": 42 }
value: {
  "before": { "id": 42, "status": "placed", "total_cents": 4200 },
  "after":  { "id": 42, "status": "paid",   "total_cents": 4200 },
  "source": { "db": "shop", "table": "orders", "txId": 5521, "lsn": 23452384 },
  "op": "u"
}

Three details to note.

The key is the row's primary key. Kafka sends every event with the same key to the same partition, so one row's events stay in order. A table with no primary key gets a null key, and its events lose that order.

op is c, u or d for a create, an update or a delete, and r for a row read by a snapshot. A delete has a null after. Debezium follows each delete with a tombstone, an event with the same key and a null value. Kafka's compaction, covered in message queues vs event streams, uses it to drop the key.

source carries the change's position in the log. In Postgres that's the LSN, the log sequence number, a byte position in the WAL. In MySQL it's the binlog file and offset, and the GTID. A consumer compares positions to tell an older change to a row from a newer one. That works for Postgres's LSN, and for MySQL positions from one server. Across a MySQL failover, neither a file and offset nor a GTID set puts changes in order.

Snapshot, then stream

The log doesn't go back to the beginning. So a new consumer first needs the current rows, and then every change after them. The two have to meet at one position in the log, and there are two ways to miss it.

A gap. You copy the table, then start the stream from the current position. A row changed while the copy ran is in neither, and nothing reports it.

An overlap applied blindly. You start the stream first, then copy the table, and apply both as they arrive. An event from before the copy can land after the copy's newer version of the row, and set the row back until a later event fixes it. Netflix's DBLog paper calls this time travel, and names LinkedIn's Databus as a system where it can happen, while a consumer catches up after loading its starting copy.

Where the copy meets the stream
In the top row, the copy runs first and the stream starts at its end (1), so a change committed during the copy is in neither, in red. In the middle row, the stream starts before the copy (2), and an older event for row 7 lands after the copy's newer version, so row 7 goes back until a later event fixes it. In the bottom row, the copy is read at position P and the stream starts at P (3), so every change appears exactly once, in green.In the top row, the copy runs first and the stream starts at its end (1), so a change committed during the copy is in neither, in red. In the middle row, the stream starts before the copy (2), and an older event for row 7 lands after the copy's newer version, so row 7 goes back until a later event fixes it. In the bottom row, the copy is read at position P and the stream starts at P (3), so every change appears exactly once, in green.
The copy has to be read at the position the stream starts from. In the top row, the copy runs first and the stream starts at its end (1), so a change committed during the copy is in neither, in red. In the middle row, the stream starts before the copy (2), and an older event for row 7 lands after the copy's newer version, so row 7 goes back until a later event fixes it. In the bottom row, the copy is read at position P and the stream starts at P (3), so every change appears exactly once, in green.

The fix is to read the copy at exactly the position the stream starts from. Debezium's snapshot does this on both databases. It reads the tables inside one transaction, notes the log position that transaction matches, and streams from that position.

Postgres has this built in. When you create a replication slot, Postgres can export a snapshot: the state of the database at the exact point where the slot's stream begins. Read the copy in that snapshot, then apply the slot's changes, and nothing is missed.

MySQL has no such hook, so Debezium makes one. It takes a global read lock, starts a repeatable-read transaction, and reads the binlog position and the table definitions. Then it releases the lock and reads every table inside that transaction. Writes wait only while the position and the definitions are read. Where a global read lock isn't allowed, as on Amazon RDS and Aurora, Debezium locks each table instead, and writes to each table wait until its copy is read.

The cost is that the copy is one long read transaction, and the stream waits for it to finish. Shopify found that its snapshots took hours on large tables and blocked binlog events while they ran, and that some tables were too big to snapshot in a reasonable time. A snapshot interrupted part way starts again from the first row. Worked example 2 prices this for a 2 TB table.

Incremental snapshots

Netflix's DBLog removes the long transaction. It copies a table in chunks while the stream keeps running, and takes no locks. It marks a window in the log around each chunk's query, so it can tell which of the chunk's rows changed while the chunk was read.

For each chunk, it takes five steps.

  1. Pause reading the log, and write a low watermark: an update to a row in a small watermark table, so the update shows up in the log.
  2. Select the next chunk by primary key, such as the next 1,024 rows after the last key copied, and hold it in memory.
  3. Write a high watermark the same way, and resume reading the log.
  4. Pass log events through as usual. Between the two watermarks, any event for a key in the chunk removes that key from the chunk.
  5. At the high watermark, emit what's left of the chunk, then carry on.

The select ran between the two watermarks, so it saw every change committed before the low one. A change committed inside the window may or may not be in the chunk's copy, so the chunk drops that row. The log event, which is at least as new, takes its place. Every change after the high watermark is emitted after the chunk. No row ever goes backwards.

One chunk between two watermarks
The connector writes the low watermark L (1), selects rows k1 to k6 (2), and writes the high watermark H (3). Between L and H the log changes k1 and k3, so those two copies are dropped from the chunk, in grey, and their log events go out instead. At H, the rest of the chunk, k2, k4, k5 and k6, goes out (4), in green, before any event after H.The connector writes the low watermark L (1), selects rows k1 to k6 (2), and writes the high watermark H (3). Between L and H the log changes k1 and k3, so those two copies are dropped from the chunk, in grey, and their log events go out instead. At H, the rest of the chunk, k2, k4, k5 and k6, goes out (4), in green, before any event after H.
A row the log changed inside the window is dropped from the chunk. The connector writes the low watermark L (1), selects rows k1 to k6 (2), and writes the high watermark H (3). Between L and H the log changes k1 and k3, so those two copies are dropped from the chunk, in grey, and their log events go out instead. At H, the rest of the chunk, k2, k4, k5 and k6, goes out (4), in green, before any event after H.

Debezium implements this as incremental snapshots, started with a signal, and it stores the last key copied so a restart carries on from the next chunk.

The consumer pays for this. It can see a read event followed by an update for one row, or only the update, or a delete for a row it never saw. A read gives the row's state at some point, not its first state. The consumer has the whole table only when the last chunk lands. And the table needs a primary key, because each chunk is a range of it.

The same move works on part of a table. DBLog can select one table or a list of primary keys, so when a consumer's copy of some rows is wrong, you send those rows through the stream again.

Ordering and keys

Kafka keeps order within a partition, and Debezium keys every event by the row's primary key. So one row's changes reach a consumer in the order they committed, and nothing else is ordered. Two rows of one table can arrive in either order, and so can two tables.

A per-row replica needs no more than that, because each row ends in its latest state. A consumer that needs a whole transaction at once doesn't get it. One transaction that inserts an order and its three lines becomes four events on two topics, and a consumer of order_lines can see a line whose order hasn't arrived yet.

There are three ways to handle it.

Make each row stand alone. The consumer accepts a line before its order, for example by indexing the line and filling in the order's fields when the order arrives.

Reassemble the transaction. Debezium can emit a BEGIN and an END event for each transaction, with a count of events per table, so a consumer can hold events back until it has them all. That's a buffer across topics that you run and size.

Publish the whole order as one event. An outbox row written in the same transaction carries the order and its lines together. Worked example 3 does this.

A change to a primary key arrives as two events. Debezium sends a delete for the old key and a create for the new one. The two keys can sit in different partitions, so a consumer can see them in either order.

Schema changes

Columns change while the stream runs. Postgres's logical decoding doesn't carry data definition language (DDL) statements, such as ALTER TABLE, so a consumer finds a new column only when an event arrives with it. MySQL's binlog carries the DDL. Debezium records each statement with its binlog position in a schema history topic, so it can read every row event with the columns the table had at that point.

Shopify keeps an Avro schema per table in Confluent Schema Registry, which checks each new version of a schema against the last one. The registry's default rule is backward compatibility: consumers on the new schema can read events written with the old one. Adding an optional column passes, and so does removing a column. Consumers have to upgrade before the new events appear.

Shopify's example of a breaking change is an integer column changed to a string, which forces every consumer to update at once. A rename of a nullable column passes the check, because it looks like one column removed and an optional one added. It still breaks every consumer that reads the old name.

So a table read through CDC changes by expand and contract: add the new column, write both, move every consumer over, then drop the old one. A rename becomes a migration with a step that waits for every consuming team.

This is the cost that message queues vs event streams gives for CDC: consumers depend on your columns. For your own pipelines, such as the search index and the warehouse, one team pays it. For other teams it's a contract nobody agreed to, and worked example 3 replaces it.

Delivery, and consumers that can take a repeat

A CDC pipeline delivers every change at least once, and some twice. Repeats come from two places.

  • The connector. Kafka Connect saves a connector's position every 60 seconds by default. A connector that crashes resends everything after the last save, and Debezium's FAQ says those repeats are always visible to consumers.
  • The consumer. A consumer that crashes after applying a batch, and before saving its own offset, applies the batch again.

Debezium can join Kafka Connect's exactly-once delivery, but its own documentation says it's unclear whether that implementation is fully correct, and the guarantee ends at Kafka anyway.

Back of envelopeWhat one connector crash resends
The question is what a single crash costs a consumer.
The orders database commits 2,000 row changes a second,
500 of them new orders. Kafka Connect saves the
connector's position every 60 s.

Resent after one crash, at most
  changes        2,000 × 60 s               =  120,000
  new orders       500 × 60 s               =   30,000

A consumer that upserts each row's after image by key
  after the replay               →  the same rows as before
  during it, a row changed twice in that minute shows
  its older state until the newer event replays

A consumer that adds each new order's total to a daily sum
  each resent insert is added again    →  up to 30,000
                                          orders counted twice

The upserting consumer ends right, and can step back for
a moment on the way. The running total stays wrong.

The fix follows from the thesis: a replica applies state, not differences. Each event's after is the row's whole state. On Postgres there's one exception: an unchanged large value stored out of line, in what Postgres calls TOAST, arrives as a placeholder unless the table has REPLICA IDENTITY FULL. An upsert, an insert that overwrites the row if its key already exists, ends in the same row however many times the events replay. A delete by key deletes nothing the second time.

A consumer that adds up values from events is applying differences, so it has to remember which events it has applied. It keeps an inbox, a table of the log positions it has applied, and writes to it in the same transaction as the sum.

An older event can land after a newer one in two more ways: a second indexer replaying an old range, and a rebuild writing copied rows into the target while the stream runs. The fix is a version check: store each row's version with it, and skip any event with a lower one. The version has to follow commit order. In MySQL, a binlog position on one server already does, because the binlog is written at commit. In Postgres, a change's LSN marks where the change was written, which can be well before its transaction commits. Worked example 1 shows where that breaks and what to use instead.

The method

1. Decide what each consumer reads. A pipeline your team owns reads the tables through CDC. An event other teams build against goes through an outbox, which the same connector can carry.

2. Prepare the log. On Postgres, set wal_level to logical, give each connector its own slot, and use failover slots. On MySQL, use row format, the full row image and GTIDs, and a binlog expiry longer than a stopped connector could go unnoticed.

3. Give every table in the publication a primary key. Debezium's default publication covers the whole database, and filtered limits it to the captured tables. The key is also the event key, the ordering scope, and the range an incremental snapshot walks.

4. Plan the copy. A blocking snapshot is fine for a small table. Use an incremental snapshot for a large table, for a table added later, and for repairs.

5. Make every consumer idempotent. Upsert the after image by key, delete by key, and check a version in commit order before writing.

6. Watch the lag in time, and the log's headroom. Alarm on how far behind the consumer is in seconds, on the WAL a slot is keeping, and on how close the connector is to binlog expiry.

Worked examples, start to finish

Each one starts from the obvious design, and each obvious design fails in a different way.

A search index that polling keeps wrong

A marketplace keeps 20 million listings in Postgres and searches them through Elasticsearch. Sellers edit listings 300 times a second and delete 20,000 a day. The first version polls updated_at every minute, and a nightly job rebuilds the whole index to clear out deleted listings.

Back of envelopeWhat the poll leaves wrong in the index
The question is how many deleted listings stay
searchable, and what the nightly rebuild costs to fix
them. Deletes reach the index only through the rebuild.

Deleted listings still searchable
  deletes per hour      20,000 / 24            ≈    833
  each waits for the rebuild: 12 h on average,
  24 h at most
  searchable at once    833 × 12               ≈ 10,000

The nightly rebuild
  documents rewritten                          =    20M
  per deleted listing   20M / 20,000           =  1,000

About 10,000 deleted listings are searchable at any
moment, and the rebuild rewrites 1,000 documents for
each one it removes.

So how should changes reach the index, so that a delete arrives in seconds and nothing can set a listing back?

Naive

Poll updated_at every minute, and rebuild the index every night

It's one query and one loop, and it needs nothing new to run. Edits arrive within a minute, which looks good enough.

The worksheet breaks it. Deletes wait up to a day, so about 10,000 deleted listings are searchable at any moment, and the poll still has the other three gaps above.

Senior

Debezium into Kafka, and an indexer that upserts by id

Debezium reads the WAL into a Kafka topic for listings, keyed by listing id. An indexer writes each event's after into Elasticsearch as the document with that id, and deletes the document when op is d. Every change arrives, deletes included, within the pipeline's lag. Shopify measured that lag at under 10 seconds at p99, from a MySQL insert to the event in Kafka.

This is what most teams build, and it works. The cost is that the index is right only while each listing's events are applied in order. A crash replay sets listings back for a moment. A second indexer replaying an old range, or a bulk reindex written into the live index, can leave an older version over a newer one.

Staff

Version every write in commit order

Stop depending on the order. Write each document with Elasticsearch's external versioning, which accepts a write only when its version is higher than the stored one and rejects the rest with a conflict. The version has to follow commit order, and a change's own LSN doesn't.

A snapshot row shows why. A transaction changes listing 9 at LSN 90, stays open while a chunk is read between LSN 100 and 110, and commits at 120. The chunk copies listing 9's old state. Stamped 110, that copy refuses the real change, stamped 90, and the listing stays stale until it changes again.

So version by commit order. Debezium's Postgres events carry source.sequence, whose first value is the last committed LSN. Every event of one transaction shares it, and it grows from one transaction to the next. Use it as the version with version_type=external_gte, which also accepts an equal version, so several changes inside one transaction still apply. Give a snapshot row the last committed LSN at its high watermark, and the commit at 120 sorts after the chunk.

An old event arriving late
The document for listing 9 holds version 500, from the newest change (1). A replay delivers an older change, version 300, afterwards (2). Without a version, the old price overwrites the new one, in red. With external versioning, Elasticsearch compares 300 with 500 and refuses the write (3), in green.The document for listing 9 holds version 500, from the newest change (1). A replay delivers an older change, version 300, afterwards (2). Without a version, the old price overwrites the new one, in red. With external versioning, Elasticsearch compares 300 with 500 and refuses the write (3), in green.
With a version in commit order, the late event is refused. The document for listing 9 holds version 500, from the newest change (1). A replay delivers an older change, version 300, afterwards (2). Without a version, the old price overwrites the new one, in red. With external versioning, Elasticsearch compares 300 with 500 and refuses the write (3), in green.

Now a re-snapshot through the connector can run straight into the live index, and two indexers can replay the same range without harm. A bulk reindex written straight into the index has no commit position for its rows, so run rebuilds as incremental snapshots instead.

The cost is in deletes. Elasticsearch keeps a deleted document's version for only 60 seconds by default, the index.gc_deletes setting. An older event that arrives after that recreates the listing. So the indexer doesn't delete a document. It marks it hidden, and the search query filters hidden documents out. A daily sweep hard-deletes only documents hidden for longer than the Kafka topic keeps events, because a replay can't reach back past that. That's one more filter on every query, and a few days of hidden documents, about 20,000 a day against 20 million live ones.

Loading a 2 TB table into the warehouse

An analytics team wants the orders table in BigQuery, kept current. The table is 2 TB, about 2 billion rows of 1 KB, on a Postgres primary that commits 2,000 row changes a second and writes 10 MB of WAL a second. Debezium's default is a single consistent snapshot, then the stream.

Back of envelopeWhat one snapshot transaction holds on the primary
The question is what a consistent snapshot of orders
costs the primary while it runs. The copy is throttled
to 50 MB/s so live queries keep their disk. Half the
2,000 changes a second are updates.

Duration
  2 TB / 50 MB/s                         = 40,000 s ≈ 11 h

While it runs
  WAL the slot keeps    10 MB/s × 40,000 s        = 400 GB
  old row versions vacuum can't remove,
  because the snapshot could still read them
                        1,000/s × 40,000 s        =  40M
  changes waiting       2,000/s × 40,000 s        =  80M,
                        the oldest 11 h late
  a failure in hour 10 starts again at row 1

The same copy as an incremental snapshot
  chunks                2B / 1,024 rows           ≈   2M
  watermark writes      2 per chunk               ≈   4M
                        4M / 40,000 s             ≈  100/s
  the stream keeps running, so the slot and vacuum
  stay put; the lag holds if the pipeline has
  50 MB/s spare

One transaction holds 400 GB of WAL and 40M old row
versions for 11 hours. The chunks cost about 100 extra
writes a second.

So how do you get 2 TB into the warehouse and start the stream, without a gap and without holding the primary for 11 hours?

Naive

Export the table, load it, then start the connector

Run COPY orders TO a file, load the file into BigQuery, and point Debezium at the current position. It's fast to explain, and every piece is familiar.

It leaves a gap. Every change committed after the export began, at least 11 hours of them at the same 50 MB/s, is in neither the file nor the stream. Those rows sit in the warehouse in their old state, deleted orders included, until the row changes again, and nothing reports it.

Senior

Debezium's initial snapshot, then the stream

The snapshot and the stream meet at one position, so nothing is missed and nothing goes backwards. This is the default, and for most tables it's the right answer.

At 2 TB, the worksheet prices it: 400 GB of WAL kept on the primary, 40 million row versions vacuum can't clear, consumers 11 hours behind, and a restart from row 1 if anything fails. The next tier asks whether the copy needs to be one transaction at all.

Staff

Start the stream, then copy the table in chunks

A replica doesn't need a copy of the table at one instant. It needs every row to end in its latest state, and DBLog's watermarks give that one chunk at a time. So start the stream now, and send a signal that starts an incremental snapshot of orders.

The worksheet gives the cost on the primary: about 2 million chunk queries, each a short transaction, and about 100 watermark writes a second. The slot and vacuum stay normal, the lag holds if the pipeline has 50 MB/s to spare, and a crash resumes from the last chunk. DBLog has run this way at Netflix since 2018, and the paper puts it in about 30 production services. Shopify planned the same move for its tables that were too big to snapshot.

What you give up: the warehouse sees reads, updates and deletes mixed together, including deletes for rows it hasn't loaded yet. Its merge has to treat every event as "this row's state now", and a delete for an unknown row as nothing to do. And the table is complete only after the last chunk, about 11 hours in, so anyone who queries it earlier sees part of it.

Order events for other teams

The orders table already streams into the warehouse. Six other teams, among them fulfilment, fraud and email, now want to react when an order changes. The raw topics exist, so the obvious move is to let them subscribe.

The question is what those teams should read, so that the orders team can still change its own tables.

Naive

Let them read the raw table topics

No new code, and the events are already flowing.

Every column is now an interface with six clients. Renaming total_cents breaks six services. An internal column, such as a fraud score, is visible to all of them. The events say a row changed, so each team works out "order paid" from before.status and after.status (the table has FULL), six times, possibly six ways. And an order and its lines arrive on two topics, in either order.

Senior

A schema registry, and every change by expand and contract

Register each table's schema with a compatibility rule, and make every rename an expand-and-contract migration.

This is the disciplined version of the same design. The cost is that every rename is a migration in several steps, paced by six teams' deploys. And each consumer still turns row changes into business events itself.

Staff

Give them an outbox, carried by the same connector

Question whether other teams should read your tables at all. A replica of your tables suits a pipeline you own, and another team needs a contract instead.

In the transaction that marks the order paid, insert an OrderPaid row into an outbox table, with a payload written for those teams. The same Debezium connector sends it, through its outbox event router.

The tables can now change freely. The payload is the contract, and you version it on purpose. It can carry the order and its lines together, so the transaction arrives as one event.

A rename, with and without an outbox
In the top half, three of the six teams read the raw orders topic, so renaming total_cents to amount_cents (1) breaks all three, in red. In the bottom half, one transaction writes the orders row and an OrderPaid row to the outbox (2), and the same Debezium connector sends the outbox row to the teams (3). The rename changes the table and not the payload, so nobody breaks, in green.In the top half, three of the six teams read the raw orders topic, so renaming total_cents to amount_cents (1) breaks all three, in red. In the bottom half, one transaction writes the orders row and an OrderPaid row to the outbox (2), and the same Debezium connector sends the outbox row to the teams (3). The rename changes the table and not the payload, so nobody breaks, in green.
The outbox moves the contract out of the table. In the top half, three of the six teams read the raw orders topic, so renaming total_cents to amount_cents (1) breaks all three, in red. In the bottom half, one transaction writes the orders row and an OrderPaid row to the outbox (2), and the same Debezium connector sends the outbox row to the teams (3). The rename changes the table and not the payload, so nobody breaks, in green.

Keep the raw table topics for pipelines you own, the search index and the warehouse, where a rename is one team's change.

What you give up: someone writes each event on purpose, and code that forgets to write one publishes nothing. Every business event is also one more insert in the order's transaction. Message queues vs event streams draws the same line: CDC for your own pipelines and analytics, an outbox for a published contract.

Invalidating a cache across regions

A MySQL primary sits in one region, with read replicas in two others and a memcached cluster in each region. On every write, the application commits and then deletes the affected keys in every region: delete on write, from caching strategies and invalidation. In the other regions, the delete can arrive before the change does.

Back of envelopeA delete that arrives before the data
The question is how often an application-side delete
leaves the old value cached in a replica region. A hot
key there is read 2,000 times a second, and the region's
replica is 500 ms behind the primary. The delete reaches
the region right after the commit.

  next read after the delete    1 / 2,000 s     = 0.5 ms
  that read misses, and refills from the replica,
  which is still 500 ms behind
  reads before the replica catches up
                                2,000 × 0.5 s   =  1,000

The first of those reads puts the old value back, and
it stays until the next write or the TTL. Every write to
this key leaves the old value cached in that region.
Deleting sooner doesn't help, because the refill reads a
database that hasn't changed yet.

Facebook described this race in its memcache paper, and the fix it built. On every database, a daemon called mcsqueal reads the statements the database commits, pulls out the cache keys the application attached to them, and sends deletes to that region's caches. In a replica region, the daemon runs beside the replica database and reads its log, so a delete goes out only after that replica has the change. The deletes come from a log the database keeps, so a lost or misrouted one can be replayed.

Who sends the delete in a replica region
In the top half, the web server deletes the key in the replica region right after the commit (1). A reader misses and refills from the replica (2), which is still behind, so the old value goes back into the cache, in red. In the bottom half, the replica applies the change (3), and a daemon reading the replica's log sends the delete after it (4), so the next refill reads the new value, in green.In the top half, the web server deletes the key in the replica region right after the commit (1). A reader misses and refills from the replica (2), which is still behind, so the old value goes back into the cache, in red. In the bottom half, the replica applies the change (3), and a daemon reading the replica's log sends the delete after it (4), so the next refill reads the new value, in green.
Sent from the replica's own log, the delete arrives after the data. In the top half, the web server deletes the key in the replica region right after the commit (1). A reader misses and refills from the replica (2), which is still behind, so the old value goes back into the cache, in red. In the bottom half, the replica applies the change (3), and a daemon reading the replica's log sends the delete after it (4), so the next refill reads the new value, in green.

The web server still deletes the key in its own cluster straight after the write. In the primary region, that lets the writer read its own change. A writer in a replica region needs more. Facebook sets a remote marker for the key first, and a later miss that finds the marker reads from the primary instead of the lagging replica. A version bump sent by the application has the same race as the delete, because the refill under the new key still reads the lagging replica. Facebook measured that between replica regions, 99.9 percent of deletes took effect within a second and 99.99 percent within 10 minutes. The most common reason a delete was still missing after a few seconds was a failed first attempt, which a retry fixed.

A Debezium consumer can do the same job without changing the SQL, with one connector per region reading that region's replica. The replica's binlog includes the replicated changes when log_replica_updates is on, which is its default. The consumer can only build keys it can work out from one row, such as user:{id}. A cached view built from many rows needs keys the application names, which is why mcsqueal reads them from the SQL. And with binlog_row_image=full, the event already carries old values, such as the old email of a cache keyed by email.

Where it goes wrong

The first three come up most.

1. Polling updated_at and calling it CDC

A poll sees only the rows still in the table, so it misses the four kinds of change listed under polling above. Read the log.

2. Starting the stream after the copy

A copy taken before the stream starts leaves a gap: every change committed while the copy ran is lost, without an error. Read the copy at the stream's starting position, or interleave chunks with the stream between watermarks.

3. Counting on exactly-once

A Debezium pipeline repeats events after a crash, up to a minute of them with Kafka Connect's default. Apply row state by key, check a version in commit order, and give any consumer that adds things up an inbox keyed by log position.

4. Publishing raw table topics to other teams

Every column becomes an interface, and a rename breaks people you've never met. Give other teams an outbox, carried by the same connector.

5. Capturing a table with no primary key

The events get a null key, so one row's changes lose their order. On Postgres, once the table is in a publication, every update and delete on it fails on the primary.

6. Letting the log run out

A stopped MySQL connector loses its position when the binlog expires. A stopped Postgres connector keeps WAL on the primary until the disk fills. Alarm on the connector's lag in time, long before either.

7. Expecting transaction order across tables

Each table has its own topic, and nothing orders one topic against another. Use one of the three fixes under ordering.

If you memorise nothing else

factwhy it matters
A poll on updated_at can't see a deleteread the log instead
CDC reads the WAL in Postgres and the binlog in MySQLevery committed change, in commit order
A replication slot keeps WAL until its reader confirms ita stopped connector fills the primary's disk
MySQL deletes binlog files after 30 days by defaulta connector stopped longer needs a new snapshot
Events are keyed by primary keyone row is in order; rows and tables are not
By default a delete carries the old key and an update no old valuesa consumer that needs old values needs FULL
The copy must be read at the stream's starting positionotherwise a gap, or rows that go backwards
A single snapshot of 2 TB at 50 MB/s is an 11-hour transactionthe slot and vacuum both wait for it
Incremental snapshots copy chunks between two watermarksno locks, resumable, about 2 writes per chunk
Delivery is at least onceone connector crash resends up to 60 s of changes
Apply the after image by keya replay ends in the same rows
Guard writes with a version in commit ordera change's own LSN isn't, so a late commit can lose to a snapshot row
Raw table topics make your columns an interfaceother teams get an outbox through the same connector

What is expected at each level

Mid-level

Know that CDC reads the database's log, the WAL or the binlog, and why that beats polling: a poll can't see deletes. Know what an event holds, the row before and after, keyed by primary key, and that delivery is at least once.

You aren't expected to raise the snapshot handoff or schema coupling without being asked. If the interviewer asks "how does the index get the existing rows?", a good mid-level answer is "a snapshot first, then the stream, and the two have to start at the same point."

Senior

You lead this part of the discussion, and three things must come up without prompting.

Deletes, through the log. Say what reads the log, a connector through a replication slot or from the binlog, and what that costs: a slot to watch, or a binlog expiry to stay inside.

The copy and the stream at one position. Say how the existing rows get there and how the stream starts without a gap. Name the long transaction as the cost for a big table.

Consumers that survive a repeat. Apply row state by key. Name any consumer that adds things up and give it an inbox.

Two things are disqualifying: polling updated_at to feed a data store that must reflect deletes, and claiming exactly-once delivery end to end.

Staff+

Producing a correct design is still the bar. A staff answer stands out by deciding who depends on what.

Copy big tables in chunks. Start the stream, then run an incremental snapshot, and say what the consumer must accept: reads mixed with updates, and deletes for rows it hasn't seen.

Make the order of writes not matter. Version each write in commit order, so replays, re-snapshots and parallel consumers are safe, and run rebuilds through the connector. Know where it leaks: a change's own LSN isn't in commit order, and Elasticsearch forgets a delete's version after 60 seconds.

Separate pipelines from contracts. Raw table topics for pipelines you own, an outbox for everyone else, both through one connector.

Invalidate from the log that the readers read. In a replica region, the delete has to come after the replica has the change.

And say what you would not build. Each of these can cost a team a quarter.

One is a homegrown connector, when Debezium reads both databases and Shopify chose it over writing its own. Another is a nightly full reindex to clear out deleted documents, when deletes arrive through the log in seconds. A third is exactly-once machinery for a consumer that could upsert by key.

Another is a schema review process so other teams can read raw tables, when an outbox would have given them a contract. And the last is a buffer that reassembles every transaction across topics, for consumers that only ever needed each row's latest state.

Sources

The product behaviour below comes from each project's own documentation, and the company figures from the papers and posts that published them. The sizing arithmetic is worked out in the article from stated inputs.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.