To keep an analytics copy of a production table, the naive approach is to copy the whole table every night. It is slow, it loads the source and it misses everything that happened in between. Change data capture (CDC) copies only what changed.
How databases record changes
Databases already write every change to a log before applying it: the write-ahead log in PostgreSQL, the binary log in MySQL. CDC tools read that log and turn it into a stream of events: this row was inserted, that row was updated from X to Y, this one was deleted.
Approaches
- Log-based CDC reads the database log. It captures every change, including deletes, with little load on the source tables.
- Query-based (polling) selects rows where
updated_atis newer than the last run. It is simple, but it misses hard deletes and any update that forgets to touchupdated_at. - Triggers write changes into an audit table. They work anywhere, but they add work to every write.
-- Query-based polling: easy, but blind to deletes.
SELECT * FROM orders WHERE updated_at > TIMESTAMPTZ '2026-01-15 00:00:00+00';What an event contains
A typical change event has the operation (insert, update, delete), the primary key, the values before and after, a timestamp and the position in the log. The position lets a consumer resume exactly where it stopped.
Applying changes downstream
Events are applied to the target in order. Updates become upserts by primary key, and deletes either remove the row or mark it as deleted. Because delivery can repeat, applying a change must be idempotent.
Pitfalls
- Schema changes in the source must be handled, or the consumer breaks.
- Initial snapshot: you need a consistent starting copy before the stream begins.
- Ordering: events for one key must be applied in order.
- Large transactions and long-running consumers can make the database keep log segments for a long time and fill the disk.
- Sensitive columns are copied too, unless you exclude or mask them.
Takeaway
Use log-based CDC when you need low latency, complete history and deletes. Use simple incremental queries when the table is small, has a reliable updated_at and deletes are rare.
Comments