FrankenPHP worker mode on an old PHP API: the two walls before the switch
On 23 November, Benjamin Eberlei, founder of Tideways, published ZTS is the future of PHP. His point: PHP built in thread-safe mode (ZTS) should become the default, and the official Docker images have already made the move: since PHP 8.6, they are built in ZTS by default (docker-library/php#1686). I agree. And reading it, I thought about what ZTS cost me this summer, very concretely, on the API of a basketball statistics site.
The result first, because it is what makes the rest worth reading:
| before | after | |
|---|---|---|
| API hosting (Clever Cloud) | several S instances, sometimes M | a single XS |
| average time of the fast endpoints | ~100 ms | ~20 ms |
| monitoring | $400 a month | $0 |
Meanwhile, bots pushed the traffic entering the platform up by roughly a hundredfold, for a few days. More on that below.
These gains do not come from FrankenPHP alone. Most of them come from rewriting the API in modern Symfony; worker mode is the last step. But to climb it, there were two walls: worker mode keeps state between requests, and ZTS breaks the APM (application performance monitoring) agent. In other words, the statics, and New Relic.
Section intitulée where-we-startedWhere we started
The site is a basketball database: players, games, stats, for hundreds of leagues. The API behind the website and its clients dates from a time when the goal was to make it work, on a small budget. Procedural PHP, a big functions.php, Manager classes that load everything. In early 2022, I moved the whole thing from a dedicated server that kept crashing to Clever Cloud, behind PHP-FPM; I told that story at Forum PHP 2022 (in French): Migration d’un hébergement classique à une infra cloud PaaS.
This summer, we rewrote that API in Symfony, endpoint by endpoint. The next step was obvious: FrankenPHP in worker mode. The Symfony kernel boots once and serves thousands of requests, instead of rebuilding everything on every call.
What does a PHP-FPM request pay before reaching your controller? With OPcache, PHP no longer reads or compiles your files on every request, but it still runs everything: it registers Composer’s autoloader, loads the classes, builds the container and every service the request touches, opens a database connection, and throws it all away at the end. In worker mode, that work is done once per worker, and what it builds stays in memory for the next requests.
Except that worker mode changes a rule a lot of old PHP code relies on: memory no longer dies at the end of the request.
Section intitulée first-wall-the-code-static-code-sFirst wall: the statics
Section intitulée the-ones-i-added-myselfThe ones I added myself
In December 2021, while preparing that migration, the API was slow, and I did what every PHP developer has done for twenty years: static caches. In PHP’s classic model, every request starts from scratch and loses everything when it ends, so a static is the cheapest cache there is, scoped to one request by design. The legacy code ran the same SQL query hundreds of times in a loop; I did not have the time to fix the code, so I cached around it. (In the same spirit, we even went back from MySQL 8 to 5.7 during the migration, to get back the query cache that MySQL 8.0 removed.) Here is one of those caches, in getTeam(), shortened and translated:
function getTeam($team, ?Season $season = null)
{
// …
$key = sprintf('%s-%s-%s-%s-%s', $team->getId(), $needNames, $needClub, $needSeasons, $needHistory);
static $cache = [];
if (isset($cache[$key])) {
return $cache[$key];
}
// … build the team, SQL queries included
$cache[$key] = $add;
return $add;
}
Under PHP-FPM, this is a very good idea. The same team shows up twenty times in a response; we build it once, and the cache dies with the request. Free, no invalidation, no risk.
In worker mode, the same code becomes a trap. The static $cache lives as long as the worker. The first version of a team is served to every following request, even after a fix in the database, and the array grows until the restart. Nothing crashes: the responses are just wrong, and heavier and heavier.
There were some in functions.php and in the Manager classes. The best way to get rid of them was not to hunt them one by one: it was to migrate every endpoint to Symfony, then delete the whole legacy runtime. 883 lines of functions.php gone at once, with their statics.
Section intitulée the-ones-left-in-modern-codeThe ones left in modern code
I thought I was done. Before the switch, a pass over the state kept by the Symfony services themselves proved otherwise. A Symfony service is shared: in worker mode, the same instance serves every request. We found two kinds of mistakes:
- A cache that only grows. A
private static arrayof computed slugs, with no bound. Every answer is correct, but in a worker, memory climbs until the restart. - A result that leaks into the next call. A service that fills a property (
$this->result,$this->games) while it works, and never empties it. Each call inherits what the previous one left. This one is wrong, not just heavy.
And “unbounded” is the word that matters. If the key of such a cache comes from the request, a client can make it grow at will, and in worker mode nothing ever empties it: a memory leak becomes a denial-of-service vector. Twig fixed exactly this twice this year, for the formatters of IntlExtension (GHSA-35wc-cvqg-78fp) and for the converters of html_to_markdown (GHSA-cxp7–29fv-2j25), both now capped at 100 entries; both advisories name FrankenPHP’s worker mode. In a worker, a cache without a maximum size is not just a leak, it is an attack surface.
The second kind is the dangerous one. One of our services writes an automatic text about a team’s schedule; called for a second team, it also listed the first team’s games. The regression test added with the fix says it better than a sentence:
public function testItDoesNotReuseGamesFromThePreviousCall(): void
{
// …
$generator->generateAutoText($firstTeam, $season, $league);
$text = $generator->generateAutoText($secondTeam, $season, $league);
self::assertStringContainsString('<h3>Second team</h3>', $text);
self::assertStringNotContainsString('January 2099', $text); // a game of the first team
}
Under PHP-FPM, rebuilding the service on every request kept this state from leaking into the next request. Worker mode removes that boundary. That is what makes it nasty: the bug was always there, nothing ever showed it.
Section intitulée resettable-servicesResettable services
Symfony has a mechanism for exactly this: ResetInterface. A service that implements it is tagged kernel.reset (automatically, with autoconfiguration), and its reset() method is called between two requests. That is how Symfony empties, among others, the Doctrine entity managers and the buffered logs before the next request.
Our services did not implement it, and I did not add it: the fix was to stop keeping state at all, by resetting it at the start of the method or passing the data as arguments. ResetInterface is the right tool for a service whose state is legitimate, like a per-request buffer; it is not a way to hide a service that should never have had state.
To find them before they bite, the FrankenPHP documentation now points to Igor PHP, a linter that looks for services missing ResetInterface, stateful properties and mutable local statics. I did not have it this summer; I would run it first today.
The rule to keep: in worker mode, anything static, or stored in $this of a shared service, lives from one request to the next. Look for static $, self::$, and service properties that are not injected dependencies.
Section intitulée second-wall-new-relicSecond wall: New Relic
I never work blind. When I moved the site to Clever Cloud in 2022, the very first thing I did, before touching anything, was to add New Relic: you cannot migrate what you cannot see. It had been watching the API ever since. And this is where ZTS comes in.
FrankenPHP serves requests with threads, not processes. So it needs PHP built with ZTS. But New Relic dropped ZTS support from its PHP agent in version 9.19, early 2023, citing low usage and instability. The request to support FrankenPHP has been open since March 2024; at the end of 2025, New Relic said it was working on it. As I write, it is still open.
No agent, then. And switching to FrankenPHP without observability was out of the question: the observability had to be there before the switch, not after. I chose OpenTelemetry, which I had wanted to try for a long time, and which does not depend on any vendor.
The setup is simple: the application sends its traces, metrics and logs over OTLP, OpenTelemetry’s protocol, to an OpenTelemetry collector running next to it, locally. On Clever Cloud, the collector is a worker process of the same instance (CC_WORKER_COMMAND), restarted on failure, with a 64 MiB memory limiter; its queues live in memory and are bounded, so a dead collector loses telemetry, never responses. It filters and samples, then exports to New Relic, which accepts OTLP. Everybody keeps the tool they know how to read; only the agent goes away. The export happens on kernel.terminate, after the response has been sent.
And since every trace goes through the collector, it is the perfect place to decide which ones are worth keeping. Before, 100 % of the transactions went to New Relic. The agent could probably have been configured to send less; I simply had not done it. Now the collector does tail sampling: it waits for the end of the trace, then decides.
# lib/telemetry/collector/otelcol.yaml (simplified)
processors:
tail_sampling:
decision_wait: 5s
policies:
- name: errors # every error…
type: status_code
status_code: { status_codes: [ERROR] }
- name: slow # anything over 1 s
type: latency
latency: { threshold_ms: 1000 }
- name: baseline # and 1 % of the rest, as a reference
type: probabilistic
probabilistic: { sampling_percentage: 1 }
The real file combines these with and/not sub-policies: 404s do not count as errors, and the front gets a 3 s threshold instead of 1 s.
So we keep everything interesting (errors, slow requests) and a sample of the rest to know what normal looks like. Metrics are not sampled. In the spans themselves, I only send what is useful for debugging, and cut everything else as much as possible.
That matters at our scale: a million requests a day is a lot of traces to keep. The result showed up on the bill: New Relic’s free tier includes 100 GB of ingest per month (as of November 2026), and we are below it. From $400 a month to $0, still keeping errors and slow requests.
One thing I have not used yet: with a single metrics line in the global options of the Caddyfile, FrankenPHP exposes Prometheus metrics about its threads and workers: busy threads, queue depth, crashes, restarts. The collector could scrape them and send them to New Relic with the rest. They would not replace the application’s own telemetry, though: what I need are business facts, which endpoint, which client, which league, and only the application knows them. The two could even meet in a single trace: Caddy’s tracing directive opens an OpenTelemetry span for each request and can pass its IDs to the application in a header, and the application would continue that trace instead of starting its own. I have not tried it yet.
Section intitulée the-switchThe switch
On Clever Cloud, moving the API to FrankenPHP workers fits in a few environment variables (documentation):
CC_FRANKENPHP_WORKER=/public/index.php
FRANKENPHP_LOOP_MAX=500
FRANKENPHP_RESET_KERNEL=0
Since Symfony 7.4, the Runtime component detects FrankenPHP and runs the worker loop itself, so public/index.php is the standard Symfony one. It was not, until that day: it started with 36 lines of early bot filtering, written before Symfony even booted, that answered with echo and ended with exit. Under PHP-FPM, exit ends the request. In worker mode, it ends the worker. Those lines went away with the switch.
Two settings deserve a word:
FRANKENPHP_RESET_KERNEL=0: despite the name, this has nothing to do with thekernel.resettag. When the option is on, Symfony clones the kernel after each request, and the clone starts without a container: every service is rebuilt and the database connection reopened, which is most of what worker mode saves. When it is off, the same container serves every request, and only the services taggedkernel.resetare reset between two requests. Since the services with state had been fixed, we keep it off.FRANKENPHP_LOOP_MAX=500(Symfony’s default): each worker restarts after 500 requests. It is a safety net: a leak we missed cannot grow forever.
Section intitulée a-canary-one-endpoint-at-a-timeA canary, one endpoint at a time
This part matters to me as much as the runtime itself: I want to be able to deploy a change like this one little by little, as a canary, and back out in seconds. Changing the runtime of an API that clients call all day is not something I would do in one go. And I did not have to, thanks to what sits in front of it.
The API is behind Varnish (I wrote about Varnish in 2021), deployed as its own application, separate from the PHP one. That was a deliberate choice: when I deploy new code, the cache does not start empty, and when I scale, I add PHP compute without scaling Varnish with it.
On the Varnish application, I had added redirection.io, a product we built at JoliCode, first for our own needs. Its v3 agent runs right after Varnish and applies rules before a request reaches PHP. One of its actions changes the backend a request is sent to. So the FrankenPHP application was deployed next to the Apache + PHP-FPM one, both live, and a rule decided which requests went to the new one:
- first a single, small endpoint, to check the whole chain: routing, the collector, the traces in New Relic, how the workers behaved;
- then endpoints that were a bit more complicated;
- and so on, until everything went through FrankenPHP.
Rolling back meant editing a rule, not redeploying anything. And the old application stayed there, warm, until I no longer needed it.
That rule has been called 215 million times since it went live in mid-August, according to redirection.io. That rule runs behind Varnish, which serves more than 60 % of the requests from its cache: those 215 million are only the ones the cache could not answer. When I say this API gets called a lot, that is what I mean.
The same agent also blocks a few kinds of dishonest traffic before they ever reach the PHP runtime: the cheapest request is the one PHP never sees.
The numbers from the beginning are today’s: a single XS instance instead of several S, sometimes M, and ~20 ms on average for the fast endpoints instead of ~100 ms, both read in New Relic (through its agent before, through the collector after). Those ~20 ms are almost only database time; with more powerful instances, we would get down to around 12 ms. The XS trade-off suits me fine.
Again, this is not FrankenPHP alone. Most of the gain comes from the rewrite in Symfony and from moving all the code to modern PHP. Worker mode removes what was left: booting the kernel on every request.
To isolate FrankenPHP itself, I put the same commit back on Apache + PHP-FPM, on the same XS size, and replayed a few hundred real production requests on both, one at a time, reading the response times in Clever Cloud’s access logs. The sample mixes every endpoint, slow ones included, so it runs slower than the fast endpoints quoted above: about 45 ms at the median for PHP-FPM, 26 to 35 ms for the worker. One run each, in both orders: in this small sequential replay, worker mode reduced the median response time by roughly a third. An order of magnitude, not a promise under load.
And what came next proved it was not a luxury. A massive wave of bots multiplied the traffic entering the platform by roughly a hundred, to over 50 million requests a day. A peak of a few days, not an average: it lasted until I blocked the callers (how, maybe in another post). With the old API, it would have cost us a fortune in instances or, more likely, it would simply not have held. Now that the bots are contained, about a million requests a day reach the API, behind the cache.
Section intitulée what-stays-hot-and-what-couldWhat stays hot, and what could
In worker mode, some things now survive from one request to the next, for free:
- the booted kernel and its container, with every service that is not reset;
- the database connection: Doctrine keeps it open between requests and only reconnects when it has been idle for more than 10 minutes (
idle_connection_ttl, 600 s by default), where PHP-FPM would open one per request; - Doctrine’s metadata, already parsed in memory.
That opens a door I have not gone through yet: keeping data hot. Some reference data in an API like ours does not change between two deployments. In worker mode, there are three places to keep it, each with its own trade-off:
- A property of a service that is not reset. The simplest. But each worker thread has its own copy (FrankenPHP starts two workers per CPU by default), and with
FRANKENPHP_LOOP_MAX=500, it is rebuilt every 500 requests. - APCu. One copy per FrankenPHP process, shared by all its threads, and it survives worker restarts. Grzegorz Drozd checked it in detail; the trap is that it must be installed, and enabled with
apc.enable_cli=1. - A PHP file generated at deployment, the way Symfony’s
PhpArrayAdapterdoes for its system caches: OPcache keeps the array in shared memory, every thread reads it without copying it, and it never expires.
For data that is truly timeless, the third one looks like the best deal. I have not measured any of them on this API yet: that will be for another post.
A fourth option came from Kévin Dunglas while reviewing this post: a small FrankenPHP extension, written in Go, exposing a cache shared by every thread, built on Otter, the Go cache library FrankenPHP already uses internally. It does not exist yet; it sounds like a nice weekend project.
Section intitulée before-switching-to-worker-modeBefore switching to worker mode
The two walls are not the same. ZTS alone keeps nothing between requests; it is worker mode that does. What ZTS changes is which extensions and agents still work. If Benjamin is right, and I think he is, more projects will meet the second wall, and those that choose a worker mode will meet the first. Before moving to worker mode, I would check:
- the state that survives the request:
statics, properties of shared services, hand-made singletons. Run a linter, then look again; - extensions and agents: are they ZTS-compatible? For APM, OpenTelemetry with a collector settles the question, and the bill with it;
- what you really keep: if you send 100 % of your traces, you mostly pay for requests that went fine;
- how you roll it out: a canary in front of the application, one endpoint at a time, with a rollback that is a configuration change, not a deployment.
A word of thanks before closing. The runtime itself was the easy part, and that is thanks to three projects: FrankenPHP, now a project of the PHP Foundation, and Kévin Dunglas, who created it and also wrote its Symfony runner; Symfony, whose Runtime component supports FrankenPHP’s worker mode natively since 7.4, so public/index.php needed no FrankenPHP-specific line; and Clever Cloud, where switching an application to FrankenPHP workers is a handful of environment variables. All the hard work in this post was in our own code. None of it was in the integration.
And the runtime is not done changing. One process per request, then threads and long-lived workers; at SymfonyCon 2026, Guillaume Loulier showed elephc, a compiler that turns a static subset of PHP into native binaries, with no virtual machine at all (elephc.dev). It is not something I would put in front of this API tomorrow. But each of these steps asks the same question as this post: what does my code assume about the way PHP runs it?
The statics I added in 2021 were a good idea in 2021. The code was not wrong; the world around it changed.