Object cache · 30 November 2026

Stop a WordPress cache stampede with a lock that actually locks

The usual WordPress lock checks a transient and then sets it. Under load, two requests pass the check together and both do the work. Here is why that happens, three locks that hold, and a test that proves it.

By Shane Rounce · 5 minute read

The problem: the lock everybody writes

This pattern is in almost every WordPress codebase I open, including my own older code:

if ( ! get_transient( 'rebuild_lock' ) ) {
    set_transient( 'rebuild_lock', 1, 60 );
    rebuild_expensive_thing();
    delete_transient( 'rebuild_lock' );
}

It reads well and it works on a quiet site. The fault is the gap between the check and the set. Two requests can both run the check before either has run the set. Both see no lock, both take it, and both do the expensive work.

The gap is tiny. On a busy site tiny gaps are hit all day, and they are hit hardest at the worst moment: when a popular cache entry has just expired and many requests arrive wanting the same thing. That pile-up is a cache stampede, and this lock is usually the thing that was meant to prevent it.

StepCheck, then setAtomic add
1A reads the lock: nothing thereA adds the lock: true, A owns it
2B reads the lock: nothing thereB adds the lock: false, already taken
3A sets the lockA rebuilds
4B sets the lock, over the top of AB serves the old copy
5A rebuilds
6B rebuilds as well
Two workers, one lock. Step through both versions and count the rebuilds.

Where the same shape turns up

It is not only locks. Any read, decide, write sequence on shared data has the same gap.

UseThe codeWhat goes wrong
Rebuild lockCheck for a lock, then set itSeveral workers rebuild the same thing at once
Click or vote dedupeCheck "has this user voted?", then record itA double tap is counted twice
Points or stock balanceRead the total, check it covers the cost, write the new totalLost updates and totals below zero

In every row, no single request does anything wrong. Each one read a value that looked fine and acted on it.

The fix: make the check and the set one operation

Stop asking "is it free?" and then claiming it. Ask the store to claim it only if it is free, and to tell you whether that worked. There are three ways to do that in WordPress, depending on what you have.

1. wp_cache_add, if you have a persistent object cache

wp_cache_add() writes only when the key does not exist and returns false when somebody got there first. With a Redis object cache that is one atomic command.

if ( wp_cache_add( 'rebuild', 1, 'locks', 60 ) ) {
    try {
        rebuild_expensive_thing();
    } finally {
        wp_cache_delete( 'rebuild', 'locks' );
    }
}

One caution. Without a persistent object cache, the WordPress object cache lasts for a single request, so this lock protects nothing between requests. Check before you rely on it:

wp cache type

Transients are not a substitute here. set_transient() overwrites. It has no "only if absent" form.

2. Redis SET with NX, if you talk to Redis directly

SET key value NX EX seconds sets the key only if it does not exist, with an expiry, in one command. Store a random token as the value and release the lock only if the token is still yours:

$token = wp_generate_uuid4();
if ( $redis->set( 'lock:rebuild', $token, [ 'nx', 'ex' => 60 ] ) ) {
    try {
        rebuild_expensive_thing();
    } finally {
        $redis->eval(
            "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) end return 0",
            [ 'lock:rebuild', $token ],
            1
        );
    }
}

The token matters. If your work runs past the expiry and another worker takes the lock, a plain delete would release their lock, not yours.

3. MySQL GET_LOCK, if you have no Redis

global $wpdb;
if ( '1' === $wpdb->get_var( "SELECT GET_LOCK('rebuild', 0)" ) ) {
    rebuild_expensive_thing();
    $wpdb->query( "SELECT RELEASE_LOCK('rebuild')" );
}

The lock belongs to the database connection and is released if the PHP process dies. It does not help across separate database servers.

What should the loser do?

A lock answers "who rebuilds". It does not answer "what does everyone else get". If the losers wait for the winner, you have swapped a stampede for a queue.

The better answer is to keep the old copy and hand it out while one worker rebuilds. That is what serving stale means, and it is how the page cache in Ace Redis Cache treats an expired page: the old copy still goes out, and one refresh is queued behind a lock. For live blocks the rule is one background render per block every 20 seconds, however many visitors ask. The features page describes both.

Always give a lock an expiry

A lock without a lifetime is a lock that survives a crashed worker for ever. Choose an expiry a little longer than the slowest honest run of the work. Too short, and a second worker starts while the first is still going. Too long, and one crash blocks the job for the rest of that time.

Write the race test

Races do not show in a normal test suite, because tests run one request at a time. You need real processes running in parallel, and WP-CLI makes that easy. Put the guarded work in a file and count how often it runs:

<?php
// race.php: try to take the lock and count each rebuild.
if ( wp_cache_add( 'rebuild', 1, 'locks', 30 ) ) {
    wp_cache_incr( 'rebuild_runs', 1, 'counters' );
    sleep( 2 );
    wp_cache_delete( 'rebuild', 'locks' );
}
wp eval 'wp_cache_set( "rebuild_runs", 0, "counters" );'
for n in 1 2 3 4 5 6; do wp eval-file race.php & done; wait
wp eval 'echo wp_cache_get( "rebuild_runs", "counters" ), PHP_EOL;'

Six workers start together and the answer should be 1. Swap the atomic add for the check, then set version and run it again. Run each several times: a race that loses once in ten runs is still a race.

Checklist

  • Search for get_transient, get_option or wp_cache_get followed closely by a set of the same key. Each one is worth a look.
  • Claim locks with an atomic add, give them an expiry, and release them only if you still own them.
  • Decide what the losers get. An old copy is nearly always better than a wait.
  • Work out totals such as points and stock from the rows that record each change, not from a cached running total.
  • Prove it with parallel processes, not a single request.

Related: page cache and object cache explains why the object cache has to be persistent for any of this to work, and the object cache wiki page lists what ARC keeps in Redis.

All notes Get the latest release