System design concepts · Doing Things Later

Stream Processing and Change Data Capture (CDC) Explained

Batch jobs answer "what happened yesterday?". Streams answer "what is happening right now?". Most modern systems need both, wired together.

What you'll be able to explain
  • Explain batch vs stream processing and when each wins
  • Capture every database change as an event with CDC
  • Reason about event time, processing time, windows and watermarks
  • Keep state and get effectively-once results in a stream job
  • Sketch a production data pipeline from app to dashboard to warehouse

Batch vs stream: two clocks

A batch job reads a bounded pile of data (yesterday's logs, last month's orders), computes, and writes a result. A stream job reads an unbounded, never-ending flow of events and updates its results continuously.

Batch Stream
Input Bounded: files, tables, a day's partition Unbounded: a topic that never ends
Latency Minutes to hours Milliseconds to seconds
Correctness Easy: all data is present when you start Hard: data arrives late and out of order
Reprocessing Just run it again Replay the log from an old offset
Typical tools Spark, SQL in a warehouse, Hadoop MapReduce Flink, Kafka Streams, Spark Structured Streaming, Beam
Use for Billing, reports, ML training sets, backfills Fraud checks, live dashboards, alerting, real-time features
Analogy

Batch is counting the votes after the polls close. Streaming is the live counter on the TV that updates as each booth reports, including the awkward moment when a late booth changes the leader.

The two aren't rivals. A common healthy shape is: stream for freshness, batch for truth. The stream job powers the live dashboard; a nightly batch job recomputes the same numbers from the full log and corrects any drift.

Change data capture (CDC)

Your most valuable events are often changes to your own database: a new order, a cancelled booking, an updated price. You could make the application publish an event after each write, but that is the dual-write problem: the DB commit can succeed and the publish fail (or the reverse), and the two drift apart.

CDC avoids this by reading the database's own replication log (Postgres WAL, MySQL binlog, MongoDB oplog) and turning every committed change into an event.

SERVICEOrder serviceDATABASEPostgresprimaryWAL / binlogWORKERCDC connectorDebeziumQUEUE / LOGKafkaorders.changesSERVICESearch indexerSERVICECache invalidatorWORKERWarehouse loaderINSERT / UPDATEtail the logchange events
CDC: the database log becomes an event stream, with no extra work in the application.

A change event typically carries the before and after row images, the operation (create, update, delete), the transaction ID and the log position:

{ "op": "u", "table": "orders", "ts_ms": 1762941201123,
  "before": { "id": "HB-7Q", "status": "PAID" },
  "after":  { "id": "HB-7Q", "status": "SHIPPED" },
  "source": { "lsn": 99812734, "txId": 5521 } }

What CDC is great for

  • Keeping derived stores in sync: search indexes, caches, read models, analytics.
  • The outbox pattern: the app writes business rows and an outbox row in one transaction; CDC publishes the outbox rows. You get atomic "save and announce" with no distributed transaction (2PC vs Saga vs Outbox Pattern).
  • Migrations: stream a live table from an old database into a new one, then cut over.
  • Audit trails: an immutable history of every change.
Common trap

Treating raw CDC events as your public API. Table columns are an implementation detail; if other teams consume orders.changes directly, you can never rename a column again. Publish domain events (via an outbox) for other teams, and keep raw CDC for your own derived stores.

Time is the hard part

Every event has (at least) two timestamps:

  • Event time: when it actually happened on the device or server.
  • Processing time: when your stream job sees it.

They differ, sometimes wildly. A phone in a lift buffers taps and sends them two minutes later. A partition rebalance delays a batch of events by 30 seconds. If you count "orders per minute" by processing time, a hiccup in your pipeline shows up as a fake dip followed by a fake spike in your business.

PhoneKafkaJob1tap @10:00:58 (sent late, at 10:01:40)2tap @10:01:053tap @10:01:05 (processed 10:01:06)4tap @10:00:58 (processed 10:01:41)5event time says this belongs to the 10:00 window
Events arrive out of order. Counting by processing time puts the late tap in the wrong minute.

The rule: aggregate by event time whenever the business question is about when things happened, which is almost always.

Windows

To aggregate an infinite stream, you cut it into finite windows.

Window Shape Example question
Tumbling Fixed size, no overlap: 10:00–10:01, 10:01–10:02 Orders per minute
Sliding / hopping Fixed size, overlapping: 5-minute windows every 1 minute Moving average of error rate
Session Gap-based: closes after N minutes of inactivity per key Length of each user's browsing session
Global + trigger One window, emit on a schedule Running total since launch
Tumbling (1 min)[10:00–10:01) [10:01–10:02) [10:02–10:03) … each event in exactly one windowHopping (5 min, every 1 min)[10:00–10:05) [10:01–10:06) … each event in five windowsSession (gap 30 min)Alice: [10:03 … 10:41] then a new session at 11:30
Three ways to slice the same stream.