Async I/O
Every HTTP request in PAM runs inside its own PHP Fiber. When your code waits for something (a timer, a socket, a DNS lookup, a file, a child process), PAM suspends that Fiber and hands the wait to its Rust/Tokio event loop. The worker is free to run other requests in the meantime, and your Fiber resumes exactly where it stopped, with its local variables and try/finally blocks intact.
You keep writing ordinary, top-to-bottom PHP. There are no promises to chain and no callbacks to nest: the functions in the Pam\Async namespace and the native I/O classes simply return their result when it is ready.
<?php
declare(strict_types=1);
use Pam\Http\Request;use Pam\Http\Response;use Pam\Http\Server;
use function Pam\Async\delay;
Server::create(static function (Request $request, Response $response): Response { delay(0.2); // suspends this request only; the worker keeps serving others
return $response->json(['slept' => 0.2]);})->listen(3000, '127.0.0.1');How Suspension Works
Section titled “How Suspension Works”request Fiber ──► Pam\Async\delay() / File::read() / Dns::resolve() ... │ Fiber::suspend(operation envelope) ▼ Rust command boundary ──► Tokio runtime waits (no PHP running) │ ▼ completion resumes the same Fiber with the resultTwo kinds of waits exist:
- Native operations (timers, socket readiness, DNS, file reads and writes, child processes, signals, response chunks) are executed by Tokio. They only exist inside a PAM HTTP request Fiber; outside one, every API in this page falls back to a blocking PHP equivalent (for example
usleep()orfile_get_contents()) so the same code still works in CLI scripts and tests. - Futures created with
async()are PHP Fibers driven by a small cooperative scheduler that lives in the request.
Every native wait is bounded by the smaller of its own timeout and the request deadline (requestTimeoutMs, 30 seconds by default). When a client disconnects, PAM cancels the request Fiber and runs its cleanup instead of resuming it later.
Timers
Section titled “Timers”delay() pauses the current Fiber for a number of seconds:
use function Pam\Async\delay;
delay(0.05); // 50 msInside a request it is a Tokio timer. In a plain script (no current Fiber) it calls usleep(). A negative value throws InvalidArgumentException.
Futures
Section titled “Futures”async() wraps a callable in a Pam\Async\Future. await() waits for one future and all() waits for many, returning their results with the original keys:
use function Pam\Async\all;use function Pam\Async\async;use function Pam\Async\await;use function Pam\Async\delay;
$profile = async(static function (): array { delay(0.3); // pretend this is a slow API call
return ['name' => 'Alice'];});
$orders = async(static function (): array { delay(0.3);
return [['id' => 1, 'total' => 42]];});
$results = all(['profile' => $profile, 'orders' => $orders]);// ['profile' => [...], 'orders' => [...]] after ~0.3 s, not 0.6 sRunning this in a request returns both results in about 300 ms:
{"results":{"a":"a","b":"b"},"ms":300}Futures Are Lazy
Section titled “Futures Are Lazy”A future does not start when you create it. It runs while some code in the same request is inside await() or all(), which drive the request’s scheduler. This keeps work predictable, but it has one consequence worth remembering:
$log = [];$future = async(static function () use (&$log): void { $log[] = 'future ran';});
$log[] = 'before await';await($future);
// $log === ['before await', 'future ran']Future States
Section titled “Future States”Future::state() returns a Pam\Async\FutureState case: Pending, Running, Fulfilled, Rejected or Cancelled. isComplete() is true for the last three. An exception thrown inside the callable is stored and rethrown by await().
Timeouts
Section titled “Timeouts”Pass a timeout in seconds to await() or all(). When it expires, the future is cancelled and a RuntimeException is thrown:
use function Pam\Async\async;use function Pam\Async\await;use function Pam\Async\delay;
try { await(async(static fn () => delay(2.0)), timeout: 0.1);} catch (RuntimeException $exception) { return $response->json(['error' => $exception->getMessage()], 504);}{"error":"Asynchronous operation timed out."}all($futures, timeout: 1.0) applies the timeout to each await() in turn, so the worst case is one timeout per future. Wrap the whole batch in a deadline when you need one budget for the group.
When a request finishes, PAM cancels every future that request left incomplete, so an abandoned future can never resume into the next request.
Deadlines
Section titled “Deadlines”Pam\Async\Deadline is an absolute point in time you can pass around and check:
use Pam\Async\Deadline;
$deadline = Deadline::after(0.5);
foreach ($batches as $batch) { $deadline->throwIfExpired(); // RuntimeException: The operation deadline was exceeded. $importer->import($batch);}
$deadline->remaining(); // seconds left, never negative$deadline->isExpired();Use remaining() as the timeout for the next call so that a chain of operations shares one budget.
Cancellation Tokens
Section titled “Cancellation Tokens”A Pam\Async\CancellationToken lets one piece of code stop another. It is cancelled when you call cancel() or when its optional deadline expires:
use Pam\Async\CancellationToken;use Pam\Async\Deadline;use Pam\Http\Client;
$token = new CancellationToken(Deadline::after(2.0));
$response = (new Client(timeout: 10.0))->get( 'https://api.example.com/reports', cancellation: $token,);The HTTP client, the Redis client, the stream classes and the low-level socket functions accept a token and check it between waits. In your own loops, call $token->throwIfCancelled() or $token->isCancelled().
Request-Local Context
Section titled “Request-Local Context”Static properties and globals are shared by every request a worker serves. For values that belong to one request (a tenant, a user, a correlation ID), use Pam\Async\FiberContext, which stores values per Fiber:
use Pam\Async\FiberContext;use function Pam\Async\async;use function Pam\Async\await;
FiberContext::set('tenant', 'acme');
$child = async(static fn (): string => FiberContext::get('tenant'));
await($child); // "acme": futures inherit a snapshot of the parent's context| Method | Purpose |
|---|---|
set($key, $value) / setMany($values) |
Store values for the current Fiber |
get($key, $default = null) |
Read a value |
snapshot() / replace($values) |
Copy or replace the whole bag |
remove($key) / removeMany($keys) / clear() |
Forget values |
A future receives a copy of the context at creation time; changes it makes do not leak back to the parent. PAM clears the context when the request ends. For resources that need cleanup, see Memory & State.
Sockets and Streams
Section titled “Sockets and Streams”The low-level stream functions work on any PHP stream resource and suspend instead of blocking:
| Function | Description |
|---|---|
connect($address, $timeout = 10.0, $tls = false, $cancellation = null, $contextOptions = []) |
Open a non-blocking TCP (or TLS) connection. "host:port" is treated as tcp://host:port. |
read($stream, $length = 8192, $timeout = null, $cancellation = null) |
Wait until readable, then read up to $length bytes. |
write($stream, $data, $timeout = null, $cancellation = null) |
Write all of $data, waiting for writability between partial writes. |
readable($stream, ...) / writable($stream, ...) |
Wait for one stream. |
waitForStreams($read, $write = [], $timeout = null, $cancellation = null) |
Wait until any of several streams is ready. |
use function Pam\Async\connect;use function Pam\Async\read;use function Pam\Async\write;
$socket = connect('127.0.0.1:6379', timeout: 2.0);write($socket, "PING\r\n", timeout: 2.0);$reply = read($socket, 64, timeout: 2.0); // "+PONG\r\n"fclose($socket);For most code, the object API in Streams & SSE is more convenient: it adds a bounded highWaterMark, chunk iteration and piping.
DNS, Files, Processes and Signals
Section titled “DNS, Files, Processes and Signals”PAM ships native, Tokio-backed versions of the other common blocking calls. They are documented in Filesystem & Processes:
use Pam\Filesystem\File;use Pam\Http\Client;use Pam\Net\Dns;use Pam\Process\Command;
$addresses = Dns::resolve('example.com', timeout: 2.0);$config = File::read(__DIR__ . '/config.json', maxBytes: 1_048_576);$health = (new Client(timeout: 3.0))->get('https://example.com/health');$job = Command::run(['git', 'rev-parse', 'HEAD'], timeout: 2.0);Pam\Async\onSignal($signal, $handler) installs a pcntl signal handler and returns a SignalWatcher; calling cancel() on it (or letting it be destroyed) restores the previous handler. It requires the pcntl extension.
Blocking Libraries
Section titled “Blocking Libraries”Ordinary synchronous PHP libraries keep working, but while they block (a PDO query, file_get_contents() on a URL, sleep()), the whole worker waits with them and no other request on that worker can progress. You have four options:
- Use a PAM-native API: HTTP Client, Redis, Filesystem & Processes.
- Move the call to a child process with
ProcessPoolorIsolatedPdoPool. - Use an Amp or Revolt integration (see below).
- Run more workers with
pam start --workers Nand accept that each blocking call occupies one.
Amp and Revolt
Section titled “Amp and Revolt”await() also accepts third-party future objects that have an await() method, such as Amp 3 futures. When such a future suspends the request Fiber without a PAM operation, PAM runs the package’s own Revolt loop until the future completes, then resumes dispatch.
This is a compatibility bridge, not a Tokio driver for Revolt: while the third-party loop runs, it occupies the worker. Prefer PAM-native operations on latency-sensitive paths, and pin the exact package versions you rely on in your own tests.
Next Steps
Section titled “Next Steps”- Concurrency: channels, mutexes and fan-out patterns.
- HTTP Client: call other services without blocking the worker.
- Request Lifecycle: what happens before and after your handler runs.