Video in progress
Cache-DB inconsistency is causing regular complaints on prod. Instead of relying on TTL, how do you build invalidation through CDC, and what are its risks?
Database changes are read from the WAL/binlog (with something like Debezium) and arrive through Kafka at a cache invalidation service, which deletes the relevant keys. The problem of "forgetting the cache" in application code goes away, but lag, the key mapping and Kafka's reliability become new sources of risk.
📖 Answer
The usual picture: cache invalidation is written by hand in 40 places in the application. Someone added a new endpoint and forgot. An admin fixed something directly with SQL — the cache doesn't know. A migration script updated prices — the cache doesn't know. Shortening the TTL isn't a solution: the benefit of the cache shrinks, and the inconsistency window is still there.
The CDC scheme:
PostgreSQL WAL -> Debezium -> Kafka (db.public.courses) -> cache-invalidator -> Redis DEL
The benefit is that every change in the database — whichever way it happens (application, admin SQL, migration) — is caught. Order is preserved (one partition per row). The application code gets simpler.
Design issues:
The table-to-key mapping. A courses row changed — which keys need to be deleted? course:42 is easy. But category:7:top, author:15:courses, and the home page block also depend on this course. This mapping lives in the invalidator and has to be kept up to date. For derived caches, a tag-based approach is often used: when a key is written, tags are attached to it (tag:course:42 -> {set of keys}), and the invalidator deletes by tag.
The race. A reader read the old value from the DB → the CDC delete arrived → the reader wrote the old value into the cache. The fix: write to the cache with a version (SET only if the version is greater, through Lua) or run the invalidation twice with a short delay. The version is the row's updated_at or version column, or the WAL LSN.
Lag. CDC is usually under a second, but when Debezium restarts or during a large migration it can stretch to minutes. Put an alert on the lag metric, and keep the TTL anyway as a safety net (for example, 1 hour).
Reliability. If Kafka or the connector stops, invalidation stops — the cache slowly goes stale. When the connector recovers it continues from the WAL, but while the replication slot is stalled, Postgres doesn't delete WAL — the disk can fill up. Monitoring the slot size is a must.
Local caches across several instances. If every pod has Caffeine in addition to Redis, the invalidation has to reach them too — through Redis Pub/Sub or each pod with its own consumer group.
When I don't do it: if the cache is small and inconsistency is harmless, TTL plus an AFTER_COMMIT delete in the application is enough. CDC is worth its operational cost where there are many writing sources and consistency matters to the business.
Sign up to mark studied questions and save your progress.