DEV Community

Szj
Szj

Posted on

slimfony: a small PHP 8.4 core for FrankenPHP worker mode, with its benchmarks and its limits

State that outlives the request

PHP's classic model hides a whole class of bugs: every request starts from nothing, and everything it built is thrown away at the end. A worker-mode server such as FrankenPHP keeps the application booted and hands it one request after another. That removes the boot from every request, and the safety net with it.

A value cached in a static property, a logger context that still carries the previous request's id, a transaction a failed request left open: in a long-running worker all of these survive into the next request. A test that sends one request does not see them. Real traffic does, which is why these bugs tend to be found in production.

slimfony/core is our attempt to make that failure mode boring. Version 1.0.0 was released on 2026-11-18. Here is what it is, the decisions behind it, what we measured and on what, what did not work out, and where its limits are.

What slimfony is

slimfony/core is a small, strict core for PHP 8.4+ microservices on FrankenPHP worker mode. It is built from a few Symfony components (http-foundation, routing, dependency-injection, plus service-contracts for the reset interface), Doctrine DBAL and psr/log. It deliberately has no http-kernel, no event dispatcher, no bundles and no YAML. JWT verification uses firebase/php-jwt, only when you use it.

Area What the core does
Boot Container and router compiled at build time, middleware chain built once
Worker loop Max requests, memory limit, services reset after every request
Errors RFC 9457 application/problem+json, no internals leaked
Tracing Validated request id, its own span id, an outgoing W3C traceparent
Auth Deny by default, scopes per route, JWT bearer verification with JWKS
Database PostgreSQL via DBAL: leaked transactions rolled back, bounded retries for deadlocks, lost connections and failover
Observability APCu-backed Prometheus metrics, protected /metrics, /healthz, /readyz
Reliability Idempotency-Key middleware for POST and PATCH
Non-HTTP ConsumerRunner for queue consumers and jobs that boot the same container

It is meant as the base for services, not as a general-purpose framework: each service owns its dependency tree and commits its own composer.lock.

Four design decisions

1. Small on purpose

A new package in require needs a justification: "what it does, why ~50 lines of our own code or a PHP built-in do not." There is no dependency for logging (an own PSR-3 JSON logger), request ids (random_bytes), configuration, HTTP clients, validation or serialization. The core even replaces the polyfills PHP 8.4 makes redundant, so a service's vendor/ stays slim.

The price: no argument resolver, no event dispatcher, no bundles. A controller is an invokable service with __invoke(Request): Response. The README names the exit: "A service that outgrows it should move to Symfony, not stretch the core."

2. Compile at build time

Nothing is computed per request that can be done at build or boot. The container and route table are dumped when the image is built, and workers only require them (opcache shares them). A broken configuration fails the warmup, so it never ships. No reflection, autowiring or event dispatching on the hot path.

vendor/bin/slimfony warmup config/services.php config/routes.php var/cache
Enter fullscreen mode Exit fullscreen mode

3. State reset as a first-class concept

Every service that implements Symfony's ResetInterface is reset after every request. If a reset fails, the worker stops: its state is unknown, and the server starts a fresh one. A transaction a request left open is rolled back, logged and counted (db_transactions_leaked_total). MAX_REQUESTS and a memory limit restart a worker after its response is sent, as a guard against anything that leaks anyway. Queue consumers get the same treatment from ConsumerRunner: reset after every message, stop on SIGTERM.

4. Failing closed

Once an Authenticator is configured, everything is denied by default, including paths that match no route (401, so the API cannot be mapped by its 404s). Routes opt out with _public or demand scopes with _scopes. The JWT verifier allows RS256, ES256 and EdDSA; shared-secret algorithms and none cannot be configured. If the identity provider is down, loaded keys keep working; a worker that starts with none waits briefly, then refuses with 401.

/metrics is off until a token or an address list is configured. Retry is bounded (three attempts by default), and a write is repeated after a lost connection only when you declare it idempotent: true, because a lost COMMIT may or may not have happened.

What the code looks like

Copied from the core README, whose samples are executed by tests/ReadmeTest.php. A controller:

<?php

declare(strict_types=1);

namespace App;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

final class Hello
{
    public function __invoke(Request $request): Response
    {
        return new Response('hello ' . $request->attributes->getString('name'));
    }
}
Enter fullscreen mode Exit fullscreen mode

The worker script, public/index.php:

<?php

declare(strict_types=1);

use Psr\Log\LoggerInterface;
use Slimfony\Core\Config\Env;
use Slimfony\Core\Config\Trust;
use Slimfony\Core\Kernel;
use Slimfony\Core\Log\JsonStdoutLogger;
use Slimfony\Core\Log\RequestContext;
use Slimfony\Core\Worker\WorkerRunner;

require __DIR__ . '/../vendor/autoload.php';

$env = Env::fromGlobals();
new Trust($env)->apply(); // TRUSTED_PROXIES / TRUSTED_HOSTS; no proxy is trusted by default (any Host is accepted until TRUSTED_HOSTS is set)

$context = new RequestContext();
$logger = new JsonStdoutLogger($env->string('LOG_LEVEL', 'info'), $context);

$kernel = new Kernel(
    __DIR__ . '/../config/services.php',
    __DIR__ . '/../config/routes.php',
    debug: $env->bool('APP_DEBUG'),
    logger: $logger,
    cacheDir: __DIR__ . '/../var/cache', // written by the warmup below; compiled at boot when missing
    synthetic: [RequestContext::class => $context, LoggerInterface::class => $logger],
);

new WorkerRunner($kernel, $logger, maxRequests: $env->int('MAX_REQUESTS', 0))->run();
Enter fullscreen mode Exit fullscreen mode

config/services.php registers the services and the middleware chain, and config/routes.php maps /hello/{name} to the controller. Without FrankenPHP, the runner serves a single request, so the same index.php works as a classic front controller.

The numbers, and how they were taken

The core's own overhead

composer bench (phpbench) measures Kernel::handle() with a typical production chain (metrics in APCu, request id, security headers, body limit, authentication), one request at a time, 30,000 requests per scenario, opcache and JIT on. It excludes HTTP parsing, the network and application code. CI runner (Linux, PHP 8.4), in microseconds:

Scenario p50 p95 p99
GET /healthz (public route) 28.8 40.3 51.2
GET /hello/{name} (authenticated, scope check, JSON) 34.1 44.3 56.5
RS256 JWT, token remembered (default) 35.7 46.5 58.4
RS256 JWT, verified on every request 129.2 151.1 168.6
EdDSA JWT, verified on every request 116.7 136.8 152.2

The core's own work stays below 50 µs at p95; the signature check is what costs, which is why a verified token is remembered for 30 seconds (never beyond its exp). On a Windows 11 development machine the p95 was 34.6 µs (public) and 40.2 µs (authenticated). CI fails above 250 µs. These are overhead figures, not throughput claims.

End to end, in the demo

The demo uses k6 in a container on the stack's own network with a constant arrival rate: each step runs 15 seconds, and k6 starts requests at that pace whether or not the server keeps up. Everything, k6 included, runs on one machine (i5-14400, 16 CPUs and 8 GB given to Docker Desktop). Single runs unless stated; read the ratios, not the absolute numbers.

What Result
GET /healthz, worker mode 15,000 requests/s, no error or dropped request, p95 7.0 ms (no limit found)
Same app, classic mode (boot per request) saturates at about 1,300 requests/s
Verified token + DB read, 4 PHP workers saturates at about 6,500 requests/s
Same route, 16 PHP workers about 12,400 requests/s
Import of 1,000 ZIPs (10,000 statements), 8 importers 11.5 s and 11.7 s (two runs)

The authenticated read was limited by workers waiting on the database, not by CPU: at 7,500 requests/s the p95 was 699 ms with 4 workers and 5.7 ms with 16.

The biggest import gain came from the application, not the core. Importers updated shared account rows in the order entries appeared, so with eight of them PostgreSQL ended many transactions as deadlocks and Retry re-ran them. Locking rows in a fixed order (sorted by IBAN) took eight importers from 67.1 s to 13.9 s for 1,000 ZIPs, and deadlock retries from 686 to 0. Retry is a net, not a strategy.

Failure injection

An authenticated read at 1,500 requests/s for 150 seconds, while the script restarts PgBouncer (at 20 s) and PostgreSQL (at 50 s) and stops the identity provider for 30 seconds. One run per column:

PgBouncer defaults query_wait_timeout = 3, server_login_retry = 1
Requests 210,041 223,769
Failed (500) 7,370 (3.5%) 188 (0.1%)
Slowest request 15,020 ms 4,057 ms

This is easy to misread. Retry gives up after its bounded attempts, a few tens of milliseconds apart: a database that is away for seconds fails the request. How long a request waits before failing is the pooler's setting. With the defaults, PgBouncer kept answering with its cached login error for server_login_retry (15 s), and waiting requests held the workers. The fix was pooler configuration, not core code. The identity-provider outage caused no failed request.

What did not pan out

  • Deferred garbage collection did nothing here. WorkerRunner can run the cycle collector between requests instead of during them. At 8,000 authenticated requests/s for 20 seconds (about 160,000 requests, 16 workers), the collector ran zero times, with or without the setting: PHP starts it at 10,000 possible cycles, and this code leaves almost none. It stays as insurance for code that builds cycles.
  • More workers stopped helping at 16. 32 workers saturated at about 12,000 requests/s, and the p95 at 7,500/s rose from 5.7 ms to 13.6 ms.
  • Batching NATS pulls helped one importer, barely eight. About 41 ms per ZIP went to waiting for the broker. Pulling five messages per request took one importer from 31.7 s to 15.8 s for 400 ZIPs, but eight importers only from 13.9 s to 13.0 s: there the database write is the limit.
  • PgBouncer costs 5 to 10 percent of import throughput on one machine, for connection economy a single host does not need.

The demo

slimfony/demo (v1.0.0) is a CAMT.053 bank-statement import. ZIP files of ISO 20022 statements arrive by the thousand; every statement is booked all or nothing, checked against an XSD and business rules (balances, accounts, currency, period, duplicates).

One docker compose up starts FrankenPHP in worker mode (the API and a live page), a small identity provider with JWKS and key rotation, an outbox relay, importers on NATS JetStream, PostgreSQL behind PgBouncer, Prometheus and Grafana. Kubernetes manifests with probes, autoscaling, disruption budgets and network policies are included.

An accepted upload and its outbox row are stored in one transaction. The page has chaos switches: kill an importer mid-batch, or cut the database connections. Every ZIP still ends up booked, or failed with the reason on record, and scripts/chaos.sh checks exactly that.

The review before 1.0

Before the 1.0 tag, the whole library went through an independent review. The most instructive finding was in ProcessMetricsEndpoint, the small /metrics listener for command-line processes. It compared its address allow-list against 127.0.0.1 for every client instead of the connected peer. A list naming the cluster network matched nobody; a list containing 127.0.0.1 admitted everybody. Either way, the list did not protect anything.

It was fixed before the tag, together with the other findings: a throwing middleware was answered outside the middleware around it (so that 500 had no request id or security headers), the JWKS provider retried a failed download on every request, and an idempotency claim could be finished by a request that had already lost it. All are in the 1.0.0 changelog.

How it is checked

  • SemVer is written down in STABILITY.md: the @api classes (parameter names included) and contracts that are not classes, such as metric names, log fields and the error shape.
  • PHPStan at level max, no baseline, plus an architecture test for final, #[\Override], typed constants and @api/@internal.
  • The build fails below 95% line coverage (95.9% when the gate was added).
  • Seeded fuzz tests for the parsers that take outside input.
  • CI on PHP 8.4 and 8.5 against real PostgreSQL and APCu, plus a row with the lowest allowed dependency versions.
  • SHA-pinned GitHub Actions; release archives with a CycloneDX SBOM and signed build provenance (gh attestation verify).

Limits

  • No real production service yet. The demo is the proof, not a customer.
  • Idempotency is not exactly-once. If the process dies between the work and storing the answer, the request runs again once the lock expires. Work that must never happen twice needs its own unique column, filled from Attributes::IDEMPOTENCY_KEY.
  • The Kubernetes manifests have not been run on a real cluster.
  • PostgreSQL first. The retries and failover handling are written and tested for it.
  • Small on purpose. No ORM, templates, bundles or Messenger; no load shedding or request deadlines, which belong to the edge and the platform.
  • The numbers come from one machine, with the load generator sharing its CPUs.

Try it

composer require slimfony/core
Enter fullscreen mode Exit fullscreen mode

The README's quickstart takes it from there. To see the whole system (the page at http://localhost:8080, Grafana at http://localhost:3000; Docker needs about 3 GB of memory):

git clone https://github.com/slimfony/demo.git
cd demo
docker compose up -d --build --wait
Enter fullscreen mode Exit fullscreen mode

On Windows, set BUILDX_BAKE_ENTITLEMENTS_FS=0 in the same terminal first.

Criticism and bug reports are welcome; security issues go through GitHub Security Advisories, as SECURITY.md describes.

Top comments (0)