PHPackages                             humanmade/hm-swr-cache - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Caching](/categories/caching)
4. /
5. humanmade/hm-swr-cache

ActiveWordpress-plugin[Caching](/categories/caching)

humanmade/hm-swr-cache
======================

WordPress stale-while-revalidate cache plugin

0.3(2y ago)23[1 PRs](https://github.com/humanmade/hm-swr-cache/pulls)GPL-3.0-or-laterPHP

Since Jun 7Pushed 1y ago3 watchersCompare

[ Source](https://github.com/humanmade/hm-swr-cache)[ Packagist](https://packagist.org/packages/humanmade/hm-swr-cache)[ Docs](https://github.com/humanmade/hm-swr-cache)[ RSS](/packages/humanmade-hm-swr-cache/feed)WikiDiscussions main Synced today

READMEChangelog (2)DependenciesVersions (5)Used By (0)

HM SWR Cache
============

[](#hm-swr-cache)

A soft expiring cache with background updating is a specialized caching strategy that allows cached data to remain available even after the expiration period. With regular caching, data becomes unavailable or leads to a 'cache miss' as soon as it expires. This can be costly, particularly with complex data fetching operations that require significant time.

In a soft expiring cache, when the cache period expires, the cached data remains accessible while a background update operation occurs. During this time, the user or application continues to see the stale cached data until the new updated data is ready. This approach ensures data is always available for end consumers with minimized latency from cache rebuild, providing a continuously smooth experience. This is also called a `stale-while-revalidate` cache strategy, thus the name.

Note: As the cache is updated via a `wp_schedule_single_event()` call, using a scalable job system such as [Cavalcade](https://github.com/humanmade/Cavalcade) is recommended as the [default WordPress pseudo-cron](https://developer.wordpress.org/plugins/cron/) slows the page load running the scheduled event.

Requirements
------------

[](#requirements)

- PHP 8.1+ is supported (technically it might run on PHP 7.1+).
- WordPress 6.4.2+ is supported (technically it might run on older versions, your experience is welcome).

Installation
------------

[](#installation)

Just install the plugin like any other plugin. Installation as a MU plugin is supported as well, and via composer

```
composer config repositories.hm-swr-cache vcs git@github.com:humanmade/hm-swr-cache.git
composer require humanmade/hm-swr-cache:^0.3 --no-update
composer update humanmade/hm-swr-cache --prefer-source
```

These commands configure Composer to use a custom Git repository for the `hm-swr-cache` package, add this package as a requirement without immediately installing it, and finally update and install the package from the source repository.

Usage
-----

[](#usage)

All that is needed is for you to create a callback function that will be called with `$callback_args` as the first parameter by a scheduled task that is triggered when the cache expires after `$cache_expiry` seconds.

The following code goes where you need to use the cached data. On the first request the cache will be empty and scheduled to be generated, so your implementation needs handle that event. After the first generation, there will either be stale or current data to display:

```
// false is returned if the data isn't in the cache yet
$data = SwrCache\get(
	$cache_key,
	$cache_group,
	__NAMESPACE__ . '\\my_callback',
	$callback_args,
	$cache_expiry
);

if ( ! $data) {
	// handle initial empty cache load
}
```

The callback is what you need to implement to generate the cacheable data, an array in the example below. You must return a `WP_Error` object in case of issues, this will generate an RuntimeException in the cron event, resulting in a cron log entry.

```
function my_callback( array $args ) : WP_Error|array {
	// Example validation handling and cache generation.
	if ( ! isset( $args['url'] ) ) {
		return new WP_Error( 'missing_arg', 'url' );
	}
	$data = example_api_request( $args );
	if ( failed_validation( $data ) ) {
		return new WP_Error( 'invalid_data', 'Data failed validation', $data );
	}
	return $data;
}
```

Internally a self-expiring and self-managed lock system ensures the callback is just processed once, avoiding race conditions. If, for whatever reason (for example due to a fatal error) the callback doesn't complete, then the lock self-expires in 1 minute.

Flushing the cache
------------------

[](#flushing-the-cache)

Engineers can clear the cache as well as any locks by calling the `cache_delete_group( $cache_group )` function, which might be useful after saving a settings page for example. The cachegroup should first be registrered for flushing using `register_cache_group( $cache_group )` before it can be flushed.

Difference with other plugins
-----------------------------

[](#difference-with-other-plugins)

1. [WP-TLC-Transients](https://github.com/markjaquith/WP-TLC-Transients) In contrast to *WP-TLC-Transients*, *HM Swr Cache* is not hitting the database in any circumstance as both the lock, cached data and cache expiry are all stored using `wp_cache` functions. The syntax is also quite different.

I think that's it!

###  Health Score

20

—

LowBetter than 13% of packages

Maintenance28

Infrequent updates — may be unmaintained

Popularity6

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity34

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~2 days

Total

2

Last Release

754d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/a42fc2280fbcf46560c203bb7a0dc56a26ab8cf99f574b6aeb3f2cb95eaa3862?d=identicon)[svandragt](/maintainers/svandragt)

![](https://www.gravatar.com/avatar/77dbeefb7745010589603f2ffc6ff310d8f700b58e08d52af190744c43342526?d=identicon)[roborourke](/maintainers/roborourke)

---

Top Contributors

[![svandragt](https://avatars.githubusercontent.com/u/594871?v=4)](https://github.com/svandragt "svandragt (12 commits)")

---

Tags

background-updatingcache-expirationcaching-strategysoft-expiring-cachestale-datastale-while-revalidatewordpresswordpress-pluginwordpresscachestale-while-revalidateexpirysoft-expiring-cachebackground-updatingcaching-strategycache-expirationdata-fetchingstale-datalow-latency

### Embed Badge

![Health badge](/badges/humanmade-hm-swr-cache/health.svg)

```
[![Health](https://phpackages.com/badges/humanmade-hm-swr-cache/health.svg)](https://phpackages.com/packages/humanmade-hm-swr-cache)
```

###  Alternatives

[rtcamp/nginx-helper

Cleans nginx's fastcgi/proxy cache or redis-cache whenever a post is edited/published. Also provides cloudflare edge cache purging with Cache-Tags.

23617.1k1](/packages/rtcamp-nginx-helper)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
