Drupal's page cache is great while it's populated, but once a page is invalidated (for example when its content changes, or after a cache clear), the next request is blocked until the page builds.
On a busy site, or a site which is being crawled aggressively, this can cause a traffic stampede to build multiple pages, which in turn can overwhelm most web servers.
This module will continue to serve cached pages after they become "stale" (that is, after the content they show has changed, or after the cache has been cleared), but in the background will rebuild the page, without blocking requests.
Background page refreshes happen immediately at the end of the current request, up to a maximum of two (configurable in admin > config > development > performance) concurrent build sessions; if more than this number of stale pages need to be built at the same time, further requests are deferred to a queue which is processed by cron.
The problem
Drupal's internal page cache stores each anonymous page as permanent, together with its cache tags. When a tag the page depends on is invalidated, or the cache is cleared, the next visitor has to wait while Drupal builds the whole page again.
Invalidation is frequent on any site with listings. Saving a single node invalidates node_list, which affects every page that lists content, and every deployment that runs drush cr empties the page cache entirely.
What this module does
When a visitor asks for a page that is:
- cached and valid: they get the cached page (
X-Drupal-Cache: HIT), exactly as in core.
- cached but invalidated: they get the stale copy immediately (
X-Drupal-Cache: STALE). The page is then rebuilt after the response has been sent, or queued for cron.
- not cached at all: the page is built on the spot (
MISS), exactly as in core.
At most two pages are rebuilt at once, whether on request or by cron. A stale page that finds both slots busy is added to a queue and rebuilt by cron. A queued page that is valid again by the time cron reaches it, or has been purged since, is skipped.
A full cache rebuild (drush cr) no longer deletes cached pages. It marks them stale, so the first visit to each page after a deployment is served instantly and the page is rebuilt behind it.
Rarely visited pages benefit most. A stale page is served however old it is, so it stays fast even if nobody has requested it for a long time.
Cache-Control on stale responses
A stale response carries a short Cache-Control: public, max-age=N. N is the smallest of the stale max-age option (60 seconds by default), the max-age the page was stored with, and the site's page cache maximum age (the "Browser and proxy cache maximum age" setting on the Performance page). That setting does not decide when a page becomes stale, only how long a browser or CDN may keep it.
Without this, a CDN or reverse proxy in front of the site would keep the stale copy for the full page maximum age. Fresh and rebuilt pages keep the header they always had. A site whose page maximum age is 0, and any page sent as private or no-cache, is left exactly as it was.
Requirements
- Drupal 11 or 12, with the core Internal Page Cache (
page_cache) module enabled.
- PHP 8.1 or later.
- No contributed modules are required. It works with whatever backend the page cache uses (database, Redis and so on) and needs nothing added to
settings.php.
Settings
All options are optional. They are on the Performance page (admin > config > development > performance), in a "Stale-while-revalidate page cache" section. Any option can also be fixed in settings.php with the key shown below. A value in settings.php always wins, and the Performance page then shows that option read-only, with a note saying why.
$settings['embettered_page_cache_enabled'] (default TRUE): a kill switch. FALSE behaves exactly like core, including drush cr deleting pages.
$settings['embettered_page_cache_stale_max_age'] (default 60): seconds a stale response may be cached downstream.
$settings['embettered_page_cache_retention'] (default 31536000, one year): how long a stored page is kept. This is housekeeping only: a stale page is served however old it is, and every rebuild stores the page again with a fresh lifetime, so only a page nobody visits for this long is dropped. On the Performance page it is a choice from 5 minutes to 1 year, or "Unlimited" (-1 in settings.php).
$settings['embettered_page_cache_rebuild_slots'] (default 2): how many pages are rebuilt at once, on request or by cron.
$settings['embettered_page_cache_lock_timeout'] (default 120): crash-safety timeout on the rebuild locks. Keep it at or above your PHP-FPM request_terminate_timeout.
$settings['embettered_page_cache_queue_limit'] (default 5000): the most stale pages waiting for cron at once. Beyond it a page is left to be rebuilt on a visit after the de-duplication window, so a crawler cannot grow the queue without limit.
$settings['embettered_page_cache_queue_dedupe_window'] (default 900): seconds before a queued page may be queued again. About one cron interval.
$settings['embettered_page_cache_failure_backoff'] (default 60): seconds to leave a page alone after a rebuild could not be stored.
Retention and unlimited retention
A stale page is served however old it is, because refusing an old copy only swaps a cheap stale serve for an uncapped build on the spot. How long the cache keeps a page is a separate, housekeeping setting ("Keep pages for"). Every rebuild stores the page again with a fresh lifetime, so a page that is visited keeps being kept, and only a page left alone for the whole period is dropped. On the database backend an expired page may still be served until garbage collection removes it.
Choosing "Unlimited" stores pages without a lifetime. It suits archive sites that are rarely visited and want minimal compute: a page nobody has asked for in years is still served instantly, and rebuilt behind the response.
The trade-off is that pages nobody visits are never reclaimed, so crawler junk and query-string variants accumulate in a database-backed cache. Bound the cache some other way. Your cache backend may also evict pages when it runs out of memory, whatever this setting says. With Redis and an allkeys-lru policy, the stale pages nobody is reading are the first to go.
When the module does nothing
The module is bypassed while the page cache maximum age ("Browser and proxy cache maximum age" on the Performance page) is set to <no caching> (0). That is how development and staging environments switch caching off, so the module stays out of the way there: it behaves exactly like core, no stale page is served, nothing is rebuilt in the background, and clearing caches deletes cached pages. A configuration override in settings.php counts too.
Drupal's own default for that setting is 0, so a freshly installed site is bypassed until a maximum age is set. The Status report has a "Stale page cache" entry that says whether the module is Active, Bypassed (maximum age off) or Switched off, and the Performance page shows the same notice at the top of the module's section.
Where pages are stored
A stale page can only be served if the store still has it. A database table keeps pages until they are deleted. Redis, Memcache and APCu are memory-bound: when they fill up they discard the entries nobody has read recently, which is exactly what a stale page is. Retention is therefore a promise only a persistent store can keep.
The module inspects the page cache backend actually in use and reports it at the top of its section on the Performance page and on the Status report (admin > reports > status). For Redis it reads the memory limit, eviction policy, evicted key count and hit rate from the server. If those settings cannot be read, the storage is treated as at risk rather than as safe.
The Status report entry is informational for a store that can evict, and a warning if "Unlimited" is chosen as the retention on a store that is known to evict. A database-backed page cache is reported as fine.
Things to know
drush cr no longer clears cached pages. To delete them for real, for example to see a configuration change straight away, run drush php:eval "\Drupal::cache('page')->purge();".
- Installing the module empties the page cache once. Pages stored before it existed lack the tag that
drush cr now invalidates, so they would otherwise survive a deployment with the old release's markup.
- A page that has never been cached is still built on the spot, because there is nothing to serve.
- Cached 403 and 404 responses are not served stale. A page that was missing is far more likely to exist now than to still be missing, so it is rebuilt straight away.
- A page that will not cache is not retried on every visit. If a rebuild returns something core will not store, such as a server error or an exception, the page is left alone for a short back-off period. If the page now comes back gone or forbidden, its stale copy is deleted. A server error keeps the stale copy, because stale is better than an error.
- A stale page is served however old it is, so pages whose last three or more rebuilds failed are listed on the Status report, with a count and when they last failed. A page quietly stuck on an old copy is then noticed.
- Unpublishing or deleting content removes its cached page at once. A stale page is served however old it is, so otherwise the page of an unpublished article would stay public until a rebuild succeeded. The page is deleted under its alias, its system path and in every translation, for any publishable content entity such as a node, term or media item. Pages that only list the content, and query-string variants of its URL, stay stale until they are rebuilt, so run the purge command above if those matter.
- A rebuild sees its own request. Code that reads
$_SERVER, $_GET or $_COOKIE directly gets values describing the page being rebuilt, with the visitor's cookies and headers removed. Cron rebuilds run as the main request, and the active theme, static caches, entity memory cache and page cache kill switch are reset between pages.
- Old cache entries can be unreadable after a release. If a cached page no longer unserialises, it is treated as not cached and overwritten.
Known limitations
- Services first used during a rebuild that follows a stale response are not destructed, because core has already finished its own shutdown work by then. They are persisted by the next full request.
- Code that calls
exit() during a request kills the rebuild, and any locks it held lapse after the lock timeout. This only matters for a queued URL that such code would redirect, which a page that was cached in the first place normally is not.
- Rebuilt pages use the triggering visitor's timezone if a module changes it per visitor (for example by GeoIP), the same as core's first-visitor-builds-the-page behaviour. Cron rebuilds use the site default.
- The persistent lock backends share one owner ID, so a rebuild that outlives the lock timeout can release another process's lock.
Monitoring
X-Drupal-Cache: STALE on a response means a stale copy was served.
- The
really_simple_embettered_page_cache log channel records rebuilds that could not be stored (warning), exceptions (error) and queueing (debug).
drush queue:list shows pages waiting for cron.
How it works
- The page cache middleware and the
cache.page bin are altered in a service provider, so nothing needs configuring and the module works on any cache backend.
- Rebuilds run in a PHP shutdown function, after the response has been sent to the visitor. Drupal's own
terminate() is not used, because it only runs after the kernel has been prepared, which a page cache answer never reaches.
- Every stored page carries one extra cache tag, and deleting the whole page cache invalidates that tag instead of deleting rows. The backend's own
invalidateAll() is deprecated from Drupal 11.2, so it is not used.
- Concurrency is limited with Drupal's Lock API: a counting semaphore built from named locks, a per-page rebuild lock, and a per-page queued lock that is deliberately never released, so its timeout is what allows the page to be queued again.
Tests
The module ships with unit and kernel tests. The kernel tests need SIMPLETEST_DB and check the service alterations against a compiled container and a real database cache bin, including that a cache flush leaves pages stale rather than deleting them.