cluster-file-backend — TYPO3 cache for Kubernetes, without a shared filesystem.
Run TYPO3 file-based caches safely across Kubernetes pods — without RWX volumes. cluster-file-backend keeps cache payloads pod-local and cache validity cluster-wide. It replaces TYPO3’s FileBackend / SimpleFileBackend for cache workloads, supports tag-based invalidation, and avoids shared filesystem coupling in multi-pod deployments.
- Composer package:
moselwal/cluster-file-backend:^2.8 - Extension key:
cluster_file_backend - TYPO3: 14.3+ (Composer mode only) · PHP: 8.5+ · MIT
TL;DR — Is this right for my setup?
Use this if …
- TYPO3 runs or will run across multiple Kubernetes pods
- no RWX volume exists or is wanted between pods
- cluster-wide tag-based cache invalidation must work reliably
- you want to replace TYPO3’s standard
FileBackendorSimpleFileBackend
Do not use this if …
- you need FAL, fileadmin or a blob store — that is not this package’s scope
- your installation is single-pod — standard
FileBackendis sufficient - PHP < 8.5 or TYPO3 < 14.3 is in use
Migration effort
One-time setup: register the metadata cache, rewrite the cache configurations, mount an emptyDir. No TYPO3 core changes, no application code changes.
Recommended metadata backend
Production: moselwal/keyvalue-store with KeyValueBackend (Valkey/Redis, sub-ms latency, taggable). Getting started without an extra dependency: TYPO3 Core’s Typo3DatabaseBackend.
Packagist
Package: packagist.org/packages/moselwal/cluster-file-backend
composer require moselwal/cluster-file-backend:^2.8
GitHub
v2.8 · TYPO3 14.3+ · PHP 8.5+
Source code, issues and changelogs. MIT-licensed.
Three-layer storage and architecture
┌─ FrankenPHP worker RAM ─────────────────────────────────────────┐
│ OPcache (compiled PHP code) → PhpFrontend .php files │
│ Payload L1 (decompressed bytes) → VariableFrontend caches │
│ Metadata L1 (CacheMetadata objects) → all caches │
└─────────────────────────────────────────────────────────────────┘
▲
┌─ Pod-local emptyDir ──────────────────────────────────────────┐
│ /<localPath>/<shard>/<sha256>[.php] │
│ • VariableFrontend: 1-byte marker + compressed bytes │
│ • PhpFrontend: plain-text PHP with .php suffix │
│ → source of truth for payload bytes │
└─────────────────────────────────────────────────────────────────┘
▲
┌─ Metadata cache (Valkey / DB) ─────────────────────────────────┐
│ ~300-byte records: { hash, checksum, lifetime, tags, state } │
│ → source of truth for cluster-wide cache validity │
│ → no PHP code, no payload bytes │
└─────────────────────────────────────────────────────────────────┘This package knows nothing about Redis/Valkey/KV stores. It only speaks the TYPO3 cache API and delegates cluster persistence to a TYPO3 cache backend of your choice.
TYPO3 Cache API → ClusterFileBackend
│
├─► Metadata cache (a second TYPO3 cache frontend;
│ backend is your choice: Typo3DatabaseBackend,
│ KeyValueBackend, MemcachedBackend, …)
│
└─► Local payload store (pod-local, emptyDir)
What it is
- No RWX volume required between pods
- Central cache validity via the TYPO3 cache API
- Deterministic re-materialisation via sha256 hash validation
- Cluster-wide tag-based invalidation (via TYPO3
TaggableBackendInterface) - Garbage collection via CLI (
clusterfilebackend:gc), delegated to the metadata cache backend - Deployment-time warm-up via CLI (
clusterfilebackend:warmup) and a listener on TYPO3’sCacheWarmupEvent
What it is not
- Not a replacement for TYPO3 FAL, fileadmin, the TYPO3 core code cache (
var/cache/code/corestays in the image), a session store, a generic blob store or a distributed filesystem - Carries no Redis/Valkey knowledge — install a TYPO3 cache backend for it (e.g. the
KeyValueBackendfrommoselwal/keyvalue-store) and pointClusterFileBackendat it viametadataCacheIdentifier
Requirements
- TYPO3 14.3+ (Composer mode only, no
ext_emconf.php, no classic mode) - PHP 8.5+
- Composer package
moselwal/cluster-file-backendfrom^2.8, extension keycluster_file_backend, namespaceMoselwal\Typo3ClusterCache\ - Licence MIT
Planning a TYPO3 Kubernetes migration? I can review your cache, storage and deployment architecture before it becomes an operations problem. Get in touch →
Setup prerequisites — the one-time steps
The package intentionally does not register any caches automatically. Hostnames, ports, TLS, paths are inherently site-specific. The steps below are a one-time setup.
Five required steps
- Composer install:
composer require moselwal/cluster-file-backend:^2.8 - Provide a cluster-capable cache backend for metadata. Out of the box, the default uses TYPO3 Core’s
Typo3DatabaseBackend— works without extra dependencies as long as the database is reachable from every pod (Galera, RDS Multi-AZ, …). For higher performance, installmoselwal/keyvalue-storeand use itsKeyValueBackend. - Register a TYPO3 cache frontend (convention:
cluster_meta) that holds the metadata. - Reconfigure the file-based TYPO3 caches (
pages,pagesection,rootline,imagesizes,assets,hash) to useClusterFileBackendand referencecluster_metaviametadataCacheIdentifier. - Mount a pod-local
emptyDirat/app/var/cache/cluster/(or whereverlocalPathpoints).
What the package ships
- Default configuration without further dependencies: metadata in the database, payloads in the cluster file cache. It works on any TYPO3 installation.
Configuration/Example/cache-configurations.example.php - Configuration for Redis/Valkey (optional): the faster variant with
moselwal/keyvalue-store.Configuration/Example/cache-configurations-redis.example.php - JSON Schema for the options: the backend validates its options when it is created. A misconfiguration raises an
InvalidCacheExceptionthat names the offending field.Configuration/Backend/ClusterFileBackend.options.schema.json - CLI commands:
clusterfilebackend:gcandclusterfilebackend:warmup.Configuration/Commands.php - Event listener: it hooks into TYPO3’s
CacheWarmupEvent, sobin/typo3 cache:warmupwarms the cluster cache as well.Configuration/Services.yaml - DI bindings: auto-discovery for
MetricsPort,ClockPortandCompressorPort.Configuration/Services.yaml
Constructor validation
The ClusterFileBackend constructor validates options against a JSON schema. Mandatory fields (otherwise InvalidCacheException): localPath (absolute path), metadataCacheIdentifier (name of the metadata cache frontend), namespace.environment (prod, staging, testing or development) and namespace.instance (slug [a-z0-9-]{1,64}). If the configured metadataCacheIdentifier is not registered as a TYPO3 cache, the constructor fails immediately with a message naming the config path — no silent failure on first set().
| Option | Default | Meaning |
|---|---|---|
compression | zstd | zstd | gzip | none. Forced to none for PhpFrontend caches. |
serializer | igbinary | igbinary | php. Switching invalidates existing entries. |
defaultLifetimeSeconds | 3600 | TTL when the caller passes null. Minimum 1 (schema rejects 0). |
maxPayloadBytes | 10485760 (10 MB) | Writes larger than this are rejected with InvalidDataException. Also the upper bound for decompressed reads (zstd-bomb mitigation). |
minCompressedBytes | 1024 | Payloads below this size are stored uncompressed (1-byte marker 0x00). Avoids the fixed cost of zstd_compress/gzdeflate on tiny values. 0 = always compress. |
payloadL1MaxEntries | 32 | Maximum entries in the request-scoped payload L1. 0 disables the payload L1 (metadata L1 stays active). LRU eviction. |
payloadL1MaxBytes | 4194304 (4 MB) | Soft memory budget for the payload L1. Entries that would push the total above this are evicted in insertion order; a single payload larger than this bypasses the L1 entirely. 0 = no byte budget. |
backendVersionEnvVar | IMAGE_TAG | Env var carrying the deploy identifier. Folded into every payload hash — every deploy gets a fresh path tree. Override for CI conventions like CI_COMMIT_SHA. |
Configuration — quick start and variants
Quick start (zero extra dependencies)
Copy the contents of vendor/moselwal/cluster-file-backend/Configuration/Example/cache-configurations.example.php into your config/system/settings.php (or additional.php) and adjust environment, instance and localPath to your deployment. This example uses TYPO3 Core's Typo3DatabaseBackend for the metadata cache — cluster-safe when your database is clustered.
Redis/Valkey variant
For sub-millisecond metadata latency, copy Configuration/Example/cache-configurations-redis.example.php instead. It uses the KeyValueBackend from moselwal/keyvalue-store with optional TLS and Sentinel support.
Manual setup
Step 1: Define a TYPO3 cache frontend that persists metadata. Any backend that implements TaggableBackendInterface (for flushByTag) works.
$GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']['cluster_meta'] = [
'frontend' => \TYPO3\CMS\Core\Cache\Frontend\VariableFrontend::class,
'backend' => \TYPO3\CMS\Core\Cache\Backend\Typo3DatabaseBackend::class,
'options' => [],
'groups' => ['system'],
];
Step 2: Point ClusterFileBackend at the metadata cache — for all file-based caches at once.
foreach (['pages', 'pagesection', 'rootline'] as $cacheName) {
$GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations'][$cacheName] = [
'frontend' => \TYPO3\CMS\Core\Cache\Frontend\VariableFrontend::class,
'backend' => \Moselwal\Typo3ClusterCache\Infrastructure\Cache\Backend\ClusterFileBackend::class,
'options' => [
'localPath' => '/app/var/cache/cluster/' . $cacheName,
'metadataCacheIdentifier' => 'cluster_meta',
'namespace' => [
'environment' => 'prod',
'instance' => 'website-a',
],
],
'groups' => ['pages'],
];
}Kubernetes deployment, warm-up and garbage collection
Pod volume for payloads
volumes:
- name: cluster-cache
emptyDir: { sizeLimit: 2Gi }
volumeMounts:
- name: cluster-cache
mountPath: /app/var/cache/cluster
Deployment-time warm-up
After a rolling deploy each new pod should typically verify that it can reach the metadata cache and that its localPath is writable before it starts serving traffic. Trigger the warm-up explicitly:
./vendor/bin/typo3 clusterfilebackend:warmup \
--namespace=cfb:prod:website-a:pages \
--namespace=cfb:prod:website-a:pagesection \
--namespace=cfb:prod:website-a:rootline
The command emits one JSON line per namespace and exits non-zero if any namespace fails its health checks. Hook it into your readiness/startup probe or a post-deploy job.
Alternatively, run TYPO3's standard warm-up — the event listener hooks in automatically:
./vendor/bin/typo3 cache:warmup
Garbage collection as a CronJob
apiVersion: batch/v1
kind: CronJob
metadata:
name: clusterfilebackend-gc-pages
spec:
schedule: "*/15 * * * *"
concurrencyPolicy: Forbid
jobTemplate:
spec:
template:
spec:
containers:
- name: typo3-cli
args: ["clusterfilebackend:gc", "--namespace=cfb:prod:website-a:pages"]
Internal architecture
DDD 4-layer (Domain → Application → Infrastructure → Presentation), enforced via deptrac. The only outside interface for “central truth” is MetadataCachePort, implemented by the Typo3MetadataCache adapter, which accepts any TYPO3 FrontendInterface.
Cluster consistency — what happens on cache clear?
Frequently asked: “When an editor clicks Clear all caches in the TYPO3 backend, how do we make sure all pods see it?”
Short answer: the pod handling the click clears the central metadata cache. All other pods see it on their next get() because they query the central metadata cache, not their local filesystem. No pod-to-pod sync needed, because metadata truth never lives on a pod.
Detailed flow
Pod A: TYPO3 backend “Clear all caches” / editor saves page /
`bin/typo3 cache:flush`
│
▼
ClusterFileBackend::flush() on pod A
│
▼ delegates to metadata cache frontend (e.g. cluster_meta)
$metadataCache->flush()
│
▼ TYPO3 cache API calls the configured backend
KeyValueBackend / DatabaseBackend / MemcachedBackend → flush()
│
▼ happens SERVER-SIDE (Redis FLUSHDB, SQL TRUNCATE, Memcached flush_all)
All pods see the empty metadata immediately
On the next get(id) on any pod:
$metadata = $this->metadataCache->get($identifier); // → null (cache flushed)
if ($metadata === null) {
// cache_miss_total{reason=no-metadata}++
return null; // ← pod does NOT consult its local FS
}
Verified by the test suite
Tests/Unit/Deployment/CrossPodFlushTest.php contains five tests that prove this: flush() propagates to pod B immediately, no sync; flushByTag() invalidates only matching entries; the local file survives the flush as a harmless orphan; re-write after flush re-establishes consistency; flush works for arbitrary numbers of pods (no scaling assumption).
Complexity — why it is faster in a cluster
Let C be the set of all cache entries and Ct ⊆ C the subset of entries tagged with t. Write n := |C| for the total count and m := |Ct| for the count of t-tagged entries — with m ≤ n. This makes the difference precise: ClusterFileBackend sits in a different complexity class, not merely at a smaller argument, because it uses backend-native algorithms and does not multiply by a pod factor.
Let P denote the number of pods and e ≤ n the number of expired entries.
| Operation | TYPO3 Core FileBackend | ClusterFileBackend | Speedup |
|---|---|---|---|
flushByTag | Θ(n) per pod — DirectoryIterator across every cache file, 2× file_get_contents per file | Θ(m) — backend reads the tag index directly | Different complexity class plus tag indexes |
findIdentifiersByTag | Θ(n) per pod | O(m) | same |
collectGarbage | Θ(n) per pod, total Θ(n · P) | O(1) active (Redis TTL auto-expire) or O(e) server-side (DB) | Backend-native plus cluster-once |
flush | Θ(n) per pod, total Θ(n · P) | Θ(n) once server-side | Pod factor disappears, constants ~100–1000× smaller |
Concrete example
n = 10,000 cache entries, of which m = 100 are tagged site_1, P = 5 pods.
| Setup | File reads | unlink calls | Round-trips |
|---|---|---|---|
Core FileBackend on flushByTag('site_1') | 2 · n = 20,000 | m = 100 | ≈ 2n + m = 20,100 local FS I/O per pod |
| ClusterFileBackend (Redis) | 0 | 0 | 2 (SMEMBERS + pipeline DEL) once cluster-wide |
Measured against SimpleFileBackend
The load is a synthetic request with 25 TypoScript payloads (4.8 MB in total), 150 Fluid templates and 40 variable entries, each time with a fresh CacheManager. A cold request writes everything, a warm one reads everything. cluster-file-backend runs with the options we also use in production, crossRequestMetadataMemo and crossRequestPhpVerification. The measurements were taken in the PHP 8.5 production image on aarch64 with a local Valkey; the figures are the median of three runs.
With open_basedir | SimpleFileBackend | cluster-file-backend v2.8.1 | cluster-file-backend v2.8.2 |
|---|---|---|---|
| warm request (cache filled) | 35.1 ms | 46.3 ms | 34.7 ms |
| cold request (cache empty) | 92 ms | 357 ms | 208 ms |
Without open_basedir | SimpleFileBackend | cluster-file-backend v2.8.1 | cluster-file-backend v2.8.2 |
|---|---|---|---|
| warm request (cache filled) | 25.5 ms | 34.4 ms | 30.8 ms |
| cold request (cache empty) | 62.5 ms | 326 ms | 165 ms |
Warm, v2.8.2 reads as fast as SimpleFileBackend, even though it checks every code cache against a checksum and fetches its metadata from Valkey; thanks to the metadata memo that takes three round trips per request instead of 217. Cold, it remains more expensive, because every payload is hashed and its metadata written to the cluster. That is the price of every pod seeing the same state, and it is paid after a deploy or a cache clear, not on every request.
Without open_basedir every backend gets faster, because only then does PHP use its realpath cache; warm, SimpleFileBackend then leads by 5 ms. Whether open_basedir actually protects your platform depends on what lies outside the paths it allows. If you switch it off, read certificates and secrets from Kubernetes through stable paths, or the realpath cache will hold on to paths the kubelet deletes on every update.
Rolling deploys with version skew
During a rolling deploy old and new pods serve traffic simultaneously. ClusterFileBackend preserves correctness in every skew scenario, but two cases change the performance profile during the deploy window — worth understanding.
A) Application code with changed cache layout
If the new image writes a different payload shape for the same cache identifier (extra fields, changed serialised classes, modified value objects) and you do not explicitly invalidate, the following happens:
- Pod-old writes payload v1 → metadata holds hashv1.
- Pod-new reads, sees hashv1, has no local blob → blob-miss → TYPO3 frontend asks the caller to rebuild → pod-new writes payload v2 → metadata is overwritten with hashv2.
- Pod-old reads, sees hashv2, has no local blob → blob-miss → rebuilds v1 → metadata reverts to hashv1.
- Hash thrashing for the duration of the rolling deploy.
The bigger risk is silent layout drift: if pod-new can technically deserialise pod-old’s bytes but the resulting object is wrong (missing fields, old enum cases, removed properties), the user sees stale or corrupt content. PHP’s unserialize does not verify class shape beyond the class name.
Recommendation: tie cache identity to the deploy
So that every release automatically gets a new BackendVersion and stale entries become unreachable, ClusterFileBackend reads an environment variable — by default IMAGE_TAG — and folds its value into the payload hash via crc32. In your deployment manifest:
# Helm values, Kustomize patch or plain Pod spec
env:
- name: IMAGE_TAG
value: "{{ .Values.image.tag }}" # or $CI_COMMIT_SHA, release semver, ...
You can override the variable name per cache if your CI convention differs:
'options' => [
'localPath' => '/app/var/cache/cluster/pages',
'metadataCacheIdentifier' => 'cluster_meta',
'namespace' => ['environment' => 'prod', 'instance' => 'site'],
'backendVersionEnvVar' => 'CI_COMMIT_SHA',
],
When the variable is unset or empty, the backend falls back to the package-internal BackendVersion::current() — safe for local development. In production wire the variable explicitly to get deploy-scoped invalidation.
Alternative invalidation strategies
- Pre-flush via
clusterfilebackend:warmupin the deploy pipeline — drains stale entries before the new image takes traffic. - Rename the cache identifier (e.g.
pages→pages_v2incacheConfigurations). Heavy hammer, only for larger schema reworks.
For non-breaking layout changes (additive, ignored by the old code) you can accept the temporary thrashing — correctness is preserved.
B) PHP major/minor version change
The identity hash includes PHP_MAJOR.PHP_MINOR (Classes/Application/Hash/ComputePayloadHash.php). PHP 8.4 ↔ 8.5 (or any other major/minor jump) automatically produces divergent hashes — no manual action needed. Correctness guaranteed. The cost is the same thrashing as in (A) for the duration of the rollout. Watch blob_miss_total in Prometheus; a sustained spike beyond the deploy window indicates the version skew did not converge (e.g. a pod stuck in the old image).
PHP patch updates (8.5.4 → 8.5.5) do not invalidate — only major and minor are in the hash.
Operational recommendation
- Patch updates (igbinary patch, PHP patch, app bug-fix without cache layout change): plain rolling deploy, no extra steps.
- Minor and major updates (PHP minor bump, BackendVersion bump, cache-layout change): rolling deploy stays safe but expect a blob-miss spike. For zero-degradation deploys, run a
Recreatestrategy or pre-flush via the warm-up command.
Operational requirements
Pod clock synchronisation
Cache lifetimes are evaluated against each pod’s local clock. If pods disagree on wall-clock time by more than a few seconds, a pod with a fast clock treats entries as expired earlier than peers — correctness is preserved but performance degrades. In Kubernetes this is normally a non-issue (nodes synchronise via chrony/systemd-timesyncd). Sanity check during incidents:
kubectl exec deploy/typo3 -- date -u
A skew above ~30 seconds across pods is the threshold where blob_miss_total and cache_miss_total{reason=expired} start to drift visibly in Prometheus.
Metadata cache availability
The metadata cache (Redis/Valkey/DB) is the single source of truth. When it is unreachable:
- Reads degrade gracefully to cache misses; the TYPO3 frontend triggers caller rebuilds. The application keeps serving, but upstream load (DB queries, render time) spikes.
- Writes surface the underlying exception — intentional, so outages are not swallowed silently.
Compatible metadata cache backends
The metadata cache must use a backend that implements TaggableBackendInterface; otherwise flushByTag becomes a no-op. Verified backends:
| Backend | Taggable | Notes |
|---|---|---|
Typo3DatabaseBackend | ✅ | Zero-dependency default |
KeyValueBackend (moselwal/keyvalue-store) | ✅ | Redis/Valkey, recommended for high-traffic |
MemcachedBackend (TYPO3 Core) | ❌ | Does not support tags — incompatible |
RedisBackend (TYPO3 Core) | ❌ | Not taggable — use moselwal/keyvalue-store instead |
IMAGE_TAG consistency across all pods
Every container pointing at the same metadata cache backend must see the same IMAGE_TAG (or whichever variable is set via backendVersionEnvVar). If the web pod runs IMAGE_TAG=1.2.3 and a worker/cron pod still runs IMAGE_TAG=1.2.2, the two compute different BackendVersion values and treat each other’s writes as blob-misses. Symptom: persistent thrashing in mixed deployments. Helm/Kustomize tip: extract the tag into a single value and reference it from every Pod spec.
Y2K38 limitation for unlimited-lifetime entries
Lifetime::unlimited() maps to expiresAt = 2147483647 (mirrors TYPO3 Core’s Typo3DatabaseBackend::FAKED_UNLIMITED_EXPIRE). On 2038-01-19 03:14:07 UTC that timestamp becomes “now” and any entry stored as unlimited will be considered expired. Practical impact before then: none.
crc32-based BackendVersion folding
BackendVersion::fromString(…) folds the deploy identifier via crc32 to a 32-bit integer. Birthday collisions occur at ~77 000 unique deploy identifiers — extremely unlikely under realistic release cadence. If you regularly cycle through thousands of distinct identifiers, prefer a stable, human-readable semver string over raw commit SHAs.
Common pitfalls
localPathmust be writable. With a read-only/appimage, mountemptyDir/tmpfsat that path.- Identical container image across all pods. Different PHP or igbinary versions produce divergent hashes → permanent blob-misses. Major versions are enough — patch versions are not in the hash (since v1.0.1).
- Wire
IMAGE_TAG(or your equivalent) in production. Without it the backend uses a package-internal version constant that does NOT change across deploys — breaking cache-layout changes can then silently serve stale or corrupt content. See “Rolling deploys with version skew”. metadataCacheIdentifiermust be registered before any cache that usesClusterFileBackend. TYPO3 loadscacheConfigurationsin array insertion order — definecluster_metafirst.- Composer mode only. No
ext_emconf.php, no classic mode.
What’s new from v2.2 to v2.8
PhpCapableBackendInterface (v2.2)
Since v2.2 ClusterFileBackend also implements PhpCapableBackendInterface — a single backend serves both VariableFrontend caches (pages, extbase, …) and PhpFrontend caches (typoscript, fluid_template). The payload store appends a .php suffix for PhpFrontend caches so OPcache can ingest the files directly. Compression is forced to none for PHP code. Cluster coherence comes from the BackendVersion-folded hash path — every deploy produces a new path, OPcache cools automatically, no opcache_invalidate() needed.
One-byte compression marker (v2.2)
0x00 = uncompressed, 0x01 = zstd, 0x02 = gzip. The reader picks the decompressor from the marker; the writer can mix codecs (e.g. skip-compress for tiny payloads, zstd for the rest).
Skip-compress for small payloads (v2.2)
Option minCompressedBytes (default 1024): payloads below this threshold are stored uncompressed. Avoids the fixed cost of gzdeflate/zstd_compress on tiny values. 0 = always compress.
Request-scoped metadata L1 (v2.2)
has() / get() / remove() hit an in-memory map of recent CacheMetadata lookups. Identical identifiers in the same request skip the Valkey/DB round-trip — ~200× faster on repeated has() calls.
Request-scoped payload L1 (v2.3)
Fully decoded payloads are cached in RAM with LRU (default cap: 32 entries / 4 MB). Repeated get() calls on a hot identifier drop from ~90 µs to ~0.5 µs — 9–20× faster than SimpleFileBackend on every repeated read. Controlled via payloadL1MaxEntries and payloadL1MaxBytes. PhpFrontend caches skip the payload L1 (OPcache is the better in-memory representation).
Prometheus counter cache_l1_hit_total (v2.3)
Alongside cache_hit_total and cache_miss_total, the new counter cache_l1_hit_total makes the three-layer hit distribution visible in production. Alert on cache_miss_total{reason=metadata-error} for early detection of metadata cache outages.
One metadata memo for reads and writes (v2.6.38)
Until then only the has() probe remembered its metadata. Reads and writes went straight to Valkey or the database, and set() threw the entry away again. A cold code cache cost three round trips for one identifier: probe, rebuild, probe again. Now every reader and writer of one backend instance shares one memo for the duration of the request. set() remembers what it wrote, flushes empty the memo.
Metadata across requests (v2.7, optional)
An uncached page render reads some 40 metadata entries, each once per request. That is how a pod learns about the other pods' writes. With the option crossRequestMetadataMemo a request reads a single value instead: the generation of the metadata store. As long as it stays the same, metadata comes from a memo in the PHP process, across requests in a FrankenPHP worker.
- Every change through this package writes a marker first and a new generation afterwards. That happens always, with the option off as well.
- A change on pod B is visible on pod A at A's next request.
- If the generation is marked, missing or unreadable, the pod reads entry by entry as before.
- At most 2048 entries per metadata cache and process, about 3 MiB, and at most five minutes old.
The gain needs a process that serves many requests. In PHP-FPM, classic mode or on the CLI the memo starts empty every time.
Switching it on in two steps: first bring v2.7 with the option off to every pod, worker and cron job. Pods on an older version change metadata without touching the generation. Only once none of them runs, switch the option on. To roll back to an older version, switch the option off first.
New counters: metadata_memo_check_total (reuse, reset, bypass), metadata_memo_hit_total, metadata_memo_miss_total, metadata_memo_full_total and metadata_generation_publish_total.
Less work per request (v2.8.2)
- SHA-256 through OpenSSL. Every write and every full verification hashes the whole payload. With
ext-opensslloaded, the backend uses the CPU's SHA instructions and needs 1.0 ms instead of 15.9 ms for 2.2 MB. Without OpenSSL it keeps usinghash(), which produces the same checksum, so pods with and without OpenSSL can share one cache. - One hash pass for PHP caches. Because the context now follows the payload (
BackendVersion3), a single pass is enough for a PHP cache's checksum. Even without OpenSSL, 2.2 MB now take 10.6 ms instead of 21.6 ms. - Options validated once per process. TYPO3 rebuilds every cache backend on each request, in a FrankenPHP worker as well. Option validation therefore runs only once per option set and process, at 9.5 µs instead of 164 µs per backend.
- One
lstat()per require. A single call now returns file type, fingerprint and modification time, where four were needed before. Symlinks are still refused on every call, now including those that point nowhere. - Nothing rewritten that has not changed. When a
set()stores the same bytes with the same tags and format for an entry that never expires, as every PHP cache entry does, the metadata is left untouched. That costs a single read instead of five round trips and creates no new generation that would empty every worker's metadata memo. The new counterrepair_unchanged_totalshows how often this happens.
Two seconds' margin for cross-request verification (v2.8.2)
With crossRequestPhpVerification the backend remembers which code-cache files it has already verified and recognises them by device, inode, size and ctime. The kernel, however, stamps file times from a coarse clock that can lag behind the wall clock, so a file written just after a second boundary may still carry the previous second. Up to v2.8.1 a one-second margin was considered enough; since v2.8.2 the backend only records a fingerprint once the ctime is at least two seconds old. The gap came to light on a CI runner.
Entry and generation in one step (v2.8.3)
If you use moselwal/keyvalue-store 4.9.0 or later as the metadata backend, a set() writes the entry and the new generation in a single atomic step on the Valkey server, where three steps were needed before. Pods on older versions can keep running alongside; while one of them writes, both sides read the metadata entry by entry. There is nothing to configure.
Running TYPO3 on Kubernetes?
If you run TYPO3 on a K8s cluster without an RWX volume, or want to take an existing FileBackend setup into multi-pod operation, cluster-file-backend is the right primitive. Get in touch for architecture advice, migration or platform setup.
Or email me directly: mail@ole-hartwig.eu