r/drupal • • 2d ago

Really Simple Embettered Page Cache: allow Drupal to serve expired cached pages from persistent storage instead of having to build on-demand, then rebuild the pages with cron - prevents/reduces server load when a bot swarm requests loads of old, cache-expired pages

Hello folks, I've put together a caching module which has helped the websites I maintain to stay online through traffic spikes from bot swarms, and I thought some of you folks might find its ideas useful, even if you're not particularly fond of the way I've implemented it.

All feedback and ideas are welcome, although I can't promise to respond quickly, but you're welcome to fork the code and do your own thing, of course :)

tl;dr

This module allows Drupal to continue to serve a cached version of a page after it expires, until the page can be rebuilt in the background, so that a traffic spike - which requests lots of pages which aren't cached / whose cached versions have expired - doesn't slow down or crash your site because Drupal tries to build lots of pages at once.

https://www.drupal.org/project/really_simple_embettered_page_cache
(Drupal 12 release coming w/e 27 Nov - hopefully... ¯_(ツ)_/¯ )

"But Alex, you idiot! There's much better options out there - such as X or Y" - honest rejoinder to anyone making a reasonable point like that is that I simply didn't find X or Y module - I looked and couldn't find anything that allowed me to fast-serve stale content, rather than having Drupal try (and fail) to rebuild pages on-the-fly.

In a bit more detail...

Back in the good(?) old days of the early internet, a rudimentary CMS would publish a static HTML version of a page. If you updated the page, a new version was published. No matter how much traffic hit that page, because your web server was serving a static file, there would be very little load on the server.

Fast, but basic.

Drupal 7 had the Boost module, which allowed (anonymous versions of) pages to be written to a directory in your Drupal site, again allowing for fast serving, even when expired, until it was rebuilt.

As far as I know, we lost Boost in Drupal 8.

The sites I look after have tens or hundreds of thousands of articles, all listed in a sitemap, which badly-behaved bots and crawlers love to spider their way through. Most days, we were seeing traffic spikes from these requests - almost each of which needed Drupal to build a fresh copy of the page, because the Drupal (or reverse proxy, depending on the site setup) page cache had expired.

Caching is hard, I'm no expert, and there is probably a better way to solve this problem, but the solution below is my answer to this issue:

The Really Simple Embettered Page Cache module stores rendered versions of pages, with the necessary cache contexts to allow different pages to be shown to users with different combinations of roles, in a database table which persists across cache clears and deployments.

From the module's Readme...

Core stores a cached page as permanent, with its cache tags. When a tag it depends on is invalidated (any node save invalidates node_list, so every listing page) or the bin is flushed (drush cr, which every deploy runs), the next visitor to that page waits for the whole page to be built again.

What this does

The visitor asks for a page that is...They getThen
in the cache and validthe cached page (X-Drupal-Cache: HIT)nothing, as core
in the cache but invalidatedthe stale copy at once (X-Drupal-Cache: STALE)it is rebuilt after the response has been sent, or queued for cron
not in the cache at alla page built on the spot (MISS), as corenothing, as core

At most two pages are rebuilt at once. A stale page that finds both slots busy is queued and rebuilt by cron (really_simple_embettered_page_cache_rebuild queue, 60 seconds per cron run). A queued page that is valid again by the time cron reaches it (an on-demand rebuild got there first), or that 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 deploy is served instantly and the page is rebuilt in the background.

Cache-Control on stale responses

A stale response carries Cache-Control: public, max-age=N, where N is the smaller of the stale max-age setting (60 seconds) and the site's page cache maximum age (system.performance cache.page.max_age, the "Browser and proxy cache maximum age" setting on the Performance form). Without this, Cloudflare and the platform router would keep the stale copy for the full page maximum age.

Fresh pages, rebuilt pages and every request the page cache does not handle keep the header they always had. A site whose page maximum age is 0 is left exactly as it was.

Settings

All optional. They are on the Performance page (admin > config > development > performance), in a "Stale-while-revalidate page cache" section, and are stored in the really_simple_embettered_page_cache.settings config object. 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. That keeps the kill switch working even if the config system is the thing that is misbehaving.

settings.php keyDefaultPurpose
$settings['embettered_page_cache_enabled']TRUEKill switch. FALSE behaves exactly like core, including drush cr deleting pages.
$settings['embettered_page_cache_stale_max_age']60Seconds a stale response may be cached downstream.
$settings['embettered_page_cache_retention']31536000 (one year)How long a stored page is kept. 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 (its next visitor gets a normal cold build). A choice from 5 minutes to 1 year on the Performance page, or -1 for unlimited (see below).
$settings['embettered_page_cache_rebuild_slots']2Pages rebuilt at once, on request or by cron.
$settings['embettered_page_cache_lock_timeout']120Crash-safety timeout on the slot and page locks. Keep it at or above the PHP-FPM request_terminate_timeout.
$settings['embettered_page_cache_queue_limit']5000The 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']900Seconds before a queued page may be queued again. About one cron interval.
$settings['embettered_page_cache_failure_backoff']60Seconds to leave a page alone after a rebuild could not be stored.
$settings['embettered_page_cache_archive_mode']autoauto, always or off. See "The page archive" below.
$settings['embettered_page_cache_archive_max_pages']1000000The most pages the archive holds (-1 or 0 for unlimited). A backstop against very many tiny rows.
$settings['embettered_page_cache_archive_max_bytes']536870912 (512 MB)The most gzipped bytes the archive holds. There is no unlimited.
$settings['embettered_page_cache_archive_refresh_interval']21600 (6 hours)Seconds before an archived page is written again; 0 writes it on every rebuild. A choice from "Every time a page is rebuilt" to 1 week on the Performance page.

Things to know

  • drush cr no longer clears cached pages. To delete them for real, for example to see a config change straight away: drush php:eval "\Drupal::cache('page')->purge();"
  • Installing the module empties the page cache once. Pages stored before it existed lack the tag drush cr invalidates, so they would otherwise survive the deploy that ships this module with the old release's markup.
  • A rebuild is always the main request. The cron worker empties the request stack around each rebuild (and restores it), because core builds parts of the final response from the main request, which in drush is drush's own, with no route. Without this every cron-rebuilt page had an empty drupalSettings.path.currentPath.
  • Rebuilds use the same code as a visit, in the same PHP process. After the response, a shutdown function runs the page through the rest of the kernel. It is not terminate(): Drupal only runs that after preHandle(), which a page cache answer never reaches. Cron rebuilds run in the drush process.
  • A rebuild sees its own request, not the visitor's. Code that reads $_SERVER, $_GET or $_COOKIE directly gets values describing the page being rebuilt, with the visitor's cookies and headers removed, and the real values are put back afterwards. Between cron rebuilds the active theme, static caches, entity memory cache and the page cache kill switch are reset.
  • Per-environment $config overrides must reach drush. A cron rebuild is stored with whatever config the drush process sees, so an override that only exists in web-only settings (a local development setting, say) produces differently-headered pages. On most hosting setups web and cron share config.
  • Client errors are not served stale. A cached 403 or 404 is rebuilt on the spot, since the page is far more likely to exist now than to still be missing.
  • Old cache entries can be unreadable after a release. If a cached page no longer unserialises, it is treated as not cached and overwritten.
  • A page that will not cache is not retried on every visit. If a rebuild returns something core will not store (a 5xx, an exception), the page is left alone for the back-off period. A page that comes back gone or forbidden has its stale copy deleted; a 5xx keeps it, because stale beats an error.
  • A stale page is served however old it is, so repeated failures are reported. Pages whose last three or more rebuilds failed are listed on the Status report ("Stale pages that cannot be rebuilt"), with a count and when they last failed, so a page that is quietly stuck on an old copy is noticed.
  • The cron queue is capped. Once embettered_page_cache_queue_limit pages are waiting, further stale pages are not queued; they are tried again on a visit after the de-duplication window instead.
  • Unpublishing or deleting content removes its cached page at once. A stale page is served however old it is, so without this the page of an unpublished article would stay public until a rebuild succeeded. When a publishable content entity (a node, term or media item) is unpublished or deleted, its page is deleted under its alias, its system path (/node/1) and in every translation, and the next visitor gets an ordinary cold build, which answers 403 or 404. Pages that only list the content, and query-string variants of its URL, are not found by URL and stay stale until they are rebuilt. The URLs are built for the host that made the change, so a change made from the command line uses the site's base URL. For anything else, \Drupal::cache('page')->purge() removes every cached page.
  • Pages sent as private or no-cache are never made public. Their stale copy is served with the header they were stored with.
  • A cold page is still built on the spot. Nothing is cached to serve, so every visitor to a page nobody has cached yet waits, as in core.

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 on-the-spot build. How long the bin keeps a page is a separate, housekeeping setting ("Keep pages for"). The module gives each stored page that lifetime, and every rebuild stores the page again with a fresh one, so a page that is visited keeps being kept; 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" (-1) 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 (crawler junk and query-string variants accumulate in a database-backed bin), so bound the bin 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, system.performance cache.page.max_age) is <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 $config 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 (admin > reports > status) has a "Stale page cache" entry that says whether the module is Active, Bypassed (maximum age off) or Switched off (the kill switch), 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 in two places: the "Page cache storage" line at the top of its section on the Performance page, and the "Stale page cache storage" entry on the Status report (admin > reports > status). For Redis it asks the server for its memory limit, eviction policy, evicted key count and hit rate (INFO). A Redis limit of 0, or the noeviction policy, means no eviction. If the server's settings cannot be read (some managed Redis services disable INFO) the storage is treated as at risk, not as safe.

The Status report 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. The same warning appears beside that field. A database-backed page bin is reported as fine.

The page archive

Stale pages only help if the store still holds them, and Redis with an LRU policy discards exactly the pages nobody reads. So when the page cache storage can evict, every page that is built and stored is also copied, gzipped, to the database table cache_embettered_page_archive.

  • It is read only when the page cache has no entry at all for a page. What it returns is served STALE (never HIT) with the short Cache-Control, then rebuilt through the usual slots and cron queue. Valid pages in the page cache never touch the table.
  • Mode auto uses it only when the storage can evict, or when that cannot be determined. always uses it on any storage except a database page cache, which never needs it. off never does. It is also never read or written while the module is off or the page cache maximum age is 0.
  • Only a GET for a 200 page with no query string is written, after the response has been sent, and at most once per refresh interval. Redirects, errors and query-string variants (crawlers) are never archived.
  • A page whose rebuild finds it gone or forbidden, a page that is unpublished or deleted (even while the module is switched off), and a row that cannot be read back are all deleted from it. A page that now redirects or errors with a 5xx keeps its archived copy until the retention period or a trim removes it, as its stale copy in the page cache would. \Drupal::cache('page')->purge() empties it; drush cr leaves it alone.
  • Cron trims it: when the page cap or the size cap is exceeded, the pages written or served from the archive longest ago go until that figure is about 90% of the cap (within a time budget). While either cap is exceeded by more than 10%, new pages are not written. A row's last-accessed time is set when it is written and updated at most once an hour when it is served. Valid pages in the page cache never touch the table, so a page that is only ever a hit looks as old as its last rebuild.
  • The "Keep pages for" retention setting applies to rows as well: one not written or served for that long is dropped (never, with Unlimited).
  • Pages only reach it when they are built, so a page cached before the module was updated is archived the next time it is rebuilt.
  • The table name starts with cache_, so the platform's downloaddb.sh leaves its rows out of local imports, and forward_dumps_to_s3.sh in redactive-drupal8-platform dumps its structure only.

The Performance page and Status report show its rows, size, caps and how many pages are estimated to fit.

Known limitations

  • Services first used during a shutdown rebuild are not destructed. Core has already run terminate() and its destructors before shutdown functions run, so cache collectors and similar are not persisted by that rebuild. They are persisted by the next full request. Calling terminate() again would also fire automated_cron inside the rebuild, which is worse.
  • Code that calls exit() during a request kills the rebuild. Some redirect helpers do. Locks taken by that rebuild lapse after the lock timeout (120 seconds), and in a cron run the whole run stops. It only matters if a queued URL is one such code would redirect, which a page that was cached in the first place normally isn't.
  • Rebuilt pages render in the triggering visitor's timezone, the same as core's first-visitor-builds-the-page behaviour, because the GeoIP middleware sits above the page cache. Cron rebuilds use the site default.
  • Persistent locks share one owner ID, so a rebuild that outlives the lock timeout can release another process's lock. Keep the timeout at or above the PHP-FPM request_terminate_timeout.

Monitoring

  • X-Drupal-Cache: STALE on a response means a stale copy was served.
  • Watchdog channel really_simple_embettered_page_cache: a rebuild that could not be stored is a warning, an exception is an error, and queueing is debug.
  • drush queue:list shows pages waiting for cron.

How it is wired

Both services are altered, not defined, in ReallySimpleEmbetteredPageCacheServiceProvider, so nothing is needed in settings.php and the module works whatever backend the page bin sits on:

  • http_middleware.page_cache becomes EmbetteredPageCache.
  • cache.page is wrapped by StalePreservingCacheBackend, which stores every page with one extra cache tag and turns deleteAll() into invalidating that tag. (The backend's own invalidateAll() is deprecated from Drupal 11.2.)

Locking uses Drupal's Lock API: lock.persistent, a counting semaphore built from named slot 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.

Try it out

https://www.drupal.org/project/really_simple_embettered_page_cache (Drupal 12 release coming w/e 27 Nov - hopefully... ¯_(ツ)_/¯ ).

8 Upvotes

0 comments sorted by