> ## Documentation Index
> Fetch the complete documentation index at: https://docs.apivalk.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Run in FrankenPHP worker mode

> Boot Apivalk once per worker and serve every request from the same instance. What FrankenPHP resets between requests, what it keeps, and what that means for your controllers and middleware.

In worker mode FrankenPHP starts your script once, keeps it in memory and hands it one request after another. Apivalk is built for that: you create the `Apivalk` instance once, and every request runs through it. The route index, the JWKS key set and your container stay warm instead of being rebuilt per request.

## What survives a request and what does not

FrankenPHP resets per request:

* the superglobals (`$_SERVER`, `$_GET`, `$_POST`, `$_FILES`, `$_COOKIE`), except `$_ENV`
* the request body behind `php://input`
* response headers and output

Everything else lives as long as the worker:

* every object you create before the request loop, including `Apivalk`, the router, the middleware stack and your container
* static properties and static variables
* `set_exception_handler()`, `ini_set()`, `setlocale()` and other process settings

`Apivalk::run()` builds the PSR-7 request from the superglobals and `php://input` and sends the response through `header()` and `echo`, which is exactly the part FrankenPHP resets, so it needs no adapter.

RoadRunner and Swoole hand the application a request object and leave the superglobals empty. Since `Apivalk` is a PSR-15 request handler, you can pass their PSR-7 request to `$apivalk->handle()` and hand the returned response back to the runtime. Apivalk does not test that setup, so this guide covers FrankenPHP only.

## The worker script

Build Apivalk once, then loop over requests. Pin the image to PHP 8.5, because the `latest` FrankenPHP image ships a newer PHP:

```dockerfile theme={null}
FROM dunglas/frankenphp:1.14-php8.5
```

```php theme={null}
<?php

declare(strict_types=1);

// Keep running when a client disconnects mid-response, the next request still needs this worker.
ignore_user_abort(true);

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

// Your bootstrap returns the configured Apivalk instance, see "Configure Apivalk".
$apivalk = require __DIR__ . '/../bootstrap/apivalk.php';

// run() answers application failures with a 500 and malformed requests with a 400, see below.
$handleRequest = static fn() => $apivalk->run();

$maxRequests = (int)($_SERVER['MAX_REQUESTS'] ?? 0);

for ($handled = 0; $maxRequests === 0 || $handled < $maxRequests; $handled++) {
    $keepRunning = \frankenphp_handle_request($handleRequest);

    // Objects in reference cycles are freed here instead of during a later request.
    gc_collect_cycles();

    if (!$keepRunning) {
        break;
    }
}
```

A `Caddyfile` that sends every request to that script, with two workers:

```caddyfile theme={null}
{
	auto_https off
}

:8080 {
	root /app/public

	php_server {
		try_files {path} index.php
		worker {
			file /app/public/index.php
			num 2
		}
	}
}
```

Start it with `frankenphp run --config /app/Caddyfile`. The worker `file` takes an absolute path. Apivalk's CI runs exactly this setup against its integration API on every push, see `Tests/Smoke/FrankenPhp/`.

* **No `try`/`catch` for application failures.** `handle()` logs every unhandled throwable via your PSR-3 logger and answers with the exception handler's response, a 500 by default; a handler that fails itself is logged and replaced by the default 500. A request nyholm/psr7 cannot represent, such as a `Host` port above 65535, gets a 400. Two things still escape `run()` and end the worker: the `LogicException` the emitter throws when something was output before the response, and an exception from your PSR-3 logger.
* **`MAX_REQUESTS`** restarts a worker after that many requests, a cheap guard against slow memory growth in your own code. `0` means unlimited.

## What Apivalk does for you

* **Route index.** The router decodes the cached route index once and keeps it until the cache entry expires, so requests do not read the cache files. Routes are still built per request, they never leak between requests.
* **JWKS keys.** `JwtAuthenticator` keeps the key set in memory for as long as the cache entry lives (one hour) and fetches it again afterwards. A token signed with a key that is not in the set yet, for example right after your identity provider rotated its keys, triggers one more download, but only when the key set is older than a minute. With a cache, the age is read from the cache entry, so the limit holds across processes.
* **Built-in middleware holds no request state.** Authentication, security, validation and rate limiting keep everything about the current request on the request object, so nothing carries over to the next one.

## What you have to watch

* **Controllers and middleware must be stateless.** Request data belongs on the request, never in a property of a controller or middleware. A controller your container hands out as a shared service lives as long as the worker, so anything it stores in `$this` is visible to the next request. Either keep controllers stateless or register them as non-shared services.
* **No request data in statics.** A static cache keyed by user, tenant or token survives the request and leaks into the next one.
* **Deployments.** The route index and your code are loaded once per worker. Restart FrankenPHP or the container when you deploy; in development the worker `watch` option restarts workers on file changes.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.