koh/frankenphp — worker mode plus Souin cache for TYPO3.
koh/frankenphp wires TYPO3 into the FrankenPHP worker mode, emits RFC 8297 conformant 103 Early Hints from the AssetCollector and invalidates the upstream Caddy/Souin HTTP cache automatically via PSR-14 events and a DataHandler hook. A backend module exposes cache flushes and key inspection right inside TYPO3.
Six building blocks
- FrankenPHP frontend worker — request classification separates frontend requests (worker mode) from backend and install tool. The worker boots TYPO3 per request and clears what a request leaves behind in static properties and globals. Optionally it boots once per worker and restores the state after the boot before every request.
- The database connection stays open — the worker carries the connection into the next request instead of opening a new one each time, and closes it whenever that is not safe.
- 103 Early Hints — actual RFC 8297 responses via
headers_send(103), sent before the render. The browser fetches stylesheets and fonts while the server is still building the page. - Caddy/Souin cache invalidation — PURGE through Souin's admin API, per URL by its exact cache key or by Surrogate-Key tag.
- DataHandler hooks plus PSR-14 — auto-invalidation on save, workspace publish, move, delete and file changes, limited to the pages affected.
- Backend module — Admin Tools → manual flushes and cache-key inspection.
Requirements
- TYPO3 13.4 or 14.x
- PHP 8.3+
- FrankenPHP 1.x
- Caddy 2.11+ with
cache-handler/ Souin - Extension key
frankenphp, namespaceKoh\FrankenPHP - MIT, source on GitHub
Frontend worker and request classification
| Class | Purpose |
|---|---|
Classes/Runtime/FrontendWorker | Worker loop with frankenphp_handle_request(), fresh TYPO3 bootstrap per request with REQUESTTYPE_FE. An exception nothing in the application caught is answered by TYPO3's exception handler, as without a worker: with the status the exception asks for and TYPO3's error page. Only without a handler does a plain 500 remain |
Classes/Runtime/RequestStateReset | Clears what survives a bootstrap in a long-lived process: the getIndpEnv() cache, singletons, BE_USER/LANG/TYPO3_REQUEST and the error and exception handlers |
Classes/Runtime/DatabaseConnectionReuse | Keeps the database connection open for the next request, saving the TCP and TLS handshake. It is closed on an open transaction (rolled back and logged), after too long idle, past the maximum age or request count, and when a SELECT 1 before the request gets no answer |
Classes/Runtime/PersistentBootstrap | With KOH_PERSISTENT_BOOTSTRAP=1: boots TYPO3 for the first two requests, records the state after the second boot and restores it before every later request |
Classes/Runtime/LeakGuard | With KOH_PERSISTENT_BOOTSTRAP=1: checks every response against its request before it is sent. On a finding the client gets a 503 and the worker ends |
Classes/Runtime/RequestLimit | Reads MAX_REQUESTS and moves the value by up to 10 % per worker |
Classes/Runtime/RequestClassifier | Pure PHP (no TYPO3 dependencies), classifies requests from $_SERVER into frontend, backend or install. Backend detection by path or host |
Resources/Private/Worker/frontend.php | Worker entry point (register as worker with match in the frontend php block, see the Caddyfile below) |
Classes/Runtime/ is excluded from DI auto-registration because this code runs before the TYPO3 container.
Environment variables
| Variable | Description | Default |
|---|---|---|
TYPO3_BACKEND_ENTRYPOINT | Backend entry point (path or URL) | /typo3 |
MAX_REQUESTS | Requests a worker serves before it ends and a fresh one starts. Each worker moves the value by up to 10 % in either direction, so the workers of a pod do not restart at the same moment | 500 |
TYPO3_AUTOLOAD_PATH | Path to vendor/autoload.php | auto-detect |
DB_REUSE | Keep the database connection between requests; 0 closes it after every request | 1 |
DB_REUSE_IDLE_TIMEOUT | Seconds a kept connection may sit idle. Keep it well below the database's wait_timeout | 60 |
DB_REUSE_MAX_AGE | Maximum age of a connection in seconds | 600 |
DB_REUSE_MAX_REQUESTS | Maximum requests per connection | 1000 |
DB_REUSE_LIVENESS_CHECK | SELECT 1 before the request, so a connection the server dropped is replaced rather than failing the request | 1 |
KOH_PERSISTENT_BOOTSTRAP | Boot TYPO3 once per worker and start every later request from the recorded boot state | 0 |
KOH_WORKER_CACHE_MEMO | Remember entries of read-mostly caches this worker has already verified, saving the HMAC check and unserialize(). The cache is still asked on every read, so a flush takes effect at once | 0 |
KOH_WORKER_TEMPLATE_PATH_MEMO | Remember Fluid's file lookups inside code directories per worker. Leave it off for local template work | 0 |
KOH_EARLY_HINTS_MEMO | Send 103 Early Hints before the render; 0 switches the 103 off | 1 |
KOH_REQUEST_TIMING | One JSON line per frontend request, with bootstrap and application timed apart | 1 |
KOH_LAZY_PAGE_LAYOUT | Resolve the backend layout from page TSconfig on first use instead of on every request. Needs PHP 8.4 and TYPO3 14 | 0 |
KOH_CHASH_REDIRECT | Redirect page URLs that carry parameters without the required cHash to the same URL without them, instead of answering 404 | 1 |
KOH_EDGE_PURGE_BY_TAG | Deliver TYPO3's cache tags in the Surrogate-Key header and purge the edge by tag | 0 |
An extension that uses SET SESSION, GET_LOCK() without releasing it, or temporary tables in the frontend would carry that state into the next request. Set DB_REUSE=0 then.
Persistent bootstrap
By default the worker boots TYPO3 for every request: building the container, loading ext_localconf.php and TCA. With KOH_PERSISTENT_BOOTSTRAP=1 it boots for the first two requests and keeps the second boot. The first often runs on cold caches and creates state that must not stay.
Before every later request the worker restores the state after the boot. Services created since then are dropped from the container. The properties of the kept objects go back to their values after the boot. The request id with its CSP nonce, the clock and the time globals are new for each request.
The LeakGuard checks every response against its request: host, language and the page's og:url. On a mismatch the client gets a 503 with Cache-Control: no-store, and the worker ends.
The worker does not reset static properties. MAX_REQUESTS bounds how long they grow.
Measured with the alternation test across two sites and two languages, medians on one worker with SQLite: 20.0 ms per request when booting per request, 6.7 ms with the persistent bootstrap.
Cache invalidation against Caddy/Souin
CaddyCacheService sends PURGE to Souin's admin API ({protocol}://{caddyHost}:{caddyPort}{apiEndpoint}). A PURGE to the public page URL has no effect, and the edge blocks PURGE from outside. There are options for mTLS to the proxy.
- Per URL — key
GET-<host>-<path>$, plus once per hostGET-<host>-/?.+=for variants with a query string - Per tag —
Surrogate-Keyheader. The middleware sets the site identifier on every page and, withKOH_EDGE_PURGE_BY_TAG=1, the cache tags TYPO3 collected for the page - Everything — a flush of the whole Souin store
Why the key is anchored
Souin reads the key as a regular expression, unanchored, and also deletes every key that starts with it. GET-host-/ thus empties the whole host, GET-host-/blog everything below /blog. The $ at the end limits the purge to exactly that page. Escaping with a backslash or brackets does not work: TYPO3 encodes those characters in the URL, Souin does not decode them, and the key matches nothing. Souin still answers 204.
Auto-invalidation
- DataHandler hook
clearCachePostProc— every editorial change: save, workspace publish, move, delete,clearCacheCmd, “flush page” - DataHandler hook
processDatamap_afterDatabaseOperations— direct saves ofpagesandtt_content - PSR-14
CacheFlushEvent— general cache flush, deferred until after the request - Files — deleting, replacing, renaming or moving purges the public URL of the file and its image variants on every host
What a save purges
- The URLs of the page in its own site, one per language the page exists in. Hidden and just-deleted pages count, never the start page in their place.
- The sibling pages only when a field a menu or teaser shows has changed: title, slug, visibility, position, abstract, media and the like. Otherwise the page and its parent.
- Nothing on a save in a workspace. Live has not changed; the publish purges.
- Each page at most once per DataHandler run.
Measured on ole-hartwig.eu, two saves of one blog page: 2104 purges before, 288 of them flushing the whole host, 10 after. For a content element 6 instead of 24.
Optional API key via X-API-Key header.
Purging by tag
A page is delivered under more URLs than the router builds for it: pagination, category routes, feeds, plugin detail routes. Each is its own Souin key, and a URL purge reaches none of them. With KOH_EDGE_PURGE_BY_TAG=1 every response carries its TYPO3 cache tags in the Surrogate-Key header. An editorial change then also purges by the tags the core flushed. Set the switch in two places: where pages are rendered and where editors save.
Custom cache tags
$this->caddyCacheService->invalidateByTags(['custom:tag', 'product:123']);
A tag only works if your pages deliver it in the Surrogate-Key header.
Custom event listener
# Configuration/Services.yaml
services:
Your\Extension\EventListener\CustomCacheListener:
tags:
- name: event.listener
identifier: 'custom-cache-invalidation'
event: Your\Extension\Event\CustomEventEarlyHintMiddleware (103 Early Hints)
The PSR-15 middleware announces the resources of a page twice:
- 103 Early Hints via
headers_send(103), before the render. What a page needs is only known after its render. So the 103 carries what the last render of the same page needed. For a page this worker has not rendered yet, it takes what all pages of the host had in common: usually the base stylesheet and the font. Link:header on the final response with the full list. An edge cache keeps it with the page.
The list is built after the render: from the stylesheets of the AssetCollector and its scripts that block the parser, plus the link elements in the head. Scripts with defer, async or loaded as a module get no preload. They would otherwise be fetched ahead of the stylesheets and the LCP image.
The memory belongs to the single worker and holds 1024 pages. A deployment starts new workers and so starts empty. The 103 is only sent for document navigations with Accept: text/html. Outside a worker there is no 103. KOH_EARLY_HINTS_MEMO=0 switches it off.
Until version 5.11 the 103 went out after the render, together with the final response. The browser gained nothing from it.
Middleware position: before typo3/cms-frontend/timetracker (see Configuration/RequestMiddlewares.php).
Installation and Caddyfile
composer require koh/frankenphp
Caddyfile
your-domain.com {
root * /app/public
# Backend and Install Tool: regular threads, no worker.
@backend path /typo3 /typo3/*
handle @backend {
php
}
handle {
rewrite * /index.php
php {
worker {
file /app/vendor/koh/frankenphp/Resources/Private/Worker/frontend.php
match *
num 4
env TYPO3_BACKEND_ENTRYPOINT /typo3
env MAX_REQUESTS 500
}
}
}
route {
cache {
api {
souin
}
ttl 1h
default_cache_control public
}
}
}
A global worker in the frankenphp block only serves a request when the resolved script is the worker file itself. TYPO3 rewrites every frontend request to /index.php, so that worker would sit idle. That is why it is declared inside the frontend php block and bound with match.
Backend and Install Tool run in regular threads. Set num_threads in the global frankenphp block to the worker count plus what the backend needs.
Extension configuration
In the TYPO3 backend under “Admin Tools → Extension Configuration → frankenphp”:
| Key | Description | Default |
|---|---|---|
enabled | Send invalidations to the proxy at all. 0 = no PURGE, no API call, e.g. locally without caddy-proxy | 1 |
caddyHost | Host of the Souin admin API | localhost |
caddyPort | Port of the Souin admin API | 2019 |
protocol | http or https | http |
apiEndpoint | Souin API path | /souin-api/souin |
apiKey | Optional, sends an X-API-Key header | — |
enableDebugLogging | Detail logs for cache calls | 0 |
httpTimeout | HTTP timeout (seconds) | 5 |
invalidateAllSites | Cache flush invalidates all sites | 1 |
cacheTagsHeader | Header name for tag invalidation | Surrogate-Key |
tlsClientCert, tlsClientKey | Client certificate and key (PEM) for mTLS to the proxy. Empty = no client certificate | — |
tlsCaBundle, tlsVerify | CA bundle to verify the proxy certificate; without a bundle, tlsVerify decides | —, 1 |
Worker reload and troubleshooting
Worker reload without a container restart
OPcache caches middleware code per worker thread. After code changes, typo3 cache:flush --group all alone is not enough — recycle the workers:
# SIGUSR1 to FrankenPHP PID 1
docker exec <httpd-container> kill -USR1 1
frankenphp reload --config /etc/caddy/Caddyfile only reloads the Caddy config, not necessarily the PHP worker threads.
Logging
PSR-3 logger via TYPO3:
- Info — normal cache invalidation operations
- Warning — failed API calls
- Error — exceptions during invalidation
- Debug — request and response details (only with
enableDebugLogging)
A failed PURGE also goes to the container's stderr via error_log(), so it lands where the platform reads logs.
Purge audit
With KOH_CACHE_PURGE_AUDIT=1 the extension writes one JSON line per purge to stderr ("koh_purge_audit":"purge"), plus one when a full flush is scheduled ("full-flush-scheduled", with the reason). Each line names the Souin key, the request or CLI command, backend user and workspace, and the calling code path. Meant for a measurement window, to find out what keeps emptying the edge cache. Without the variable nothing is written.
Backend module
“Admin Tools → Caddy Cache Management”:
- Flush All Cache — invalidates all configured sites
- Flush Site Cache — per site
- Cache Status — overview of the auto-invalidation
Troubleshooting
| Symptom | Likely cause |
|---|---|
103 is not visible in curl -v | Souin swallows the 103 on cache hits. Use Cache-Control: no-cache plus a cache buster in the URL. Also, curl < 8.10 silently hides 103. |
Browser console Refused to apply style from 'https://host/EXT:...' | Pre v4.0.3 — EXT: resolution was not implemented. Update to v4.0.6+. |
| Cache is not invalidated | Check host, port and protocol of the admin API, enable enableDebugLogging. Souin answers every PURGE with 204, even when the key matches nothing: use the purge audit to compare the key sent with key= in the page's Cache-Status header |
| Edge cache is empty right after every save | Version before 5.6.1: unanchored purges emptied whole hosts. Update |
| API calls fail with 401 | Check API key, allow the X-API-Key header in the Caddy config |
Moving TYPO3 to worker mode?
If you want to take TYPO3 into FrankenPHP worker mode, cleanly invalidate the Caddy/Souin cache layer in front of TYPO3, or shave measurable LCP off CSS/JS-heavy pages via 103 Early Hints, get in touch. I coordinate migration, Caddyfile, worker reload pipeline and the backend setup.
Or email me directly: mail@ole-hartwig.eu