DEV Community

Cover image for One Kernel for Every Tenant: FrankenPHP Worker Mode for Database-per-Tenant Symfony 8.1
Matt Mochalkin
Matt Mochalkin

Posted on

One Kernel for Every Tenant: FrankenPHP Worker Mode for Database-per-Tenant Symfony 8.1

In part 1 we put every free tenant of a database-per-tenant SaaS on one shared Symfony 8.1 deployment. Each request names its tenant in the path, a DBAL wrapper reconnects to the tenant's database, a cache decorator namespaces by tenant, and one Messenger worker reads every tenant's stream. The saving was memory: one set of processes per placement instead of one per tenant.

The HTTP side of that deployment still ran under php-fpm, and php-fpm forgets everything between requests. Every request boots the kernel, loads the compiled container, asks Redis whether the tenant is placed here, and opens a connection to the tenant's database. Part 1 measured that last step at about six milliseconds per switch and shrugged, because a php-fpm request pays a connection anyway. This article is about that shrug.

FrankenPHP's worker mode keeps the kernel alive across requests. For a single-tenant app that is a throughput story. For a shared multi-tenant deployment it changes what a tenant switch costs, and it changes which state leaks if you are careless. We'll move the demo from part 1 to FrankenPHP, keep one open connection per tenant database inside each worker, go through the state that must and must not survive a request, and measure four deployments under a load that changes tenant on every request.

Prerequisites

  • The demo from part 1: mattleads/tenant-shared-demo, PHP 8.4, Symfony 8.1, Doctrine DBAL 4, PostgreSQL 16 and Redis 7 in Docker.
  • symfony/runtime 7.4 or later. It ships FrankenPhpWorkerRunner and detects worker mode on its own, so the separate runtime/frankenphp-symfony package is not needed. That package is still capped at Symfony 7 at the time of writing and will not install on 8.1.
  • FrankenPHP 1.13 from the dunglas/frankenphp:1-php8.4 image (PHP 8.4.27, Caddy 2.11), php:8.4-fpm-alpine and nginx:1.27-alpine-slim for the baseline, and wrk for the load.

Everything below is in the same repository: docker/, compose.bench.yaml, scripts/bench.sh and bench/.

1. What php-fpm throws away on every request

Trace one GET /tenant_<uuid>/notes on the shared deployment of part 1:

  1. PHP starts, opcache hands over the compiled files, the kernel boots and the container is instantiated.
  2. TenantRequestListener reads the prefix and asks PlacementReader whether the tenant is served here. The reader has a 30 second in-memory cache, which under php-fpm is always empty, so this is one HGET on Redis per request.
  3. The repository runs its query. TenantConnection::connect() opens a connection to tenant_<uuid> first: a TCP handshake, Postgres authentication, a backend process forked on the server.
  4. The response goes out and the process forgets all of it.

Step 3 is the one we measured in part 1 with app:bench:switch, the command that runs SELECT 1 three hundred times on one tenant and then three hundred times alternating tenants:

300 queries on one tenant:              0.172 ms per query
300 queries switching tenant each time: 5.976 ms per query (299 reconnects)
cost of a tenant switch: 5.80 ms
Enter fullscreen mode Exit fullscreen mode

Under php-fpm nothing can be done about steps 1 to 3 except making each cheaper. Under a worker they can stop happening.

2. FrankenPHP in one Dockerfile and three environment variables

FrankenPHP is a PHP SAPI embedded in Caddy. It serves PHP two ways. In classic mode each request gets a fresh PHP execution, like php-fpm but without FastCGI and without a separate web server. In worker mode a script is started once per worker thread and handles requests in a loop. Both modes run from the same image; only the configuration differs.

# docker/frankenphp/Dockerfile
FROM dunglas/frankenphp:1-php8.4

RUN install-php-extensions pdo_pgsql redis intl opcache zip
COPY --from=composer:2 /usr/bin/composer /usr/bin/composer
COPY docker/php/app.ini /usr/local/etc/php/conf.d/app.ini

ENV APP_ENV=prod APP_DEBUG=0 SERVER_NAME=:80 SERVER_ROOT=/app/public
WORKDIR /app

COPY composer.json composer.lock symfony.lock ./
RUN composer install --no-dev --no-scripts --no-progress --prefer-dist --no-autoloader
COPY . .
RUN composer dump-autoload --no-dev --classmap-authoritative \
 && bin/console cache:warmup --no-interaction \
 && chown -R www-data:www-data var
Enter fullscreen mode Exit fullscreen mode

The image ships a Caddyfile that reads its site block from SERVER_NAME and SERVER_ROOT, and its FrankenPHP block from FRANKENPHP_CONFIG. Classic mode:

FRANKENPHP_CONFIG: num_threads 8
Enter fullscreen mode Exit fullscreen mode

Worker mode, eight workers running public/index.php:

FRANKENPHP_CONFIG: |
  num_threads 8
  worker ./public/index.php 8
Enter fullscreen mode Exit fullscreen mode

Nothing in public/index.php changes. Since symfony/runtime 7.4, SymfonyRuntime::getRunner() checks the FRANKENPHP_WORKER variable that FrankenPHP sets inside a worker and returns a FrankenPhpWorkerRunner. That runner is short enough to read in full, and you should, because it decides what your application sees between requests:

  • It calls frankenphp_handle_request() in a loop. For each request it builds a Request from globals, calls $kernel->handle(), sends the response, then calls $kernel->terminate().
  • After each request it drops its references to the request and response and runs gc_collect_cycles().
  • It stops after FRANKENPHP_LOOP_MAX requests, 500 by default, and FrankenPHP starts a fresh worker. A slow leak is bounded by that number.
  • With FRANKENPHP_RESET_KERNEL=1 it clones the kernel after every request. That is the heavy option for applications with state you cannot track down. We will not need it.

$_SERVER['APP_RUNTIME_MODE'] tells the application how it runs: web=1 under php-fpm or classic FrankenPHP, web=1&worker=1 inside a worker. The demo's /whoami prints it.

3. What survives a request, and what must not

A worker keeps the kernel, the container and every service instance alive. For a multi-tenant application that is the whole question. Go through the state of part 1 one item at a time.

The tenant itself. TenantContext is static. It is set by TenantRequestListener on kernel.request and cleared on kernel.terminate. The worker runner calls terminate() after every request, including one that ended in an exception caught by the kernel, so the next request starts without a tenant and a path without a prefix is still a 404. If your tenant context has no clear on terminate, add one before you turn worker mode on. A worker that keeps the previous tenant and serves a request without a prefix answers from the wrong database.

Services reset by the kernel. Symfony resets tagged services before it handles the next request. Kernel::boot() checks a resetServices flag set by the previous handle() and calls services_resetter, which runs every kernel.reset method: the entity manager clears its identity map, the Doctrine connection does nothing, loggers flush, and the part 1 cache decorator TenantAwareCache::reset() drops its per-tenant sub-pools. That decorator inherited the kernel.reset tag from cache.app when it took over the service id, so there is nothing to add. This is the same mechanism Messenger workers have relied on since they exist, so a codebase whose workers are clean is most of the way there.

The placement cache. PlacementReader keeps the list of served tenants for 30 seconds. Under php-fpm that cache never outlived a request and the TTL was decorative. In a worker it is real: a tenant moved to another placement keeps being served here for up to 30 seconds by each worker that had read the list. Decide whether that is acceptable for your move procedure. The demo's app:tenant:place invalidates its own reader, which does nothing for the workers; a move that must be immediate needs a shorter TTL or a Redis pub/sub signal.

The database connection. This is the one we want to survive. TenantConnection from part 1 already keeps its connection as long as the tenant does not change, and under php-fpm that meant nothing. In a worker it means the second request of the same tenant on the same worker runs no handshake. Three tenants in turn, though, still reconnect on every request, because the wrapper closes the previous connection before opening the next one. Section 4 fixes that.

Static counters, singletons, memoized lookups. Part 1 counted 31 classes with tenant-specific state in constructors in the production codebase, and a scan test keeps them from coming back. That test is the entry ticket to worker mode. A memoized "current tenant's settings" in a private property, a static $cache keyed by nothing, a connection pool keyed by nothing: each of them is correct under php-fpm and a cross-tenant leak under a worker. Run the scan, then run two tenants through one worker in a test, as in section 7.

4. Keep one connection per tenant database

The wrapper from part 1 switched database by closing and reconnecting. In a worker the switch happens on most requests, so instead of closing the previous connection we park it, keyed by database name, and take it back the next time that tenant comes round. The number of connections a process keeps is a query parameter of DATABASE_URL, so a php-fpm deployment and a worker deployment can run the same image with different settings:

DATABASE_URL=postgresql://app:app@database:5432/app?serverVersion=16&charset=utf8&tenantConnections=16
Enter fullscreen mode Exit fullscreen mode

DoctrineBundle merges every query parameter of the URL into the connection parameters, so the wrapper reads it from getParams():

// src/Tenant/TenantConnection.php
class TenantConnection extends Connection
{
    private ?string $connectedTo = null;

    /** @var array<string, DriverConnection> Open connections of other tenants, least recently used first. */
    private array $parked = [];

    /** How many times this connection opened a driver connection, for the benchmark and /whoami. */
    public static int $connects = 0;

    protected function connect(): DriverConnection
    {
        $params = $this->getParams();
        $target = $this->databaseFor($params['dbname'] ?? null);

        if ($this->_conn !== null) {
            if ($target === $this->connectedTo) {
                return $this->_conn;
            }
            if ($this->isTransactionActive()) {
                throw new \LogicException(sprintf('Tenant changed to %s inside a database transaction', TenantContext::current()->uuid));
            }
        }

        // take the target out before parking the current one, so it cannot be the one dropped over the limit
        $resumed = $this->parked[$target] ?? null;
        unset($this->parked[$target]);
        if ($this->_conn !== null) {
            $this->park($params);
        }

        if ($resumed !== null) {
            $connection = $this->_conn = $resumed;
        } else {
            try {
                $connection = $this->_conn = $this->driver->connect(['dbname' => $target] + $params);
            } catch (Driver\Exception $e) {
                throw $this->convertException($e);
            }
            ++self::$connects;
        }
        $this->connectedTo = $target;

        if (!$this->isAutoCommit()) {
            $this->beginTransaction();
        }

        return $connection;
    }

    /** Keep the current connection for its tenant's next turn, dropping the least recently used one over the limit. */
    private function park(array $params): void
    {
        $keep = max(1, (int) ($params['tenantConnections'] ?? 1)) - 1;
        if ($keep > 0 && $this->connectedTo !== null) {
            $this->parked[$this->connectedTo] = $this->_conn;
            while (count($this->parked) > $keep) {
                unset($this->parked[array_key_first($this->parked)]);
            }
        }
        $this->_conn = null;
        $this->connectedTo = null;
    }
Enter fullscreen mode Exit fullscreen mode

Three things to notice. The default is 1, which is the part 1 behavior: close on switch, right for php-fpm where a kept connection would die with the process anyway. The parked array is ordered by last use, so a worker that serves a hundred tenants with tenantConnections=16 keeps the sixteen it saw most recently, and dropping one is a plain unset: PDO closes the connection in its destructor. The transaction guard is unchanged, a switch inside a transaction is still refused, kept connections or not.

The first bug I wrote here is the comment in the middle. Parking the current connection before taking the target out of the parked list evicts the very connection you are about to reuse, as soon as the list is full. The test in section 7 caught it on the second case.

The CLI benchmark from part 1 with the parameter set:

300 queries on one tenant:              0.154 ms per query
300 queries switching tenant each time: 0.160 ms per query (2 reconnects)
cost of a tenant switch: 0.01 ms
Enter fullscreen mode Exit fullscreen mode

Two reconnects for three tenants: the first was already connected. The switch went from 5.80 milliseconds to the cost of an array lookup.

Postgres sees the difference as idle backends. A worker that keeps 16 connections holds 16 Postgres backends, each a process with a few megabytes of its own. Eight workers times sixteen is 128 backends from one container, so set tenantConnections from max_connections on the server, not from the number of tenants, and put PgBouncer in session mode in front if the sum across placements gets close.

The same knob applies to the Messenger worker of part 1, which was already a long-lived process and reconnected on most messages. Set it in the worker's DATABASE_URL too.

5. Watching a worker switch tenant

/whoami now reports how the process runs and what its connection has done. Twelve requests rotating three tenants against worker mode without kept connections, then a thirteenth:

{"tenant":"11111111-…","runtime":"web=1&worker=1","connects":13,"open":["tenant_11111111_…"]}
Enter fullscreen mode Exit fullscreen mode

The same against worker mode with tenantConnections=16:

{"tenant":"11111111-…","runtime":"web=1&worker=1","connects":3,"open":["tenant_22222222_…","tenant_33333333_…","tenant_11111111_…"]}
Enter fullscreen mode Exit fullscreen mode

Three connections for thirteen requests, three databases open, the current one last. One detail that bites when you read these numbers: FrankenPHP workers are threads of one process, so pid is 1 in every answer, and PHP statics such as $connects are per thread. Each worker thread counts its own connections.

6. The benchmark: four deployments, a tenant switch on every request

compose.bench.yaml starts the same code four ways on the Postgres and Redis of part 1, every container limited to 4 CPUs and 8 PHP threads or processes:

name serves PHP with tenant connections kept
fpm-nginx php-fpm 8.4, pm = static, 8 children, behind nginx 1
frankenphp FrankenPHP classic mode, 8 threads 1
frankenphp-worker FrankenPHP worker mode, 8 workers 1
frankenphp-worker-keep FrankenPHP worker mode, 8 workers 16

scripts/bench.sh gives every tenant 20 notes, warms each deployment for 10 seconds and then runs wrk for 20 seconds with 4 threads and 32 connections. The Lua script sends GET /tenant_<uuid>/notes for the three tenants in turn, so each PHP thread or process sees a tenant switch on most requests. That endpoint runs the request listener, the Redis placement check, an ORM query and JSON serialization: a small but real page.

deployment requests/s avg latency p50 p99 max DB connections opened container RSS
fpm-nginx 690 46.28 ms 45.44 ms 70.09 ms 81.35 ms 13,892 41.6 MiB
frankenphp (classic) 366 87.06 ms 90.30 ms 113.40 ms 153.72 ms 7,383 78.0 MiB
frankenphp-worker 553 57.70 ms 64.33 ms 88.14 ms 280.13 ms 7,771 68.7 MiB
frankenphp-worker-keep 8,521 3.86 ms 3.38 ms 10.65 ms 41.41 ms 1,026 75.4 MiB

20 seconds each, no errors in any row. "DB connections opened" is what Postgres counted in pg_stat_database.sessions for the three tenant databases during the measured run, not what PHP believes. The full output of each run is in bench/ and the table is bench/results-2026-11-12-sslmode-prefer.md.

Read the table from the bottom. Worker mode with kept connections serves 8,521 requests per second with a p99 of 10.65 milliseconds, against 690 and 70 milliseconds for php-fpm: twelve times the throughput on the same 4 CPUs, with no change to a controller, a repository or a route. Its connection column is the other thing to read. Eight workers times three tenants is 24 connections for the whole run; Postgres counted 1,026. That is FRANKENPHP_LOOP_MAX: a worker recycles after 500 requests, 170,000 requests is about 340 recycles, and every new worker opens its three connections again. Raise the loop max and that column drops to 24.

The two middle rows are the ones a benchmark on a single-tenant app would not show you. Worker mode without kept connections is slower than php-fpm. It saves the kernel boot and the placement read, and it still opens a connection for 7,771 of its 11,100 requests, because the tenant changes on most of them. The connect it keeps paying costs more than the boot it saves. Classic FrankenPHP is slower still, at about half of php-fpm's throughput, and that one took me a while.

The memory column is the part 1 saving unchanged: one set of processes per placement either way. The FrankenPHP container sits at 69 to 78 MiB with Caddy and eight PHP threads inside, the eight php-fpm children at 42 MiB, nginx not counted.

A trap I did not expect: concurrent connects inside one process

The classic FrankenPHP row is slower than php-fpm on this page, which it is not on a page without a database: on /health alone, classic mode serves about 1.5 times the requests of php-fpm and worker mode about 3.8 times. The difference is the connect. A single new PDO(...) to a tenant database takes about 4 milliseconds from either image, measured in a loop. Eight CLI processes in the FrankenPHP container running that loop at the same time still get 4.5 milliseconds each. Eight FrankenPHP threads serving a script that only connects and disconnects get about 390 connects per second between them, against about 1,800 for the eight processes.

Something between pdo_pgsql and libpq 17 serializes connection setup across the threads of one process. It is not SSL negotiation, not GSS negotiation and not name resolution: sslmode=disable, gssencmode=disable and connecting by IP each left the number where it was. I stopped there, because the fix for a shared deployment is the same whatever the lock is: stop connecting. With tenantConnections set, a worker opens its connections once and the lock is never contended. If you run FrankenPHP without kept connections on a connect-heavy page, expect php-fpm to win.

Docker Desktop on a laptop, with the load generator, Postgres and Redis on the same machine: the absolute numbers say nothing about your servers. The ratios between the rows are the point, and they will move with your page. A page that spends 50 milliseconds in queries gains less from skipping a 6 millisecond connect than one that spends 5.

7. Testing it

Two tests, both against the real Postgres of the demo. TenantConnectionKeepTest builds a TenantConnection straight from DATABASE_URL with tenantConnections set and walks it through tenants:

// tests/TenantConnectionKeepTest.php (abridged)
public function testKeptConnectionsAreReusedAndTheLeastRecentlyUsedIsDropped(): void
{
    $connection = $this->connection(2);
    $before = TenantConnection::$connects;

    $this->query($connection, self::A);
    $this->query($connection, self::B);
    $this->query($connection, self::A);
    self::assertSame(2, TenantConnection::$connects - $before, 'A came back from the parked connection');
    self::assertSame([$this->db(self::B), $this->db(self::A)], $connection->open());

    $this->query($connection, self::C);
    self::assertSame(3, TenantConnection::$connects - $before);
    self::assertSame([$this->db(self::A), $this->db(self::C)], $connection->open(), 'B was the least recently used');
}
Enter fullscreen mode Exit fullscreen mode

A third case begins a transaction on one tenant, switches, and expects the LogicException.

The isolation test from part 1 stays as it is. It runs two tenants through one kernel in multi mode and reads the result back through HTTP, which is the closest a PHPUnit test gets to a worker: one kernel, many requests, the identity map reset in between. Run it after every change to a listener or a decorator, and before you deploy worker mode for the first time.

8. Deploying it

  • One image, two modes. FRANKENPHP_CONFIG decides between classic and worker mode, TENANT_MODE between dedicated and shared. The dedicated deployments of paying tenants can run the same image in worker mode with tenantConnections=1; they never switch.
  • Workers and connections. Start with num_threads equal to the CPUs you give the container and the same number of workers. tenantConnections times workers is the number of Postgres backends one container can hold open; check max_connections before raising it.
  • Health and restarts. /health is open on both modes and answers from a worker, so a wedged worker fails the check. FRANKENPHP_LOOP_MAX recycles a worker after 500 requests by default, and every recycle reopens the kept connections: that is where the 1,026 connections of the benchmark came from. Raise it once the scan test and the isolation test are green, keep it while you are not sure.
  • Messenger workers are unchanged. They were already long-lived, and they take the same tenantConnections parameter.
  • Do not do this when the scan test from part 1 is red. Every class it flags is a cross-tenant leak waiting for the first worker. Fix those under php-fpm first, where they only cost performance, then switch.

Conclusion

  • Worker mode turns the per-request cost of a shared deployment into a per-switch cost, and tenantConnections turns the switch into an array lookup: twelve times the throughput of php-fpm on a page that changes tenant on every request, and a p99 of 10.65 milliseconds instead of 70.
  • The state that must not survive a request is the same state Messenger workers have had to handle for years: the tenant context, cleared on terminate, and the services reset by the kernel. If your workers are clean, your web workers are too.
  • The state that may survive is the one you choose: the placement list for 30 seconds, and up to N open tenant connections, sized by the database server, not by the tenant count.

Start with classic FrankenPHP mode, which already removes FastCGI and the second container and changes nothing in the application. Turn on worker mode when the two tests are green. Add tenantConnections when /whoami shows connects climbing with requests.

Source Code: You can find the full implementation and follow the project's progress on GitHub: https://github.com/mattleads/tenant-shared-demo

Let's Connect!

If you found this helpful or have questions about the implementation, I'd love to hear from you. Let's stay in touch and keep the conversation going across these platforms:

Top comments (0)