Kai Ole Hartwig

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

Requirements

Frontend worker and request classification

ClassPurpose
Classes/Runtime/FrontendWorkerWorker 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/RequestStateResetClears 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/DatabaseConnectionReuseKeeps 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/PersistentBootstrapWith 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/LeakGuardWith 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/RequestLimitReads MAX_REQUESTS and moves the value by up to 10 % per worker
Classes/Runtime/RequestClassifierPure PHP (no TYPO3 dependencies), classifies requests from $_SERVER into frontend, backend or install. Backend detection by path or host
Resources/Private/Worker/frontend.phpWorker 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

VariableDescriptionDefault
TYPO3_BACKEND_ENTRYPOINTBackend entry point (path or URL)/typo3
MAX_REQUESTSRequests 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 moment500
TYPO3_AUTOLOAD_PATHPath to vendor/autoload.phpauto-detect
DB_REUSEKeep the database connection between requests; 0 closes it after every request1
DB_REUSE_IDLE_TIMEOUTSeconds a kept connection may sit idle. Keep it well below the database's wait_timeout60
DB_REUSE_MAX_AGEMaximum age of a connection in seconds600
DB_REUSE_MAX_REQUESTSMaximum requests per connection1000
DB_REUSE_LIVENESS_CHECKSELECT 1 before the request, so a connection the server dropped is replaced rather than failing the request1
KOH_PERSISTENT_BOOTSTRAPBoot TYPO3 once per worker and start every later request from the recorded boot state0
KOH_WORKER_CACHE_MEMORemember 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 once0
KOH_WORKER_TEMPLATE_PATH_MEMORemember Fluid's file lookups inside code directories per worker. Leave it off for local template work0
KOH_EARLY_HINTS_MEMOSend 103 Early Hints before the render; 0 switches the 103 off1
KOH_REQUEST_TIMINGOne JSON line per frontend request, with bootstrap and application timed apart1
KOH_LAZY_PAGE_LAYOUTResolve the backend layout from page TSconfig on first use instead of on every request. Needs PHP 8.4 and TYPO3 140
KOH_CHASH_REDIRECTRedirect page URLs that carry parameters without the required cHash to the same URL without them, instead of answering 4041
KOH_EDGE_PURGE_BY_TAGDeliver TYPO3's cache tags in the Surrogate-Key header and purge the edge by tag0

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.

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

What a save purges

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\CustomEvent

EarlyHintMiddleware (103 Early Hints)

The PSR-15 middleware announces the resources of a page twice:

  1. 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.
  2. 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”:

KeyDescriptionDefault
enabledSend invalidations to the proxy at all. 0 = no PURGE, no API call, e.g. locally without caddy-proxy1
caddyHostHost of the Souin admin APIlocalhost
caddyPortPort of the Souin admin API2019
protocolhttp or httpshttp
apiEndpointSouin API path/souin-api/souin
apiKeyOptional, sends an X-API-Key header—
enableDebugLoggingDetail logs for cache calls0
httpTimeoutHTTP timeout (seconds)5
invalidateAllSitesCache flush invalidates all sites1
cacheTagsHeaderHeader name for tag invalidationSurrogate-Key
tlsClientCert, tlsClientKeyClient certificate and key (PEM) for mTLS to the proxy. Empty = no client certificate—
tlsCaBundle, tlsVerifyCA 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:

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”:

Troubleshooting

SymptomLikely cause
103 is not visible in curl -vSouin 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 invalidatedCheck 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 saveVersion before 5.6.1: unanchored purges emptied whole hosts. Update
API calls fail with 401Check API key, allow the X-API-Key header in the Caddy config
Next step

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.

Discuss worker mode →

Or email me directly: mail@ole-hartwig.eu