Video in progress

A bug in a consumer corrupted a read model and it has to be rebuilt from a Kafka topic. How do you plan retention, compaction and the replay process?

Replay works only if history is kept in the topic: retention must be long enough or the topic must be compacted. I do the rebuild into a new table with a new consumer group, idempotently and at a speed that doesn't flood prod traffic, then switch reads over in one moment.

📖 Answer

The first question: is there history? The default retention.ms is 7 days. If the bug went in 3 weeks ago, the events you need are already gone from the topic. So "can a read model be rebuilt from this topic" is decided when the topic is created:

  • state events (CustomerUpdated with the full state): a compacted topic (cleanup.policy=compact): the last value for each key stays forever. This is exactly what you need to rebuild a read model;
  • change events (MoneyWithdrawn): compaction breaks them. For those you need long retention or an archive (S3, Kafka tiered storage);
  • if history isn't enough: ask the source service for a "snapshot": it re-emits all current state into the topic (a bootstrap).

How the replay goes:

  1. A new table customer_view_v2 and a new consumer group customer-view-rebuild-v2, auto.offset.reset=earliest. The old read model keeps running, so nothing changes for users.
  2. The fixed consumer reads from the beginning. Writes must be idempotent (an upsert with a version), because rebalances and re-reads will happen during the replay.
  3. Rate limiting. A replay can read tens of thousands of messages per second and write that many to the DB, which slows down prod queries. Control the speed with batch writes, max.poll.records and the number of pods.
  4. When the new consumer catches up to the latest offset (lag ≈ 0), compare the two tables: row counts, random samples.
  5. Switch reads over through the view name, a feature flag or config. Keep the old table and consumer group for a while.

Watch out for side effects. If a consumer takes an event and sends an email or calls another service, the replay will resend 3 weeks' worth of emails to customers. The code that builds the read model must be separate from side-effect code, or side effects must be switched off in replay mode.

A compacted topic has a subtle point too: deletion tombstones (a null value) are cleaned up after delete.retention.ms. If a slow replay reading from the beginning runs longer than that, it may read the old value and never see the tombstone, so a deleted record stays alive in the read model.