AlgoViz

Change data capture

medium 28 min

Change data capture (CDC) turns every insert, update and delete in a database into an ordered stream of events that other systems follow: search indexes, caches, warehouses and services.

See it run

One committed change, followed by many systems: the pipeline, its traps and how a consumer stays correct.

Operations

The pipeline

An insert, an update and a delete travel from the database to the search index.

Step 1 of 6

Insert

commitlogAppPostgreSQLusers: 1Connectorposition 0Kafka topicemptySearch indexempty

Committed

The app commits user 1. Its work is finished.

Step 1: Insert

db.commit(change)                      # the app is done hereevent = connector.read_next(log)       # capturetopic.publish(key=event.key, event)    # deliverfor event in topic.after(offset):      # consume    index.apply(event)    offset += 1
Delay
Usually seconds
Handle
Duplicates

The application never talks to Kafka or to search. That is the point.

In the real world

The same change data capture doing real jobs. Pick one and step through it.

A stopped connector endangers the database, not only the index.

Step 1 of 3

Friday

commitlogAppPostgreSQLdisk 40%ConnectorstoppedKafka topicno new eventsSearch indexold

Silent

The connector stops. The app works normally and nobody notices.

Step 1: Friday

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Writing to both systems

    critical

    There is no shared transaction. A crash or a race leaves two different answers.

    Wrong
    db.save(product)search.index(product)
    Right
    db.save(product)      # CDC does the rest
  • Assuming one delivery

    critical

    A restart repeats the last events. Counters drift and emails go out twice.

    Wrong
    stats["orders"] += 1
    Right
    if event.id not in processed:    stats["orders"] += 1    processed.add(event.id)   # same transaction
  • Crashing on a tombstone

    major

    After a delete comes a message without a value. Parsing it fails and blocks the partition.

    Wrong
    event = json.loads(message.value)
    Right
    if message.value is None:    return                # tombstoneevent = json.loads(message.value)
  • Bookmark before work

    major

    If the process dies in between, the event is never processed.

    Wrong
    commit(offset)apply(event)
    Right
    apply(event)          # idempotentcommit(offset)

Interview tips

  • How to explain it

    • Every committed change becomes an event.
    • Others follow with a bookmark.
    • It replaces dual writes.
  • Memory trick: CDC

    • Capture: read from the log.
    • Deliver: publish to a stream.
    • Consume: apply, then bookmark.
  • Reach for it when

    • Search, cache or warehouse must follow.
    • Deletes matter.
    • New readers keep appearing.
  • Leave it when

    • A read replica is enough.
    • A nightly export is enough.
    • The answer is needed inside the transaction.