Scrivio Interview library
ConceptFoundations7 min read · updated 13 November 2026

Sometimes one change affects many cached entries, for example a category rename that changes thousands of cached product pages. Deleting each key is slow, and listing them may not be possible.

How can you invalidate a large group of cache keys at once, and what are the trade-offs of version-based keys compared with tracking keys in a set?

Try it yourself

Cache-aside: one read, three cache states

See what a cache hit saves, what a miss costs, and why a write deletes the cached entry instead of updating it.

Read this example as text

When the entry is in the cache (a hit)

  1. A request arrives. A caller asks the service for product 42. The cache already holds it.
  2. Ask the cache first. The service always asks the cache before the database. It sends GET product:42.
  3. Hit: the value comes back. The entry is there and still fresh, so the cache answers at once. The database is never touched.

1 cache call, 0 database reads.

When it was never cached (a miss)

  1. A request arrives. A caller asks the service for product 42. Nobody has asked for it before, so the cache holds nothing.
  2. Ask the cache first. The service always asks the cache before the database. It sends GET product:42.
  3. Miss: nothing comes back. The key was never stored. The cache answers nil, and the service must find the value itself.
  4. Read the database. The service runs SELECT ... FROM products WHERE id = 42. This is the slow, authoritative read the cache exists to avoid.
  5. The row comes back. The database returns the row. The service now has the value, but the cache is still empty.
  6. Store it for next time. Before answering, the service writes the value into the cache with a time to live: SET product:42 ... EX 300. The next read inside 300 seconds will be a hit.
  7. Answer the caller. The caller gets the value. It cost one database read, which a hit would have saved.

2 cache calls, 1 database read.

When its time to live has run out

  1. A request arrives. A caller asks the service for product 42. The cache held it once, but its time to live ran out 12 seconds ago.
  2. Ask the cache first. The service always asks the cache before the database. It sends GET product:42.
  3. Miss: nothing comes back. An expired key is the same as a missing one: Redis no longer returns it, and removes it. The cache answers nil, and the service must find the value itself.
  4. Read the database. The service runs SELECT ... FROM products WHERE id = 42. This is the slow, authoritative read the cache exists to avoid.
  5. The row comes back. The database returns the row. The service now has the value, but the cache is still empty.
  6. Store it for next time. Before answering, the service writes the value into the cache with a time to live: SET product:42 ... EX 300. The next read inside 300 seconds will be a hit.
  7. Answer the caller. The caller gets the value. It cost one database read, which a hit would have saved.

2 cache calls, 1 database read.

When the price changes afterwards

  1. The price changes. Later, someone updates the price to 25. The service writes the database first: UPDATE products SET price = 25 WHERE id = 42.
  2. Delete the cached entry. Then it deletes the key: DEL product:42. It does not write 25 into the cache. Deleting is simpler and safer: the next read misses and loads whatever the database holds then.
  3. The next read will miss. The cache is empty for this key again, so the next request repeats the miss path and stores 25.

3 cache calls, 1 database read, 1 database write.

What this example leaves out
  • One request at a time. Two requests missing at the same moment (a stampede) are not shown.
  • The write deletes the key. Some systems update the cache instead, which this example does not model.
  • The numbers are counts of round trips, not measured times.

There are two standard ways. With version (generation) keys, we keep a counter per group and put it into every key, so incrementing the counter makes all old keys unreachable with one O(1) command; the old entries stay until their TTL or eviction, and every read needs the current version. With tag sets, we record each key in a set per tag and delete all members on change; memory is freed at once, but the work grows with the number of keys and the sets must be maintained. Deleting by pattern is the option to avoid.

Why this question is asked

Most cache invalidation is one key at a time, but some changes ripple: rename a category and thousands of cached pages that show its name are now wrong. Interviewers ask this to see whether we know that we do not have to find and delete every key, and whether we understand what each shortcut costs. In this answer, we will look at why group invalidation is hard, then version keys, then tag sets, compare them, see why deleting by pattern is a trap, and finish with the same idea at a CDN.

1Why Deleting a Group Is Hard

Suppose category 12 has 8,000 product pages cached under keys like page:12:<productId>. To delete them we first need their names. Redis has no index from a category to its keys, so the only general way is to search the keyspace. KEYS page:12:* does that in one call, but Redis runs commands on a single thread, and KEYS over 50 million keys blocks every other client for seconds. SCAN with the same pattern does not block, but it still walks all 50 million keys to find 8,000, which takes minutes.

So we want an invalidation whose cost does not depend on searching. There are two ways to get it: make the old keys unreachable without touching them, or keep our own list of the keys.

2Version Keys: Change the Name, Not the Data

We keep a small counter per group, category:12:version, and build every key in the group from it. Readers and writers both read the counter first.

Text
GET category:12:version # "7"
SET page:12:v7:5001 "<html>" EX 3600
GET page:12:v7:5001 # "<html>" a hit
INCR category:12:version # (integer) 8: the whole group is invalidated
GET page:12:v8:5001 # (nil) readers now build v8 keys and miss
# page:12:v7:5001 is still in memory until its TTL ends or it is evicted

Notice that the invalidation itself is a single INCR, whatever the size of the group. Nothing is deleted; the old keys simply stop being asked for. That is the strength of the approach and also its first cost: the 8,000 old pages still occupy memory until their TTL runs out or the eviction policy removes them. So version keys only work together with TTLs on every entry and some memory headroom for the dead generation.

The second cost is the extra lookup. Every read now needs the current version before it can build the key, which is a second round trip to Redis. The usual answer is to cache the version locally for one or two seconds, which costs almost nothing and means an invalidation takes effect within that time on every pod. There is also a subtle trap: if the version key itself is ever evicted and recreated starting from 1, very old generations could become reachable again. Version keys should have no TTL, live where eviction cannot touch them, or start from a timestamp instead of 1.

3Tag Sets: Keep Your Own Index

The other approach builds the missing index. Whenever we cache a page, we also add its key to a set for each tag it depends on. On a change we read the set and delete everything in it.

SQL
SET page:12:5001 "<html>" EX 3600
SADD tag:category:12 page:12:5001 # (integer) 1
EXPIRE tag:category:12 3700 # the set lives at least as long as its pages
# category 12 is renamed
SMEMBERS tag:category:12 # 8,000 keys (use SSCAN for very large sets)
UNLINK page:12:5001 page:12:5002 ... # in batches of a few hundred
DEL tag:category:12

Here memory is freed at once, and there is no extra lookup on reads. But the work of an invalidation now grows with the number of keys, so a tag with 500,000 members is a long job, and the set itself needs care. Pages that expired on their own leave stale members behind, so the set grows unless it has its own TTL. Writing the page and adding it to the set are two operations that can be split by a crash. And in Redis Cluster, the pages of one tag live on many nodes, so the deletes must be grouped per node rather than sent as one multi-key command.

4Choosing Between Them

Version keys win when groups are large, changes are frequent and memory has some room: invalidation is instant and constant-time. Tag sets win when memory is tight or freed memory matters, and when a key belongs to several groups, because a key can be added to many sets but can only carry one version in its name. Many systems combine them: versions for big, coarse groups such as a whole category or a tenant, tag sets for fine-grained dependencies.

Group invalidation options
ApproachCost of invalidatingMain drawback
Version keyOne INCR, O(1)Old entries use memory until TTL
Tag setO(keys in the tag)Sets to maintain and expire
Pattern delete (KEYS)Scans every key, blocksStalls the whole server
Pattern delete (SCAN)Walks the whole keyspaceSlow and loads the server
CDN surrogate keysOne purge requestPropagation takes seconds

5The Same Idea at the CDN

CDNs face the same problem with cached pages and solve it with tags. The origin attaches a header listing the keys a response depends on, for example Surrogate-Key: category-12 product-5001 at Fastly or Cache-Tag at Cloudflare and Akamai (check your provider's header name). A single purge request for category-12 then removes every object tagged with it, at every edge location. It is the tag-set idea run by the CDN, which is why it fits rendered pages that depend on several entities.

6Follow-up questions

How would you cache the version number itself?

In a local in-process cache with a very short TTL, one to five seconds. That removes the extra Redis round trip from almost every read, and the TTL bounds how long a pod keeps using the old generation after an INCR. If one to five seconds of delay is too much, we can also publish version changes on a pub/sub channel so pods update their local copy immediately, keeping the short TTL as the backstop for a missed message.

Can the version be part of the value instead of the key?

Yes. We can store the version inside the cached value and compare it with the current group version on read, treating a mismatch as a miss. It avoids building keys from the version, but the old value is still read and transferred before being rejected, so it is usually only worth it when keys must stay stable for other reasons.

What happens if the INCR runs but the database change rolls back?

Readers miss and reload from the database, which still has the old data, so they cache correct values under the new version. A spurious invalidation costs some misses but never correctness, which is why invalidating after the commit is preferred but invalidating too often is harmless.

7Conclusion

In this answer, we saw two ways to invalidate a group of keys without searching for them. Version keys put a per-group counter into every key, so one INCR makes the whole group unreachable, at the cost of memory held by the old generation until its TTL and a version lookup on each read, best cached locally. Tag sets keep our own index of keys per tag and delete them on change, which frees memory at once but costs work per key and set maintenance. Pattern deletes with KEYS or a full SCAN are the option to avoid, and CDNs offer the tag idea as surrogate keys.

What to say in the interviewAbout 80 seconds aloud

Open with

When one change affects many keys, I avoid searching for them. KEYS blocks single-threaded Redis, and SCAN over the whole keyspace to find a few thousand keys is slow and loads the server.

Then, if they want more

The first option is version keys. I keep a counter per group, like category:12:version, and include it in every key, so page:12:v7:5001. Changing the category is one INCR, and every old key becomes unreachable instantly, whatever the group size. The old entries are not deleted, so every key needs a TTL and I need memory headroom for the dead generation.

And every read needs the current version, so I cache it locally for a second or two, which also bounds how long invalidation takes. The version key itself must not be evicted and restarted at 1, or old generations come back. The second option is tag sets.

When I cache a page I SADD its key to tag:category:12, and on a change I read the set, UNLINK the keys in batches and delete the set. Memory is freed immediately, but the work grows with the number of keys and the set needs its own TTL and cleanup.

CDNs offer the same idea as surrogate keys or cache tags, purged with one request.

About this answer

Last updated
13 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "How can you invalidate a large group of cache keys at once, and what are the trade-offs...": https://scrivio-interview-library.netlify.app/architecture/caching-strategies/515f68a551/