Overlapping Requests and Framework State
In worker mode, when the request a worker is running suspends, the worker can take a new request or resume one it has paused. Requests that overlap this way share everything the worker keeps between requests: the outer scope, static properties, the service container and its singletons, open connections (see What persists).
What PHP itself keeps for a request (its superglobals, its session, the ini directives and the working directory it changed) travels with it, within the limits listed in What gets reset between requests. The file mode mask a request sets with umask() is shared by the whole process until that request pauses or ends. Code that keeps what belongs to one request in the request object and in local variables is not affected. Code that keeps it in a shared object hands it to whichever request runs next, and that is where most full-stack frameworks keep the current request, user, route and locale.
RUNTIME_HOOKS is where this usually starts to matter, because it turns waits inside the framework and its database and HTTP clients into suspension points. This page covers when requests overlap, what goes wrong in Laravel, Symfony and Yii3, what happens to a transaction on a shared connection, and which setups avoid both.
When requests overlap
Overlap needs worker mode. In Traditional, Framework and SPA modes every request starts from a clean PHP state and no request suspends to let another one run on its thread; RUNTIME_HOOKS makes no request suspend there (see Runtime Hooks).
In worker mode without RUNTIME_HOOKS, overlap starts only at OxPHP's own waits:
oxphp_sleep()andoxphp_usleep();oxphp_async_await()and the otheroxphp_async_await_*()functions;- a blocking send or receive on an
OxPHP\Shared\Channeland an acquire that waits on a saturatedOxPHP\Shared\Pool, where those suspend the fiber rather than the thread; oxphp_stream_flush()orflush()in a streaming response, when the client reads more slowly than the script writes (see Server-Sent Events).
A worker whose requests reach none of these runs them one after another. Each of them still finds what the previous one left in shared objects, so the integration has to reset that between requests, but no two requests use it at the same time.
With RUNTIME_HOOKS, the hooked waits are added, and they sit inside code you did not write:
sleep: everysleep()andusleep(), in a retry loop or a rate limiter;streams: every reply a client waits for on a plaintcp://stream (mysqlnd, so PDO_MySQL and mysqli; phpredis; the HTTP stream wrappers), andstream_select(). For an application on MySQL or Redis over TCP that means nearly every request;net(Linux only, listed together withstreams): replies on TLS streams and on sockets that are not TCP (MySQL reached throughlocalhost, which the client reads as its Unix socket, or a database or Redis behind TLS), and connects, TLS handshakes and writes that wait for room;curl(Linux only, with libcurl loaded as a library of its own, as in the official images): every request made through ext/curl, including those of Guzzle with its default handler, Symfony HttpClient'sCurlHttpClient, and the SDKs built on either.
Clients that wait inside their own library do not suspend: pdo_pgsql, which waits inside libpq, is one (see The net category). Under streams, a request that waits for a PDO, mysqli or phpredis connection another request holds does suspend, whatever the driver (see Transactions on a shared connection).
With any hook category on, a worker runs its first request alone for a bounded time, so that a container or router built during that request is finished before another request can see it (see Hooked waits and shared application state). That covers a build, once per worker start. It does nothing for the state each request sets for itself.
Request state in shared objects
The failure has the same shape in every framework that has it:
- Request A sets the current user and locale on a shared service, then suspends.
- Request B starts on the same worker and sets its own.
- A resumes and reads B's user and B's locale.
- When B ends, the reset that follows it clears or replaces the state A is still using.
OxPHP raises no error and logs nothing. The symptom is a response carrying another client's data, or an exception from a framework that refuses to set its state twice.
| Framework | Where the current request's state lives | When requests overlap |
|---|---|---|
| Laravel | Static properties: the application in Container::$instance, the facade root and the resolved facades in Facade::$app and Facade::$resolvedInstance. An integration built on Laravel Octane sets a clone of the application there for each request, points shared singletons at that clone (the router, the authorization gate, the view factory, and the database and cache managers among them), and sets the translator's and Carbon's locale |
A request that resumes finds whatever application the last request to start or end left in the statics (another request's clone, or the worker's own application), with that request's user and locale. Restoring the statics when a request resumes would not be enough: the shared singletons still point at the other clone |
| Symfony | Shared services: RequestStack, the security TokenStorage, the router's RequestContext, the translator's locale, and Doctrine's EntityManager, whose unit of work tracks every entity loaded through it, whichever request loaded it |
A request can find another request's current request, user, route context and locale in them, or none, depending on which request last set or reset them, unless the integration keeps these services per request. A flush() in one request writes the changes another request has made to its entities and not flushed yet, even when neither request begins a transaction itself. That happened even with an integration that keeps the request stack, router context, security token and locale per request fiber, because the EntityManager stayed one per worker |
| Yii3, one container per worker | Shared services, among them the router's CurrentRoute, which accepts a route and a URI once and is reset after each request |
A request that starts while another is suspended past routing fails with LogicException (Can not set URI since it was already set.), and the reset after it clears the route of the request still running |
| PSR-15 application that keeps route, user and locale in request attributes | The request object passed down the middleware stack | That state travels with its request. What the application's own services store is shared like anything else |
Checked against Laravel 13.43 with Octane 2.25, Symfony 8.1 with Doctrine ORM 3.8, and yiisoft/router 4.0.
What isolates such a framework is an integration that keeps these services per request. One way is per request fiber: in worker mode each request runs in a Fiber of its own, and Fiber::getCurrent() returns it anywhere in the request's code except inside fibers the application starts itself and in the destructors PHP's cycle collector runs, which get a fiber of their own. The other is a container built for each request, at the price of building it every time. That works only for a framework whose code gets its services from that container rather than through static properties. It does for Yii3, not for Laravel, whose application and facades are static, so a clone per request is shared as soon as the next request sets its own.
Checking an application
The shape is easy to reproduce. This worker script keeps a user in a static property, as a framework's "current user" service would:
<?php
final class CurrentUser
{
public static ?string $name = null;
}
oxphp_worker(function () {
$user = $_GET['user'] ?? 'anonymous';
CurrentUser::$name = $user;
if (isset($_GET['wait'])) {
oxphp_sleep(1.0); // a hooked query, an await or a streaming flush does the same
}
echo "$user sees ", CurrentUser::$name, "\n";
});Run it with WORKER_MODE_ENABLED=true, ENTRY_FILE pointing at it and PHP_WORKERS=1, so that both requests land on one worker, and send the second request while the first one waits:
curl 'http://localhost/?user=alice&wait=1' & sleep 0.2; curl 'http://localhost/?user=bob'; waitbob sees bob
alice sees bobTo check a real application, add a route that sets the user or locale through the framework, calls oxphp_sleep(1.0) and reads it back, and send the same two requests.
Transactions on a shared connection
A connection opened before oxphp_worker(), or kept by the framework's database layer for the life of the worker, is one connection for every request on that worker. A transaction on it belongs to the connection, not to the request that began it.
Without the streams category
Nothing then claims the connection for a request. A request that suspends while its transaction is open lets the statements of any request that runs meanwhile on the same connection into that transaction, and they are committed or rolled back with it rather than with their own request. Request B can answer 201 Created for a row that request A's rollback then removes.
That holds for every suspension point listed above, and for the hooked waits of the sleep and curl categories: a Guzzle call between beginTransaction() and commit() is enough.
With the streams category
Under streams a request that has used a PDO, mysqli or phpredis connection holds it until the request ends, and another request's call on it waits (see A fiber keeps the connection until its request ends). B's plain write in the example above then waits for A to end and is kept. Two problems remain.
The requests that use the connection run one after another, each from its first query to its end, not only for the length of each query. A PDO or mysqli call that waits past its bound goes ahead without the claim, as it would without streams, with one exception. It throws and sends nothing when the connection has a transaction open, or on MySQL runs with autocommit off or is partway through a query, and that does not count as the caller's own (mysqli::close() still closes a connection partway through a query, unless that would free what another request or task is still using). A transaction the caller begins itself there holds the connection against the holder in turn (see Past the bound for which transactions count). A phpredis call throws either way.
The framework's count of open transactions is a property of its shared connection object ($transactions on Laravel's Illuminate\Database\Connection, $transactionNestingLevel on Doctrine DBAL's Connection), and nothing claims that. When B's first call on the connection is beginTransaction() while A's transaction is open, it finds A's transaction counted and treats its own as nested in it, so instead of beginning a transaction it asks for a savepoint, and that statement waits for A. A request that has used the connection before either holds it or has already waited for A's request to end, and is not affected. What happens next depends on the library:
- Laravel raises its count only once the savepoint is created. A's commit or rollback therefore ends the real transaction, and B's savepoint then runs outside any transaction. PostgreSQL refuses it with
SAVEPOINT can only be used in transaction blocks, so B's request fails; later requests are not affected. - Doctrine DBAL raises its count before it sends anything, so A's commit or rollback goes to B's savepoint, which does not exist yet, and fails. A failed commit still lowers the count; if A's error path then rolls back, as
transactional()does, the real transaction ends, A fails as well as B, and later requests are not affected. If A's request ends on the error without a rollback, or its rollback is the call that failed, the count never returns to zero and on PostgreSQL the real transaction stays aborted, so every later request on that worker that uses the connection fails withSQLSTATE[25P02](current transaction is aborted). That lasts until the connection is closed or the worker is replaced. DoctrineBundle closes it on the first request at leastidle_connection_ttl(600 seconds by default) after it connected. OxPHP does not replace the worker for this: an exception the application turns into a500is not one of the failures that recycle a worker.
Checked against Laravel 13.43 and Doctrine DBAL 4.6 on PostgreSQL. On MySQL the count goes wrong the same way, but how the server then answers the misplaced savepoint statements was not checked.
A transaction is the request's own only on a connection that request holds alone for as long as the transaction lasts, rather than on the connection the framework keeps for the worker. That is one it opens itself without PDO::ATTR_PERSISTENT, or one it acquires from a Shared\Pool.
Giving a transaction its own connection
Take the connection from a Shared\Pool and keep the whole transaction, from beginTransaction() to commit() or rollBack(), inside one with() call. While the closure runs, its connection is out of the pool and no other request gets it, whatever the request waits on in between. A request that finds every connection taken waits for one, suspended, as What a wait holds describes.
<?php
$db = new OxPHP\Shared\Pool(
factory: fn () => new PDO(getenv('DB_DSN'), getenv('DB_USER'), getenv('DB_PASS'), [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]),
maxSize: 16,
);
oxphp_worker(function () use ($db) {
$orderId = $db->with(function (PDO $conn): int {
if ($conn->inTransaction()) {
$conn->rollBack(); // left open by a request that died inside it
}
$conn->beginTransaction();
try {
$conn->exec("INSERT INTO orders (status) VALUES ('new')");
$id = (int) $conn->lastInsertId();
chargeCard($id); // an HTTP call: the request suspends here
$conn->commit();
return $id;
} catch (\Throwable $e) {
$conn->rollBack();
throw $e;
}
});
// ...
});with() gives the connection back as it is. The catch keeps an exception from returning it with the transaction still open. The check at the top covers what the catch cannot: a fatal error inside the closure, such as running out of memory, still gives the connection back with its transaction open, and the next request to take it would otherwise run its statements in that transaction.
Only the code inside the closure runs on the pool's connection. The framework's database layer keeps using the connection it holds for the worker.
Under the streams category the claim on a pooled connection lasts until the end of the request that used it, as on any other connection, and not only until with() gives it back. The next request to take that connection from the pool waits until that request has ended, up to the bound. Nothing is mixed up while it waits, but a request that goes on to a long wait after its transaction makes the next user of its connection wait as long.
Checked on MySQL 9 with PDO. On the worker's own connection, a row a second request inserted while the first was suspended inside its transaction was lost with the first request's rollback when RUNTIME_HOOKS was off. With RUNTIME_HOOKS=1 the second request waited for the first and its row was kept. Through the pool the row was kept either way.
Running these frameworks
- Framework mode (
ENTRY_FILE=index.phpwith worker mode off) is how the framework examples run. Every request starts from a clean state, nothing overlaps on a thread, andRUNTIME_HOOKSmakes no request suspend. - Worker mode without overlap: leave
RUNTIME_HOOKSunset and keep every wait listed under When requests overlap out of the request path (oxphp_sleep(), awaits, streaming responses and the rest). The worker then runs its requests one after another, and the integration only has to reset state between them. - Worker mode with overlap (
RUNTIME_HOOKS, or any of those suspension points) needs two things. Request state has to be kept per request, as above. Any request that opens a transaction needs a connection of its own rather than the worker's shared one. Keeping request state per request does not give a request a connection of its own.
Prompts for your agent
These prompts assume an agent with the OxPHP documentation MCP server connected. The agent reads the pages it needs itself.
Check whether requests that overlap on one OxPHP worker can leak state or break transactions in my application. Read the `features/overlapping-requests` page through the OxPHP documentation MCP server.
Find every suspension point in the request path, every shared object in this repository that holds the current request, user, route or locale, and every transaction on a connection the worker keeps. Then tell me which of the setups on that page to run and show me the fixes.See also
- Runtime Hooks: the hook categories and what each one makes suspend
- Shared Connections Under Runtime Hooks: how one connection behaves when several fibers share it
- Fiber Multiplexing: how a worker runs several requests at once and where it can suspend one
- Worker State Between Requests: what a worker resets between requests and what it keeps