Cache and worker mode in a module
The core cache for a module: keys, tags, invalidation and stale values, the page cache for guests, and what a module must respect when one process serves many requests.
By the end the module's service keeps a ranking in the cache under the module tag, answers a question asked several times on one page with a single database query, and makes a write visible to visitors at once. The same code runs unchanged under plain PHP and in FrankenPHP worker mode.
Minimal example
<?php
declare(strict_types = 1);
namespace Flute\Modules\Example\Services;
use Flute\Core\Cache\CacheKeys;
use Flute\Core\Kernel\PageCacheStore;
use Flute\Core\Support\RequestMemo;
use Flute\Modules\Example\database\Entities\Score;
final class Leaderboard
{
private const MEMO = 'example.score';
public function top(int $limit, string $sort = 'score'): array
{
return cache()->callback(
"module.Example.top.{$sort}.{$limit}",
fn(): array => $this->load($limit, $sort),
300,
[CacheKeys::moduleTag('Example')],
);
}
public function scoreOf(int $userId): int
{
return RequestMemo::remember(
self::MEMO,
$userId,
static fn(): int => rep(Score::class)->select()->where('user_id', $userId)->fetchOne()?->points ?? 0,
);
}
public function record(Score $score): void
{
$score->saveOrFail();
RequestMemo::forget(self::MEMO, $score->user_id);
cache()->deleteByTag(CacheKeys::moduleTag('Example'));
PageCacheStore::flush();
}
private function load(int $limit, string $sort): array
{
return rep(Score::class)
->select()
->orderBy($sort === 'name' ? 'name' : 'points', $sort === 'name' ? 'ASC' : 'DESC')
->limit($limit)
->fetchData();
}
}top() goes to the database once every five minutes for the whole site. The card, the badge and the profile tab all ask scoreOf() about the same player, and the database gets one query. record() drops all three layers: the request memory, the module cache and the stored pages for guests.
How the cache works
cache() returns the Cache\Contracts\CacheInterface of the current driver (files, Redis, Memcached or APCu). callback() looks in process memory first, then in the store. On a miss one request computes the value under a file lock, and the others wait for its result instead of computing the same thing in parallel.
Every value has a stale copy. Once the value expires, in production (no debug) callback() returns the old value at once and computes the new one after the response goes out.
When the function throws and a stale copy exists, that copy is returned and the exception doesn't escape. No copy is written for a ttl under 60 seconds. ttl = 0 means "no expiry".
delete() and deleteByTag() remove both the value and its stale copy, so a visitor won't see the old value after a write. Tags are given at write time, in set() or callback(); tagKey() stays for old code and does nothing for a key that hasn't been written yet. Name keys module.<Name>.<what>, and take the module tag from CacheKeys::moduleTag('Example'). The module provider's clearFileCache() drops that tag, and php flute cache:clear empties the whole cache. The Achievements module's catalog and showcase work this way.
Page cache for guests
With "Performance Mode" on, the core keeps ready pages for guests for 30 seconds (the setting is in Platform, data retention and files). The core serves such a page before modules load, so neither boot(), nor bootRequest(), nor the module's controller runs.
Code that changes what a guest sees (a published news post, a new product, a new server in the list) calls PageCacheStore::flush(). Without it a guest sees the old page for up to 30 more seconds. Signed-in visitors never get stored pages.
Worker mode
FrankenPHP with FLUTE_WORKER=1 keeps the booted app between requests, and the FLUTE_WORKER constant is then true. Locally php flute serve --worker --workers=4 starts it. A provider's boot() runs once per process and bootRequest() before each request, as covered in Module provider.
Before each request Runtime\RequestScope::reset() returns the process to the state the boot left. Services the container first built during the request are thrown away, and so are routes and listeners from bootRequest(). The core resets its own static properties from a private list, which a module can't join. Nobody but the module cleans up the module's statics and the services built in its boot().
That gives the module these rules:
| Where | Rule |
|---|---|
| registration | whatever depends on the visitor goes in bootRequest() |
a service from boot() | keeps no request, user, session or data read for them |
| a read repeated on one page | goes through RequestMemo::remember() or many(); the code that writes that data calls forget() |
static | nothing that belongs to a request or came from the database |
| a registry that lives from the boot | keeps a class name and builds the object again, as WireRegistry::lazy() and SurfaceRegistry::add() do |
RequestMemo is cleared before each worker request and after each queue job and scheduled task. Inside a transaction it remembers nothing and always reads again, so money and permissions are read fresh before a write. The Quests module keeps quest state for profile cards this way.
If a service from boot() still needs memory between calls, give it a Runtime\RequestMark and forget what it remembered when changed() returns true:
if ($this->mark->changed()) {
$this->seen = [];
}The Rewards module's reward form does this. changed() returns true on the first ask of each request and false outside a request, in the console and in tests.
A worker restarts by itself after 500 requests (FLUTE_WORKER_MAX_REQUESTS), after settings are saved, after a module is installed, updated, enabled or disabled, and after the theme changes. If a module keeps its settings in its own table and holds them in a service from boot(), the other processes won't notice a change: read such settings through cache() with the module tag and drop the tag on save.
Reference
| Method | What it does |
|---|---|
cache()->callback(string $key, callable $callback, int $ttl = 0, array $tags = []) | the cached value, or the function's result stored with the tags |
cache()->set(string $key, mixed $value, int $ttl = 0, array $tags = []): bool | stores a value |
cache()->delete(string $key): bool | removes a key together with its stale copy |
cache()->deleteByTag(string $tag): void | removes every key with the tag |
CacheKeys::moduleTag(string $moduleKey): string | the module tag, module.<key> |
PageCacheStore::flush(): void | drops the stored pages for guests |
RequestMemo::remember(string $scope, int|string $key, callable $load) | one read per request, queue job or scheduled task |
RequestMemo::many(string $scope, array $keys, callable $load, mixed $absent = null): array | the same for a list of keys, $load gets only the missing ones |
RequestMemo::forget(string $scope, int|string|null $key = null): void | forgets a key or the whole scope |
RequestMark::changed(): bool | whether a new request has started since the last ask |
Common mistakes
| Symptom | Cause |
|---|---|
| in worker mode one visitor sees another's name or balance | a service from boot() or a static kept data from the previous request |
| after the module's settings are saved, some pages still show the old ones | the settings live in a service from boot(), and the other processes got no restart |
| a guest sees the old page for another half minute | PageCacheStore::flush() wasn't called after the write |
| after a write the page still shows the old value | the wrong key was deleted: top(5) and top(10) have different keys, so drop by tag |
on a site without debug an error inside the callback() function doesn't show | the stale copy is returned; the error shows when there is no copy or debug is on |