Cache Invalidation: 6 Strategies and When to Use Each
A user edits a price, hits save, refreshes the page, and the price isn’t updated yet. The database is updated, but the cache in front of it doesn’t know that yet. Every cache needs a rule for when its copy of the value can’t be trusted anymore. Choosing that rule is most of the work of caching.
What is cache invalidation?
Cache invalidation is the process of updating or removing cached values when the source data changes, so readers don't get stale data. It’s always a balance between stale read vs. more cache misses (leading to increased load on the DB).
And this problem is not new - “There are only two hard things in Computer Science: cache invalidation and naming things.” Phil Karlton's line is famous for a reason: the cache and the database are two separate stores, and no write updates both at the same instant.
The six strategies compared
Most apps are a combination of two or three of these types. In the examples below, I am going to use Upstash Redis, but you can use the same commands on any Redis. To follow along, sign up for Upstash and create a free Redis database; Redis.fromEnv() reads its REST URL and token, both on the database page.
| Strategy | How stale data can get | Cost | Great for |
|---|---|---|---|
| TTL expiry | Up to the TTL | Nothing beyond setting the expiry | Every key, as a safety net |
| Delete on write | Until the delete runs, plus a rare race | One delete per write | Writes that touch keys you can name |
| Versioned keys | Not stale for reads after the bump | One extra read per lookup; old keys wait for their TTL | Many keys per user or entity |
| Tag sets | Until the tag is cleared, plus the same rare race as delete on write | One set add per cached value | Pages or queries built from several records |
| Event-driven | Until each server gets the message | A pub/sub channel or a stream | In-process caches on many servers |
| HTTP and CDN busting | Not stale for new asset URLs; until purge for pages | A build step or a purge API call | Static files and CDN-cached pages |
TTL expiry
A TTL (time to live) tells Redis to delete a key after a number of seconds. It puts a ceiling on how stale any value can get, even when every other strategy misses a write. Setting it in the same command as the value means no key ever lives without one:
import { Redis } from "@upstash/redis";
const redis = Redis.fromEnv();
await redis.set("inv-demo:product:1", { id: 1, price: 39 }, { ex: 300 });
console.log(await redis.ttl("inv-demo:product:1"));300Your choice of TTL should be the maximum amount of time you are willing to let the value be stale for, regardless of the update frequency of the value. For example, product price can be up to 5 minutes stale, but user permissions should be seconds stale. EXPIRE can be used to set or reset the TTL on an existing key.
The Data Browser in the Upstash console lists each key and the TTL remaining. If needed, you can modify the TTL in the Data Browser, or even delete a key manually, if you must evict a single value immediately.
A cached product in the Data Browser, with 48 seconds left on its TTL
Eviction is a backup mechanism for keys that are written without a TTL and can therefore never expire. By default eviction is turned off and then Upstash rejects writes after the database reaches its size limit. If you turn eviction on in the database settings then Upstash removes some keys to make room and keys with a TTL are evicted first:
The Eviction toggle in the database settings
A simple TTL approach would leave updates unseen until the key expires, but the strategies below will help bridge that gap, while TTL still provides the backstop.
Delete the key after the database write
When a write changes a record, delete its cache key. The next read misses, loads the new row from the database and caches it again:
import { Redis } from "@upstash/redis";
const redis = Redis.fromEnv();
type Product = { id: number; price: number };
const db = new Map<number, Product>([[1, { id: 1, price: 39 }]]);
async function getProduct(id: number): Promise<Product | undefined> {
const key = `inv-demo:product:${id}`;
const cached = await redis.get<Product>(key);
if (cached) return cached;
const product = db.get(id);
if (product) await redis.set(key, product, { ex: 300 });
return product;
}
async function updatePrice(id: number, price: number) {
db.set(id, { id, price });
await redis.del(`inv-demo:product:${id}`);
}
console.log(await getProduct(1));
await updatePrice(1, 35);
console.log(await getProduct(1));{ id: 1, price: 39 }
{ id: 1, price: 35 }Writing the new value into the cache is risky because two concurrent writes might reach the cache in reverse order and leave the cache with the old value. Two deletes, however, will always leave the cache with the same state. Facebook’s memcache layer deletes cache entries instead of updating them because deletes are idempotent.
It’s important to make the delete after the database write commits, as opposed to before. If we make the delete before the write, then any read that starts after the delete but before the write can place the old row back into the cache:
Deleting before the write lets a concurrent read put the old price back
Deleting after the write leaves one rare race: a read that misses, loads the old row before the write commits, and writes it to the cache only after the delete has run. This needs the read to stall for longer than the whole write plus the delete, so it is uncommon, and the TTL bounds how long the stale value lives.
For an Upstash Global database, the delete runs on the primary region and then is replicated asynchronously to the read regions. So for a short time after the delete returns, a read from another region can return the old value.
One way to verify that invalidation is working in production is to monitor hits and misses. The Usage tab in the console has a chart with hits and misses per second. When keys are invalidated, misses rise for a moment while the cache refills, then hits recover. A miss rate that stays high after a deploy or a write burst means keys are being invalidated more often than you expect.
The Hits / Misses chart for a database serving cached product reads
Versioned keys
Some writes invalidate many keys at once. Changing a user's plan might change their orders page, their cart, their usage summary and a dozen API responses. Listing every key is fragile. Instead, put a version number in the key and bump it:
import { Redis } from "@upstash/redis";
const redis = Redis.fromEnv();
async function cacheKey(userId: string, name: string) {
const version = (await redis.get<number>(`inv-demo:user:${userId}:v`)) ?? 0;
return `inv-demo:user:${userId}:v${version}:${name}`;
}
await redis.set(await cacheKey("42", "orders"), ["order-1"], { ex: 300 });
await redis.set(await cacheKey("42", "cart"), ["item-7"], { ex: 300 });
console.log(await redis.get(await cacheKey("42", "orders")));
await redis.incr("inv-demo:user:42:v");
console.log(await redis.get(await cacheKey("42", "orders")));[ 'order-1' ]
nullA single INCR operation invalidates all keys for a given user, as subsequent reads will construct keys using the new version. The previous version’s keys will be left to expire according to their TTL, as they will no longer be read. Thus, versioned keys must have a TTL associated with them to prevent excessive memory usage. In exchange, we pay the cost of an additional read operation per lookup to obtain the version. Bump the version after the database write commits, for the same reason as the delete in the previous section.
Tag-based invalidation with sets
A cached page can depend on several records, and one record can appear on several pages. Tags handle that many-to-many link. When you cache a value, add its key to a Redis set for each tag. To invalidate a tag, read the set and delete every key in it:
import { Redis } from "@upstash/redis";
const redis = Redis.fromEnv();
async function setTagged(key: string, value: unknown, tags: string[], ttl: number) {
const p = redis.pipeline();
p.set(key, value, { ex: ttl });
for (const tag of tags) {
p.sadd(`inv-demo:tag:${tag}`, key);
p.expire(`inv-demo:tag:${tag}`, ttl);
}
await p.exec();
}
async function invalidateTag(tag: string) {
const keys = await redis.smembers(`inv-demo:tag:${tag}`);
await redis.del(...keys, `inv-demo:tag:${tag}`);
return keys.length;
}
await setTagged("inv-demo:page:/products", "<html>…</html>", ["products"], 300);
await setTagged("inv-demo:page:/products/1", "<html>…</html>", ["products", "product:1"], 300);
console.log(await invalidateTag("products"));
console.log(await redis.exists("inv-demo:page:/products", "inv-demo:page:/products/1"));2
0As we see, deleting the products tag leads to the removal of both pages. The tag sets are given the same TTL as the values, meaning that a tag cannot live much longer than the keys that it references. Like a plain delete, invalidateTag runs after the database write commits, and the value's TTL still covers the rare read that re-caches old data. This is similar to cache tags on CDNs, and Drizzle ORM integration uses table names and custom tags similarly.
Event-driven invalidation for local caches
Deleting a Redis key works when every server reads from the same Redis. Some apps also keep a copy in each server's memory to skip the network round trip. A Redis delete cannot reach those copies, so the writer has to tell every server. Redis pub/sub does that in a few lines:
import { Redis } from "@upstash/redis";
const redis = Redis.fromEnv();
const local = new Map<string, unknown>();
const subscriber = redis.subscribe<string>("inv-demo:invalidate");
subscriber.on("message", ({ message }) => {
local.delete(message);
console.log("evicted", message);
});
local.set("product:1", { id: 1, price: 39 });
// After the database write commits:
await new Promise((r) => setTimeout(r, 1000));
await redis.publish("inv-demo:invalidate", "product:1");
await new Promise((r) => setTimeout(r, 1000));
console.log(local.has("product:1"));
await subscriber.unsubscribe();evicted product:1
falseWith pub/sub, only servers that are subscribed at that moment get the message. A server whose connection drops briefly, or that fills its cache before it subscribes, misses the message and keeps serving the old value until its local TTL runs out. If you need invalidations to survive dropped connections, store them in a Redis stream and have each server read from its last position. This approach is covered in depth in our post on a replicated local cache backed by Redis, which goes step by step, including covering the race between a read and an invalidation.
If the caches are hosted by other services, the writer can send the invalidation over HTTP. It can publish through QStash, to one endpoint or to a URL group that fans out to all of them, and QStash retries a failed delivery 3 times by default.
HTTP and CDN cache busting
Browsers and CDNs keep their own copies, and your server cannot delete them. For static files, the fix is to never change a file at the same URL. Put a version or content hash in the file name, then let caches keep it for a year:
<script src="/assets/app.3f9a1c.js"></script>
Cache-Control: max-age=31536000, immutableWhen we make a new build, we get a new URL, so we never request the old file again. The immutable directive tells the browser that the response will not change while it is fresh, so there are no more revalidation requests.
But HTML pages maintain their URLs, so they need either a low max-age or a way to be purged. CDNs offer two ways to purge: by URL and by tag. Cloudflare, for example, looks for the Cache-Tag response header and then purges up to 100 tags per request. This is the same idea as the Redis tag sets above, one layer further out.
Which strategy to choose
Cache invalidation is a complex topic with many different strategies, but there are a few general approaches to invalidation for typical applications. For most applications, caching can be as simple as setting a TTL for each cached key, and deleting cached keys after each database write. For applications with many keys affected by a single database write, versioned keys can be useful. For applications where pages depend on many records, tag sets can be useful. And for applications where servers cache in-memory copies, pub/sub or a stream can be useful. For more on the read side of these patterns, see Redis caching patterns, which covers cache-aside, write-through, and cache stampedes.