← Building blocks

React to database changes

Decoupling & async worksenior

Other systems (search, cache, analytics) must stay in sync with the database without the app publishing for each one.

Say it like this

The search index and the cache must follow the database without every service remembering to publish, so I tail the write-ahead log with change data capture and emit each committed row change as an event.

Basic solution

Tail the database’s change log and emit each row change as an event (change data capture).

DebeziumDynamoDB StreamsPostgres logical replication

Tail the log, fan out the changes

The application only writes to Postgres. Debezium reads committed changes from the WAL and publishes them per table; each downstream system applies them in its own shape and tracks its own offset.

How it works

  1. The database already writes every committed change to its own log before anything else happens: the write-ahead log in Postgres, the binlog in MySQL, Streams in DynamoDB. CDC reuses that log rather than asking the application to publish anything.
  2. A connector (Debezium, for example) opens a replication slot on the database, which is a bookmark the database keeps so it will not delete log entries the connector has not read yet. The connector reads changes in commit order, each one carrying the table name, the operation (insert, update or delete), the row before and after the change, and the log position.
  3. The connector publishes each change to a topic, usually one topic per table, partitioned by the row's primary key so all changes to one row stay in order.
  4. Consumers such as the search indexer, the cache invalidator and the analytics loader read the topic and apply each change in their own shape: the indexer upserts a document, the invalidator deletes a cache key, the loader appends a row.
  5. The connector periodically records the log position it has reached. After a restart it resumes from that position, which can mean re-reading a few changes it had already published, so consumers must be idempotent.

How it differs from the outbox

  • The outbox publishes events the application chose to write, in a public shape it controls. CDC publishes what the tables did, in table shape. Teams often combine them: CDC is the transport that reads the outbox table, and the outbox row is the contract.

Worked example

Keeping the news feed's search index and caches in sync

  • Posts table: 1,200 inserts/s average, 5K/s peak, plus edits and deletes. Users table: ~100 writes/s.
  • Without CDC: the post service must call the indexer, invalidate the post cache and notify analytics on every write, three network calls that can each fail independently. Any missed call is a stale index entry.
  • With CDC: Debezium reads the WAL with ~10 ms added latency and publishes to posts-changes (5K events/s × 600 B ≈ 3 MB/s). Three consumers subscribe; the post service makes zero extra calls.
  • Replication slot retention: if the indexer is down for an hour, the WAL keeps ~5K × 3,600 × 600 B ≈ 11 GB until it catches up. Alert on slot lag so disk does not fill.
  • Reindex: a new consumer replays from the earliest retained offset or runs a snapshot first; Debezium's initial snapshot of 2B posts is the slow part, hours, so plan it.

Variants and when each wins

Log-based CDC (Debezium, DynamoDB Streams, logical replication)

  • The connector reads the database's own log. It wins on latency and because it adds no load to the tables and sees deletes; it needs replication enabled on the database and a connector to operate.

Query-based CDC (polling updated_at)

  • A job periodically selects rows where updated_at is later than the last run. It wins when you cannot touch database configuration; it misses deletes entirely, needs an index on the timestamp, and adds polling load and latency.

Trigger-based

  • Database triggers copy each change into a change table that a job then reads. It wins on databases too old for logical replication; triggers slow every write and are easy to forget when the schema changes.

Application-level outbox

  • The application writes an event row in the same transaction as the data and a relay publishes it. It wins when consumers should receive intent (OrderPlaced) rather than row diffs; pair it with CDC as the relay for the best of both.

Log-based CDC is the default; use the outbox on top when consumers should get domain events rather than table rows.

Failure modes

Schema change breaks consumers

  • The search indexer crashes when a column is renamed. It happens because consumers are coupled to the table's shape, so a change to the table is a change to their input. Put a schema registry with compatibility checks in front of the topic, or publish through an outbox table that acts as the stable contract.

Replication slot fills the disk

  • The primary database runs out of disk and stops accepting writes. It happens because the connector or a consumer stopped, so the replication slot kept pinning log entries the database would otherwise have deleted, and the log grew until the disk was full. Alert on slot lag in bytes, set a maximum slot size, and never leave a slot without an owner.

Out-of-order application

  • A delete is applied before the insert and the deleted row reappears in the index. It happens because the topic was partitioned by something other than the primary key, or parallel consumers processed one row's changes concurrently. Partition by primary key and apply each key's changes serially.

Initial snapshot never finishes

  • A new consumer is days behind and not catching up. It happens because it tried to read billions of existing rows through the connector before reaching the live stream. Bulk-load from a database snapshot instead, note the log position of that snapshot, and start CDC from there.

Duplicate events after restart

  • The cache is invalidated twice and an analytics count is off by one. It happens because the connector resumed from its last recorded position and republished the changes after it. Dedupe on the log position in consumers, or make the apply idempotent; at-least-once is the contract.

Interviewer follow-ups

Answer out loud before you open each one.

When would you use CDC instead of the outbox pattern?

When many consumers need to follow the tables as they are and the application should not know about them: search, cache, analytics, replicas. The outbox is better when consumers need a stable domain event and you want to control what is published; CDC can be the relay for the outbox table.

How do consumers deal with seeing the same change twice?

Every change carries its log position, which is monotonic. A consumer stores the last position it applied per partition and skips anything older, or makes the apply idempotent such as upserting the search document rather than appending.

What does a schema migration do to a CDC pipeline?

Adding a nullable column is safe; renaming or dropping one breaks every consumer reading that field. Use a schema registry with backward-compatibility checks, roll out expand-then-contract, and give consumers a deprecation window.

What is the cost on the primary database?

Almost nothing for reads, since the connector reads the log, not the tables. The real cost is WAL retention: a lagging consumer pins the log and can fill the disk, so slot lag needs an alert and a cap.

Connections

In study paths
Decoupling with events
Built on
Write-ahead log
Pairs with
Publish events reliably with the write · Keep events as a replayable log · Full-text and fuzzy search · Invalidate the cache when data changes · Move data between systems · Make retries safe
Pulls against
Change the schema without downtime

The same parts on other clouds

The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.

AWSUsed here asGoogle CloudMicrosoft AzureOpen source and others
Amazon EC2 Auto ScalingPost service, Debezium, Search indexer, Cache invalidator, Analytics loaderCompute Engine managed instance groupsVirtual Machine Scale SetsKubernetes Deployment with a HorizontalPodAutoscaler, Nomad
Amazon AuroraPostgresAlloyDB for PostgreSQL, Cloud SQLAzure Database for PostgreSQL or MySQLPostgreSQL, MySQL, CockroachDB
Amazon MSK (Kafka)Topic: posts-changesManaged Service for Apache KafkaEvent Hubs (Kafka API)Confluent Cloud, Redpanda