The problem: "forget everything about this"
Sooner or later every cache needs a button that forgets a whole family of entries. A menu is edited, a plugin updates, a price list changes, and thousands of stored values are wrong at once.
The obvious answer is to find every matching key and delete it. On a small cache that works. On a large one it is slow, it keeps Redis busy while it runs, and it gets slower as the cache grows. If it runs on publish, your editors feel it on every save.
Three ways to clear a group of keys
| Method | How it works | Cost |
|---|---|---|
SCAN, then DEL each key | Walk the keyspace with a pattern and delete one key per command | One round trip per key, and the scan looks at every key in the database, not only yours |
SCAN, then UNLINK in batches | Same walk, but keys are removed a few hundred at a time and their memory is freed in the background | Far fewer round trips. Still a walk of the whole keyspace |
| Generation counter | Do not delete. Change one number that is part of every key name | One command, however many keys there are |
Never use KEYS for this on a live server. It blocks Redis until it has looked at everything.
How a generation counter works
Each group of keys has a small counter, and the counter's current value is part of every key name in the group. To clear the group you add one to the counter. Every old key still exists for the moment, but nothing will ever ask for that name again.
| Before the flush | After the flush |
|---|---|
| Counter is 7 | Counter is 8 |
WordPress asks for shop:v7:options | WordPress asks for shop:v8:options |
shop:v7:options is found | shop:v7:options still exists but is never asked for, and expires on its own |
| Commands sent: 0 | Commands sent: 1 (INCR) |
In plain PHP against Redis it looks like this:
function menu_key( Redis $redis, string $id ): string {
static $gen = null;
if ( null === $gen ) {
$gen = (int) $redis->get( 'gen:menu' );
}
return "menu:{$gen}:{$id}";
}
// Write, always with a lifetime.
$redis->set( menu_key( $redis, $id ), $html, [ 'ex' => 3600 ] );
// Read.
$html = $redis->get( menu_key( $redis, $id ) );
// Clear the whole group.
$redis->incr( 'gen:menu' );
The counter costs one extra read per request, and holding it in a variable means it is fetched once.
The trade-offs, honestly
A generation counter is not free. It moves the cost from time to memory.
- Every key needs a lifetime. Old generations are abandoned, not deleted. Without an expiry they stay in memory until Redis evicts them, and with a
noevictionpolicy they stay until Redis refuses writes. See how long a Redis key should live. - Memory does not drop straight away. After a flush, used memory falls gradually as the old keys expire. If you are short of memory right now, a batched
UNLINKis the better tool. - Do not lose the counter. If the counter key is evicted it starts again from nothing, and entries from an old generation with the same number could come back. Give the counter no expiry.
- It clears a whole group. To remove one entry, delete that one key. Counters are for families.
If you do need the keys gone
When memory matters more than speed, scan in chunks and remove in batches. Two checks first. UNLINK needs Redis 4.0 or later. And on a cluster-mode server a multi-key command only works when every key hashes to the same slot, so send one key per UNLINK inside a pipeline. I learnt that one in production, and wrote it up in cluster-mode Redis and the read that returns nothing.
$redis->setOption( Redis::OPT_SCAN, Redis::SCAN_RETRY );
$it = null;
while ( false !== ( $keys = $redis->scan( $it, 'shop:menu:*', 500 ) ) ) {
$pipe = $redis->multi( Redis::PIPELINE );
foreach ( $keys as $key ) {
$pipe->unlink( $key );
}
$pipe->exec();
}
SCAN can return the same key twice and can return an empty batch before it has finished, so count carefully and stop only when the cursor says so.
What Ace Redis Cache does
The object cache in Ace Redis Cache keys every value under a per-site generation number. A flush is a single INCR instead of a scan of the whole Redis database: old keys are unreachable at once and expire by their lifetime. A scheduled clean-up removes superseded generations a couple of minutes after a flush, and again daily, so they do not sit there for their full lifetime.
Two related decisions came out of running it on busy sites:
- Saving a post does not flush the object cache. It removes that post's own keys and moves a stamp that post queries depend on. An importer saving posts in a loop used to move the generation a dozen times a minute, dropping every transient each time.
- A full clear of the page cache runs as a job. It works in batches inside a time budget, keeps its place, and reports progress, so a large clear cannot outlast the admin request that started it.
The object cache wiki page and purging and refresh have the detail, and what is different about ARC puts it in context.
How to check your own site
- Run
redis-cli --latencyin one terminal. - In another, trigger the clear you are worried about: publish a post, or press your cache plugin's clear button.
- If latency jumps while the clear runs, look at the code that does it. A loop with one delete per key is the usual cause.
- Compare
redis-cli info commandstatsbefore and after. A clear that sends tens of thousands of commands is a clear that will get slower every month.
Checklist
- Know what your "clear cache" button actually sends to Redis.
- Prefer one counter change for groups that are cleared often.
- Give every key a lifetime, and the counter none.
- Keep batched
UNLINKfor when you need the memory back now. - Never clear more than you own on a Redis shared between sites.