CakePHP 5.4 in FrankenPHP worker mode, done properly
FrankenPHP's worker mode boots your application once and then serves request after request from the same PHP worker thread. I'll assume you have read that page; this article is about what happens when the application is CakePHP.
CakePHP has no worker runtime of its own. The only FrankenPHP support in core is bin/cake server --frankenphp, a
development launcher that runs frankenphp php-server: classic mode, one full boot per request, no --worker. And
CakePHP, like most PHP code, assumes that every request starts with a clean slate. Static registries, cached Table
objects and the dependency injection container all rely on PHP discarding all state at the end of each request.
So worker mode is a deal. You get real speed, and you pay for it with state that outlives the request. This article covers both sides on a small but realistic app, and shows how to keep the speed without the bugs. All the code, the soak test, the leak detector and the benchmark scripts are in the demo repository.
The demo is a multi-tenant feature-flag service:
GET /api/flags/{tenant}?user=&country=&plan=returns every flag of a tenant, evaluated for one caller. This is the hot path: a tiny JSON response at a high request rate.POST /webhooks/{tenant}changes a flag. It is signed with an HMAC of the body and a secret per tenant.GET /admin/flagsis an HTML page that lists all tenants and their flags through the ORM.
Flags have targeting rules (a percentage rollout, segments such as country in [PL, DE] or plan = pro) stored as
JSON and compiled into closures.
Why: what worker mode gives a CakePHP app
Boot once. In classic mode every request runs config/bootstrap.php, loads plugins, builds the container,
registers event listeners, builds the middleware queue and loads the routes. OPcache does not save you from this: it
caches compiled code, not the work that code does. In worker mode all of it happens once per worker, and, if you keep
them, so do the routes; that turns out to be harder than it sounds.
Connections reused. The database connection opened by one request stays open for the next, even with
'persistent' => false (the skeleton's setting): no TCP handshake, TLS setup or database authentication per
request. Each new connection to a remote or managed database costs network round trips and authentication. Classic
mode can get the same with persistent PDO connections, and CakePHP's Redis cache engine is persistent by default in
both modes.
State kept on purpose. This is the one benefit that does not exist at all in classic mode. The demo compiles a tenant's targeting rules into closures once per worker and keeps them in memory, so the hot path runs one cheap query for the tenant row and evaluates the closures. What this compiled-flag cache saves on every request is a flags query and the entity hydration; the compilation is a smaller share.
The numbers, measured on the demo: same FrankenPHP image for both modes, 2 PHP threads serving requests in each,
DEBUG=false, ApacheBench at concurrency 4, median of three runs of 3,000 requests. They are local Docker numbers
(WSL2), not production capacity: compare the two rows of an endpoint with each other, not with your servers.
| Endpoint | Classic (req/s) | Worker (req/s) | Gain | p99 classic → worker |
|---|---|---|---|---|
| Flag API | 499 | 2,297 | 4.6x | 12 → 3 ms |
| Admin page (ORM, 100 flags, HTML) | 314 | 658 | 2.1x | 19 → 9 ms |
| Webhook (transaction, row lock) | 408 | 642 | 1.6x | 14 → 8 ms |
The gain follows the share of each request that is startup work. The flag API does almost nothing per request, so skipping the boot is most of its cost, and its gain also includes the compiled-flag cache, which classic mode cannot have. The admin page and webhook gains come from startup work alone: boot, routes and the database connection. The webhook spends most of its time in a database transaction, which worker mode cannot make faster. If your heaviest endpoints look like the webhook, weigh a gain of that size against the risk below.
Cost: what outlives a request in CakePHP
Classic PHP is shared-nothing: nothing you write to a static property, a registry or a singleton can reach the next request. Worker mode removes that guarantee and nothing in CakePHP replaces it. Here is what outlives a request, and what the reset layer (see "Fix: reset, or keep on purpose") does about it.
Router: the route collection, the current request, the request context (host, base path), URL filters.Router::setRequest()only fills the host into the request context if it is not set yet, so a leftover context builds URLs for an earlier request's host. Reset to its after-boot state.TableLocator: every Table instance, with its behaviors, associations and their runtime configuration. Code that changes a Table at runtime changes it for every later request. Tables cleared, locator config kept.Configure: runtime writes, such as a tenant override, stay for the next request. Restored.- The I18n locale: a locale set for one request stays for the next. Restored.
Inflector: its cache keeps every string it has inflected. With fallback routes, every distinct URL path adds entries, without limit. Cache restored to its after-boot state.ConnectionManager: open connections, which is good, and open transactions, which is not: a request that dies halfway can leave one for the next request to commit. Rolled back.EventManager::instance(): a global listener added during a request is added again on the next one. Not reset: add global listeners at boot only; the leak detector reports listener growth.- Cache and Log: configured at boot, which is fine. Not reset, by design.
- The session: closed after every request, as in classic mode. If your app uses sessions, include session flows in your soak test.
- The DI container and every service registered as shared. Kept; see below for the catch.
- Static properties in your own code and in every plugin and library. This is the hardest part, because the framework cannot reset what it does not know about.
Most of these failures throw nothing. They show up as wrong data, slower requests or growing memory.
Three more things in the 5.4.4 source matter in a worker.
You cannot loop on Server::run(). It calls bootstrap(), middleware() and pluginMiddleware() on every call.
Call it per request and you rerun plugin bootstrap, event registration and the middleware build per request, which
is exactly what worker mode exists to avoid.
Plugin routes are connected again on every request. RoutingMiddleware::process() calls loadRoutes() on every
request. BaseApplication::routes() only loads config/routes.php while the Router is empty, so your own routes are
safe, but pluginRoutes() has no such guard. In a worker, every plugin that has routes adds them to the collection
again on each request, so the collection and memory keep growing. In development, with DebugKit loaded, that is 14
more routes per request, forever; in production, any plugin with routes does the same.
The container keeps every request (with the default container). This one is easy to miss in the code and
obvious under load. BaseApplication::handle() adds ServerRequest and ContainerInterface definitions to the
container on every request, and ControllerFactory::create() adds a ComponentRegistry. Unless App.container is
set to 'cake', CakePHP 5.4's container extends League Container 5.2, whose add() appends a definition instead of
replacing one, and whose lookups scan the list and return the first match. In classic mode nobody notices. In a
worker the container lives on, so:
- memory grows, because every request object is kept;
- every container lookup scans a longer list, so each request is slower than the one before. On the flag API, in consecutive runs of 1,000 requests, the worker served 1,348 requests/s in its first 1,000 and 116 in its eighth 1,000, against 2,300–2,460 with the fix;
$container->get(ServerRequest::class)returns the worker's first request, andget(ComponentRegistry::class)the first request's registry, for as long as the worker lives.
The fix for the default container is one line at boot, shown in the worker runtime below. CakePHP 5.4's own
container ('App.container' => 'cake') replaces definitions by id, so it does not need it.
Two patterns that work in classic mode and leak in a worker
Both are correct in classic mode, where one request serves one tenant, and both are what the demo's FlagEvaluator
and TenantSecretCache would look like written the obvious way. Neither is in the demo.
FlagEvaluator::evaluate() with a cache keyed by the tenant's flags version, but not by the tenant:
public function evaluate(Tenant $tenant, array $context): array
{
$key = (string)$tenant->flags_version;
$this->compiled[$key] ??= $this->compileTenant($tenant);
return array_map(static fn(Closure $flag): bool => $flag($context), $this->compiled[$key]);
}
In the demo, both tenants start at version 1, so in a worker the second tenant is served the first tenant's flags. No exception, just the wrong answer.
TenantSecretCache::get() with the webhook secret memoized in a static property, also without the tenant:
private static ?string $cache = null;
public static function get(int $tenantId): string
{
if (self::$cache === null) {
self::$cache = TableRegistry::getTableLocator()->get('Tenants')->get($tenantId)->webhook_secret;
}
return self::$cache;
}
In a worker, the next tenant's webhook is checked against the first tenant's secret. That is a security bug, not just wrong data: it rejects the second tenant's valid webhooks and accepts webhooks for it signed with the first tenant's secret, so anyone with one tenant's secret can change another tenant's flags. (The demo's secret cache is demo-only: a real app would read the secret from the tenant entity the controller has already loaded.)
With these two snippets in place, one run of the soak test (bin/cake worker_soak http://frankenphp-worker --rounds 5 --workers 2) caught both in its first round: five rounds over two tenants gave 15 wrong flag answers and 5 rejected
webhooks out of 80 requests.
Fix: the worker runtime
The entry point, webroot/frankenphp-worker.php, trimmed (the real file also switches to a development runtime when
the leak detector or the worker-id header is on):
<?php
declare(strict_types=1);
use App\Application;
use App\Worker\RequestCycle;
use App\Worker\WorkerRuntime;
require dirname(__DIR__) . '/vendor/autoload.php';
$app = new Application(dirname(__DIR__) . '/config');
$maxRequests = (int)(getenv('WORKER_MAX_REQUESTS') ?: 0);
$runtime = new WorkerRuntime($app, $maxRequests, new RequestCycle($app));
$runtime->run();
On the FrankenPHP side, the Caddyfile declares this script as the worker and sends every request that is not an
existing file to it; any other .php file gets a 404, so classic mode never runs next to the worker (see
docker/frankenphp/Caddyfile.worker in the repository).
WorkerRuntime does what Server::run() does, split in two halves: what happens once, and what happens per request.
Booting, trimmed (the real method also checks that the app has plugins and a League container before using them, and
skips loading routes if some are already loaded):
public function boot(): void
{
$this->app->bootstrap();
$this->app->pluginBootstrap();
$container = $this->app->getContainer();
$container->defaultToOverwrite(true); // see "The container keeps every request"
$queue = $this->app->pluginMiddleware($this->app->middleware(new MiddlewareQueue([], $container)));
$this->server->dispatchEvent('Server.buildMiddleware', ['middleware' => $queue]);
$this->middleware = $queue;
$builder = Router::createRouteBuilder('/'); // routes now, not on the first request
$this->app->routes($builder);
$this->app->pluginRoutes($builder);
$this->cycle?->afterBoot();
}
And per request (trimmed: the real method also refuses to run before boot()):
public function handle(?ServerRequestInterface $request = null, ?callable $send = null): ResponseInterface
{
$request ??= ServerRequestFactory::fromGlobals();
try {
$response = $this->runner->run($this->middleware, $request, $this->app);
if ($request instanceof ServerRequest) {
$request->getSession()->close();
}
if ($send !== null) {
$send($response);
}
$this->server->dispatchEvent('Server.terminate', ['request' => $request, 'response' => $response]);
} finally {
$this->cycle?->afterRequest();
}
return $response;
}
The loop passes the ResponseEmitter as $send and stops after $maxRequests requests if that is set. A few
details are easy to get wrong:
- Send the response before you reset. A body that streams lazily, such as a
CallbackStreamover an ORM query, runs while the response is sent. Reset first and it runs against cleared tables and routes. frankenphp_handle_request()exists in classic mode too. If someone requests the worker script on a classic server, it boots the whole app and then fails. Check$_SERVER['FRANKENPHP_WORKER']before booting.- Do not inject
ServerRequestinto a shared service. Even with overwrite on, a shared service resolved once keeps the request it got first. - *Keep the `Server.
events,** with aServerobject as subject, as in classic mode.Server.buildMiddleware` now fires once per worker, not once per request.
Routing needs one change in your Application::middleware(): replace RoutingMiddleware with a subclass that does
not load routes again while the Router has some.
class KeepRoutesRoutingMiddleware extends RoutingMiddleware
{
protected function loadRoutes(): void
{
if (Router::routes() !== []) {
return;
}
parent::loadRoutes();
}
}
->add(new KeepRoutesRoutingMiddleware($this))
In classic mode the Router starts empty on every request, so this loads routes as before. In a worker they were
loaded at boot, so pluginRoutes() no longer piles them up.
Fix: reset, or keep on purpose
The reset layer is one class, RequestCycle, with two methods: afterBoot() records the state to go back to, and
afterRequest() goes back to it after every request, including one that failed. Order matters. Condensed, with the
numbered comments added for this article:
public function afterRequest(): void
{
$this->rollbackTransactions(); // 1. data first
// 2. app code, while routes and config still work
$this->app->getEventManager()->dispatch(new Event('Worker.afterRequest', $this->app));
$container = $this->app->getContainer();
if ($container->has(self::RESETTABLE_TAG)) {
foreach ((array)$container->get(self::RESETTABLE_TAG) as $service) {
if ($service instanceof ResettableInterface) {
$service->reset();
}
}
}
foreach ($this->router as $name => $value) { // 3. CakePHP's own registries
(new ReflectionProperty(Router::class, $name))->setValue(null, $value);
}
$locator = $this->tableLocator();
$locator->clear();
foreach ($this->tableConfig as $alias => $options) {
$locator->setConfig($alias, $options);
}
Configure::clear();
Configure::write($this->configure);
I18n::setLocale($this->locale);
(new ReflectionProperty(Inflector::class, '_cache'))->setValue(null, $this->inflectorCache);
}
Transactions come first, because a request that died halfway must not leave a transaction for another user to commit.
The strategy is a hardcoded list for CakePHP's statics, because core classes cannot opt in to anything, and opt-in
for your code. A service that holds per-request state implements ResettableInterface (one method, reset()) and is
tagged in the container:
$container->addShared(TenantSecretCache::class)->addTag(RequestCycle::RESETTABLE_TAG);
The demo-only TenantSecretCache is such a service: an instance with secrets keyed by tenant, registered as shared,
tagged, and emptied by reset(), so a rotated secret takes effect on the next request. Code outside the container
listens to Worker.afterRequest on the application's event manager, which is the global EventManager::instance().
What is deliberately kept, and why:
- Connections. Reconnecting per request would give back one of the gains. They need no ping: CakePHP 5's
ReconnectStrategyalready retries a lost connection outside a transaction. - The loaded routes.
Router::reload()looks like the answer and is not: every call empties the route collection, and from its second call on it resets every Router static to its declared default, so URL filters and the route class set at boot disappear without an error. Instead, the worker loads routes at boot,afterBoot()snapshots every Router static, andafterRequest()restores that snapshot.Inflector::reset()has the same trap (it drops custom rules), so only Inflector's cache is restored. - The table locator, but not the Tables. Clearing Table instances after every request is the safe default, and
it has a cost: each Table is rebuilt from the schema cache on the next request, so ORM-heavy pages such as the
admin page keep part of their per-request work in worker mode. Note that
TableLocator::clear()also wipes anything set withsetConfig()at boot, so put that back. Keep the locator object itself; long-lived services hold a reference to it. - The compiled-flag cache. This is state kept on purpose, so it follows three rules:
- Scoped keys. One slot per tenant, holding the version it was compiled from.
- A bound. A new version replaces the old one, and at most 1,000 tenants stay compiled, the oldest dropped first.
- A shared signal for invalidation. A webhook reaches one worker; the others still have the old closures. The
flag API loads the tenant row on every request anyway, and its
flags_version, incremented by the webhook in the same transaction, tells every worker when to recompile. Kept state needs a signal that every worker can see.
From FlagEvaluator::evaluate():
$slot = $this->compiled[$tenant->id] ?? null;
if ($slot === null || $slot['version'] !== $tenant->flags_version) {
unset($this->compiled[$tenant->id]);
if (count($this->compiled) >= $this->maxTenants) {
unset($this->compiled[array_key_first($this->compiled)]);
}
$slot = ['version' => $tenant->flags_version, 'flags' => $this->compileTenant($tenant)];
$this->compiled[$tenant->id] = $slot;
}
Adopting it
To use the same approach in your app:
- Copy
src/Worker/withoutDev/, and use the trimmed entry point shown above aswebroot/frankenphp-worker.php. - Replace
RoutingMiddlewarewithKeepRoutesRoutingMiddlewareinApplication::middleware(). - Tag every service that holds per-request state with
RequestCycle::RESETTABLE_TAG. - Serve the worker script with a Caddyfile like
docker/frankenphp/Caddyfile.worker. - Set
WORKER_MAX_REQUESTS, and restart the workers on every deploy.
The request limit is a safety net, not a fix: each worker stops after that many requests and FrankenPHP starts a
fresh one, which caps the damage of a leak you have not found yet. The restart matters because workers keep the code
and configuration they booted with; OPcache does not help here. After a migration, clear the schema cache
(bin/cake schema_cache clear) as in classic mode, and restart the workers too, since a long-lived service may still
hold a Table built from the old schema.
Proof: finding the leaks you do not know about
The demo has three tools, and the most useful lesson is what each of them cannot see.
The leak detector snapshots CakePHP's registries and every static property of the namespaces you give it before
a request, diffs them after the request and the reset layer, and logs every change that survived. It runs in a
development-only runtime (enable it with WORKER_LEAK_DETECTOR=1) and is slow, because it scans all loaded classes
with reflection. It watches App\ by default; pass your plugin and library namespaces too, for example
new LeakDetector(['App\\', 'MyPlugin\\']). With the static TenantSecretCache from the Cost section in place, it
reports it on the first webhook a worker handles:
Worker leak: static App\Flags\TenantSecretCache::$cache changed and outlived the request [...]
It sees statics. It does not see state inside long-lived objects, such as the shared FlagEvaluator.
The soak test (bin/cake worker_soak) catches what the detector misses, by checking answers instead of state.
For every tenant in turn, it compares the served flags with a fresh evaluation from the database, sends a webhook
signed with that tenant's own secret, and checks that the new version is served.
One trap makes such a test pass without proving anything: sequential requests always land on the same idle worker,
so a few reads after a webhook never reach the others. The soak test sends those reads in parallel batches and
counts the workers that answered, through a development-only X-Worker-Id header; a worker that did not answer
fails the round.
Load over time is the only one of the three that sees the container leak: it is instance state, so the detector
cannot see it, and it gives correct answers, so the soak test cannot see it either. It only shows up as throughput
that falls with every thousand requests, which a short benchmark after a warm-up hides. The demo's bin/decay.sh
runs consecutive batches of 1,000 requests on freshly restarted workers; remove the defaultToOverwrite(true) line
from WorkerRuntime::boot(), restart the worker service, and run it to see the numbers above.
Go / no-go checklist
Before you switch a CakePHP app to worker mode:
- On your highest-traffic endpoints, measured in your own setup, worker mode gives a clear win, for example at least 1.5x the throughput or a clearly lower p99. A hello-world route does not count.
- You have listed the statics in your app, your plugins (in
vendor/andplugins/) and the libraries you keep long-lived: grep forstatic, and run the leak detector with their namespaces over your test or smoke traffic. Each one is reset or kept on purpose, and every long-lived library is safe in a long-running process (bounded caches, no per-request statics). - Everything you keep has a reason, and every kept cache is scoped, bounded and invalidated through a signal all workers can see.
- Nothing shared receives
ServerRequest. - The response is sent before the reset, and the reset runs after failed requests too.
- A soak test of your own, modeled on
worker_soak, passes: it alternates tenants or users, includes writes, and counts every worker as answering. - Throughput is flat over thousands of requests per worker: the last 1,000 requests within about 10% of the first 1,000 after warm-up.
- A request limit is set, your deploy restarts the workers, and migrations clear the schema cache.
- The development diagnostics (leak detector,
X-Worker-Id) are off in production. The demo'scompose.yamlturnsX-Worker-Idon by default for the soak test. - You have tried the rollback: serve the app with a plain
php_server, as indocker/frankenphp/Caddyfile.classic, so that requests go towebroot/index.php, and check that it still serves.
If 2 or 6 fails, stay in classic mode: the speed is not worth serving one user's data to another.
Run the demo's soak test against the worker on a development copy (it writes to the database; pass --workers with
your worker count), then add one of the Cost section's snippets and run it again. Watching it fail is the
fastest way to believe the rest of this article.
If this sounds like your project: a CakePHP application that needs more speed than classic mode gives it, a move to worker mode you want to make without serving one user's data to another, or workers that already slow down or grow in memory over time, CakeDC, the company behind CakePHP, does exactly this kind of work. Get in touch and let's talk about where your application is and how to make it faster safely.
Need help with this in your own CakePHP app?
Talk to a CakePHP expertGet the CakeDC newsletter
One email a month: releases, security advisories and one article worth reading.