Video in progress

Someone proposes doing cache invalidation through CDC (for example, Debezium) instead of in the application code. What trade-offs do you see?

CDC doesn't skip any write path and delivers committed changes in order, so the application code gets simpler. The price: extra infrastructure (Kafka Connect, Debezium), a delay of around a second, and keeping the mapping between a DB table and a cache key in another place.

📖 Answer

The usual problems with in-application invalidation:

  • someone changes the DB directly through a migration script or an admin panel, and the cache doesn't know;
  • a new endpoint was added and the invalidation was forgotten;
  • the pod died after the commit but before the invalidation, so the cache stays stale until the TTL;
  • one entity affects many caches (product, list, search), and you have to remember all of them at every write site.

The flow with CDC: PostgreSQL WAL / MySQL binlog → Debezium → Kafka topic → an invalidator service → DEL/UNLINK in Redis.

What we gain:

  • only what was committed arrives, and rollbacks drop out on their own;
  • changes for a single row are ordered (the Kafka partition key is the primary key);
  • if Redis is down, the invalidator waits on Kafka and then continues, so there are no "lost invalidations".

What we pay:

  • delay: usually 100 ms to a few seconds. If you need read-your-writes, the application still deletes the cache entry itself after its own write, and CDC becomes the guarantee layer;
  • operational cost: a Kafka Connect cluster, a replication slot (in Postgres, if the slot stalls, the WAL fills the disk, which is a real prod incident), schema changes;
  • mapping: the knowledge of "which keys must be deleted when the product_price table changes" now lives in the invalidator. Teams forget it when they change tables. I require that this mapping be kept as code in the service owner team's repository;
  • for a denormalized cache (a response assembled from several tables), the mapping gets complicated.

When it's worth it: several services or paths change the DB, there are many caches, and staleness bugs have caused real incidents. For a single small service it's overkill: @TransactionalEventListener(AFTER_COMMIT) plus a short TTL is enough.

If the organization already has an outbox or Debezium, adding invalidation to that flow is cheap, since no new infrastructure is needed.