Pub/Sub & Change Data Capture
Two patterns for moving events between systems without tightly wiring them together.
Pub/Sub & CDC in 30 seconds
- The problem: one event, many interested systems — wiring the source to call each directly creates a brittle tangle.
- Pub/Sub: publisher writes to a topic, every subscriber gets a copy. The source never knows who's listening — pure decoupling.
- Queue vs pub/sub: a queue gives each message to one consumer (task distribution); pub/sub fans out to all (event broadcast).
- CDC: tap the database's write log and turn every insert/update/delete into an event — events derived from the source of truth.
- Why CDC wins: it dodges the dual-write problem, where writing the DB and publishing an event separately can drift apart.
- The cost: eventual consistency, and consumers must be idempotent because events can be redelivered.
A newsroom and a bulletin board
Picture a radio station broadcasting the news. The announcer reads it once into the microphone; every radio tuned to that frequency hears it. The announcer has no idea who's listening, how many, or whether anyone is at all — they just broadcast, and listeners tune in or don't. That's Pub/Sub: a publisher announces an event to a channel, and everyone subscribed to that channel receives it, with neither side knowing the other.
Now picture a second idea: a scribe who sits by the town records office and, every time a clerk writes a new entry in the ledger, copies that change onto a public bulletin board. Nobody has to remember to post — the posting is an automatic consequence of the ledger changing. That's Change Data Capture: events derived straight from the database's own record of what changed. This page is about both, and about why the second one quietly fixes a bug the first one can't.
The problem it solves
When something happens in one part of a system — an order is placed, a user signs up — several other parts usually care: send an email, update analytics, write an audit log. Wiring the source to call each of them directly creates a brittle tangle. Publish/Subscribe and Change Data Capture are two ways to broadcast those events so interested systems react on their own, without the source knowing or caring who's listening.
The gap direct calls can't fill
The naive approach is the obvious one: when an order is placed, the order service just calls each interested service directly. It works — until it doesn't. Watch how it rots as the system grows:
- Every new reaction edits the source. Want to add fraud scoring? You crack open the order service and add another call. The one piece of code that should be stable keeps getting churned.
- The source is coupled to everyone. The order service now needs to know the address, the API shape, and the health of email, analytics, audit, shipping… It can't be reasoned about alone.
- One slow or down dependency drags the source down. If analytics is slow, placing an order is slow. If audit is down, do you fail the order?
- Testing explodes. You can't test 'place an order' without standing up five downstream services.
def place_order(order):
save(order)
email.send_confirmation(order) # must know each dependency's API
analytics.record_sale(order) # a new reaction = edit THIS function
audit.log(order) # one slow call blocks the whole order
# fraud.score(order) # ...and the list keeps growing
# The order service is now coupled to five systems and fails if any one does.The thing all four problems share: the source knows about its consumers. Pub/Sub breaks that knowledge. The source announces what happened and stops caring who reacts — which is the whole point of the next section.
Publish/Subscribe
In Pub/Sub, a publisher sends a message to a named topic and is done. Any number of subscribers registered on that topic each receive a copy. The publisher never knows who the subscribers are — that decoupling is the whole point. Adding a new reaction (say, a fraud-check service) means subscribing to the topic; no change to the publisher.
# Publisher: fire the event and move on — it doesn't know who's listening
broker.publish("order.placed", { "order_id": 1234, "user_id": 42 })
# Each subscriber registers on the topic and reacts independently
@subscribe("order.placed")
def email_service(event): send_confirmation(event["user_id"])
@subscribe("order.placed")
def analytics_service(event): record_sale(event["order_id"])
@subscribe("order.placed") # add a new reactor without touching the publisher
def fraud_service(event): score_order(event["order_id"])Pub/Sub vs a plain queue
A point-to-point queue delivers each message to one consumer — good for distributing tasks. Pub/Sub fans a message out to many independent subscribers — good for broadcasting events. They're complementary: you often publish an event, and each subscriber feeds its own work queue. The distinction interviewers look for is 'one worker takes it' (queue) versus 'everyone interested gets it' (pub/sub).
| Pattern | Delivery | Decouples | Fits |
|---|---|---|---|
| Queue (point-to-point) | One consumer per message | Producer from a worker pool | Task distribution, job processing |
| Pub/Sub (topic) | All subscribers get a copy | Producer from many reactors | Event broadcast, fan-out notifications |
In practice they stack. A single order.placed event is published once (pub/sub, fan-out to all), and each subscriber drops it onto its own private queue where a pool of its workers takes one message each (queue, distribute among workers). Broadcast between services, distribute within one. See Message queues for the worker side.
Change Data Capture (CDC)
Sometimes the 'event' you want is simply the database changed. CDC taps a database's write log (the same log replication uses) and turns each insert, update, and delete into an event stream. Instead of your application code remembering to publish an event on every write — which it will eventually forget to do — CDC derives events straight from the source of truth, so nothing is missed.
{
"op": "UPDATE", // INSERT | UPDATE | DELETE
"table": "users",
"ts": 1716249600,
"before": { "id": 42, "email": "ada@old.com" },
"after": { "id": 42, "email": "ada@new.com" },
"source": { "lsn": "0/16B3F48" } // position in the DB write log
}
// a downstream consumer reacts: re-index search, invalidate cache, etc.The gap app-level publishing can't fill — the dual-write problem
Here's the subtle bug CDC exists to kill. If you use plain pub/sub for 'keep the search index in sync', your order service does two separate writes: save to the database, then publish an event. These are two independent operations to two independent systems, and nothing makes them happen together. So picture the crash:
- The database write succeeds — the order is saved.
- Then the process crashes (or the broker is momentarily down) before the publish.
- Now the order exists in the database but no event was ever sent. The search index, the cache, the warehouse never hear about it. They're silently, permanently out of sync.
- The reverse is just as bad: publish succeeds, then the DB commit fails — now there's an event for an order that doesn't exist.
def place_order(order):
db.insert(order) # write #1 to the database
# <-- CRASH HERE: order is saved, but...
broker.publish("order.placed", order) # write #2 never happens
# Downstream systems never learn about the order. The DB and the event
# stream have silently diverged, and nothing will ever reconcile them.This is the dual-write problem: any time you write to two systems without a shared transaction, a crash between them leaves the two disagreeing. CDC removes the second write entirely. There's only one write — to the database — and the event is derived from the committed change, read out of the write log the database already keeps for durability. No commit, no event; a commit, always an event. The two can't drift because there's only one source.
How CDC reads the log without slowing the database
A fair worry: doesn't 'tapping the write log' add load to the database you're trying to protect? Barely — and that's the elegance. Every durable database already writes a sequential log of changes (Postgres calls it the WAL, MySQL the binlog) so it can recover after a crash and feed replicas. CDC just reads that existing log, exactly like another replica does. It doesn't query your tables or compete with your application's reads and writes.
-- The database already streams its write-ahead log to replicas.
-- A CDC tool connects as if it were one more replica and reads the same stream:
SELECT * FROM pg_logical_slot_get_changes('cdc_slot', NULL, NULL);
-- lsn | change
-- ----------+-----------------------------------------------
-- 0/16B3F48| INSERT users (id=42, email='ada@new.com')
-- 0/16B3F9C| UPDATE orders SET status='paid' WHERE id=1234
-- Each change becomes an event. No table scans, no extra load on queries.Because the log is ordered and positions (the LSN) are durable, a CDC consumer that falls behind or restarts just resumes from its last position — no change is skipped, none is read twice without the consumer knowing. That's what makes CDC a reliable, replayable event source rather than a best-effort hook.
What they enable
Together these patterns power event-driven architecture: keeping a search index fresh as records change, invalidating caches when source data updates, feeding a data warehouse or analytics pipeline, and letting microservices react to each other's changes without direct coupling. The cost is the usual asynchronous trade — eventual consistency and the need for idempotent consumers, since events can be redelivered.
| Use | Pub/Sub | CDC |
|---|---|---|
| Event source | App explicitly publishes a business event | Derived automatically from DB writes |
| Best for | Business events ('order placed', 'user invited') | Keeping derived stores in sync (index, cache, warehouse) |
| Dual-write risk | Yes — app write and publish can diverge | No — single write, event follows the commit |
| Granularity | Whatever the app chooses to emit | Every row-level insert/update/delete |
| Coupling to schema | Loose — events are a chosen contract | Tighter — events mirror table structure |
They're not rivals. A common setup uses CDC to reliably emit low-level change events, then pub/sub to fan those events out to every component that needs them. CDC guarantees nothing is missed; pub/sub spreads it to everyone who cares.
The catch: at-least-once and eventual consistency
Both patterns inherit the asynchronous world's two standing rules, and you must design for them. First, delivery is at-least-once — a consumer that crashes mid-process will see the event again on retry, so the same event can be processed more than once. Make consumers idempotent (see Idempotency) so a repeat is harmless. Second, reactions are eventually consistent — there's a gap between the write and the moment the index or cache catches up. Usually milliseconds, but never zero.
def on_user_changed(event):
# Events can redeliver, so dedupe on a stable id + log position.
key = (event["after"]["id"], event["source"]["lsn"])
if seen.contains(key):
return # already applied — ignore the repeat
seen.add(key)
search_index.upsert(event["after"]) # re-indexing twice = same result anyway
# Idempotency turns 'at-least-once delivery' into 'effectively exactly-once'.Pub/Sub and CDC are the plumbing of event-driven architecture — the shift from services calling each other directly to services reacting to things that happened, which is what lets a system grow without turning into a web of hard wiring.
Why it matters
- They decouple the source of an event from everyone who cares, so you add reactions without touching the producer.
- CDC keeps derived stores — caches, search indexes, warehouses — in sync from the source of truth automatically.
- They're how independent teams and services evolve in parallel instead of coordinating every change.
If ignored
- A brittle tangle of direct calls where adding one new reaction means editing the producer again.
- Dual writes that drift: the database commits but the event fails, and your systems quietly disagree.
- Stale caches and search indexes because someone forgot to publish an event on a write path.
Where it fits
- Sits on the event path, between the system that changes state and everything downstream that reacts.
- Rides on top of message queues and logs for durable, replayable delivery.
- CDC lives right next to replication — both tap the same database write log.
Related topics
- Message queues: the durable transport pub/sub and CDC events travel over
- Replication: CDC taps the same write log that replication uses
- Idempotency: events redeliver at-least-once, so subscribers must be idempotent
- Caching: CDC events are a clean way to invalidate caches when source data changes
Interview lens
Questions it unlocks
- How do you notify several services when an order is placed?
- How do you keep a search index or cache in sync with your database?
- What's the difference between a queue and pub/sub?
60-second answer
For broadcasting an event to many reactors I use Pub/Sub — the publisher writes to a topic and every interested subscriber gets a copy, so adding a new reaction needs no change to the source. A plain queue differs: one consumer takes each message, which suits task distribution. To keep a cache, search index, or warehouse in sync, I prefer Change Data Capture over app-level publishing, because deriving events from the committed write log avoids the dual-write problem where the database and the event stream drift apart. Both need idempotent consumers since events can redeliver.
Common traps
- Confusing pub/sub (fan-out to all) with a queue (one consumer).
- Doing dual writes to the DB and an event bus and letting them diverge, instead of CDC.
- Forgetting that event delivery is at-least-once and consumers must be idempotent.