CodePark/ questions / Invalidation, stampedes & consistency
START PRACTICINGPRACTICE
Backend question · Redis & caching › Invalidation, stampedes & consistency

What strategies can you use to invalidate cached data?

There are four main strategies. Most systems combine them.

TTL expiry: every key gets a lifetime (TTL, time to live). So data can only be stale for a limited time, even if everything else fails. TTL is the safety net under all the other strategies.

Explicit delete on write: after the database commit, delete the affected keys. This is precise. But you must know every key built from that data, including lists and aggregates (totals, counts).

Event-driven: publish change events and let a consumer delete the keys. The events can come from the app or from change data capture (CDC) on the database. CDC means reading every change from the database's log. This way, the code that writes data does not need to know how the cache is organised.

Versioned keys: put a version in the key, such as products:v17:page:1, and increase the version when data changes. Nobody reads the old keys again, and they expire on their own. This is handy for invalidating whole groups of keys without scanning.

Do not invalidate by pattern with KEYS, because it blocks Redis while it scans every key. Instead, track related keys in a set, or use versioned prefixes.

  • A TTL is the basic safety net.
  • Delete the affected keys after the database write.
  • Event-driven invalidation deletes keys when change events arrive.
  • Versioned keys invalidate whole groups cheaply.
  • Never delete by KEYS pattern in production.