Stale-while-revalidate caching with WordPress transients
A normal transient has one weak moment: when it expires, the next visitor waits while the expensive value is rebuilt, and on a busy site several visitors rebuild it at the same time. Stale-while-revalidate avoids both: after the “fresh” time the old value is still served, and a single background job rebuilds it. Only the very first request, with nothing cached at all, has to wait.
Problem: A “popular posts” box is cached for five minutes, and every five minutes a page view takes two seconds longer, sometimes several at once.
Solution: Store the value together with the time it was built in one transient with a long lifetime, return it while it is fresh, return it anyway when it is stale and schedule one rebuild with wp_schedule_single_event() behind a short lock, and register the rebuild function per key so that the cron job can call it.
The helper
function ha_swr_register( $key, callable $build ) {
$GLOBALS['ha_swr_builders'][ $key ] = $build;
}
function ha_swr_get( $key, $fresh = 300, $stale = 3600 ) {
$entry = get_transient( 'ha_swr_' . $key );
if ( is_array( $entry ) ) {
if ( time() - $entry['built'] > $fresh && ! get_transient( 'ha_swr_lock_' . $key ) ) {
set_transient( 'ha_swr_lock_' . $key, 1, 60 );
wp_schedule_single_event( time(), 'ha_swr_rebuild', [ $key, $fresh, $stale ] );
}
return $entry['value']; // fresh or stale, the visitor does not wait
}
return ha_swr_build( $key, $fresh, $stale ); // nothing cached yet
}
function ha_swr_build( $key, $fresh, $stale ) {
$build = $GLOBALS['ha_swr_builders'][ $key ] ?? null;
if ( ! $build ) {
return null;
}
$value = $build();
set_transient( 'ha_swr_' . $key, [ 'value' => $value, 'built' => time() ], $fresh + $stale );
delete_transient( 'ha_swr_lock_' . $key );
return $value;
}
add_action( 'ha_swr_rebuild', 'ha_swr_build', 10, 3 );
One transient holds the value and its build time, so they can never disagree. The transient lives for $fresh + $stale seconds; after that, the value is too old to serve and the next request builds it again. The lock prevents a burst of visitors from scheduling a dozen rebuilds.
The builders are registered in PHP and not passed to the cron event, because cron arguments are stored in the database and a closure cannot be saved there. The registration must therefore run on every request, also the cron request: put it in a plugin file or functions.php, not in a template.
Usage
add_action( 'init', function () {
ha_swr_register( 'popular_posts', function () {
return get_posts( [
'posts_per_page' => 5,
'meta_key' => 'ha_views',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'fields' => 'ids',
] );
} );
} );
// in the template
foreach ( (array) ha_swr_get( 'popular_posts', 5 * MINUTE_IN_SECONDS, HOUR_IN_SECONDS ) as $post_id ) {
printf( '<li><a href="%s">%s</a></li>', esc_url( get_permalink( $post_id ) ), esc_html( get_the_title( $post_id ) ) );
}
When the cron job runs
wp_schedule_single_event() puts the job into WP-Cron, which runs on the next page load (in a separate, non-blocking request) or from a system cron if DISABLE_WP_CRON is set. On a quiet site the rebuild may wait for the next visitor; the stale value covers that time. More about one-off events: wp_schedule_single_event() for background tasks.
NOTE: Without a persistent object cache, transients are rows in wp_options, and the lock is not atomic: two requests in the same millisecond can both schedule a rebuild. That costs one extra rebuild, nothing more. With Redis or Memcached, use wp_cache_add() for the lock, which succeeds only for the first caller; see the object cache and Redis.