Skip to content

Background Tasks

Some work does not belong on an HTTP worker: a CPU-heavy report, a command-line tool, a blocking extension, or anything you want to happen after the response. PAM gives you two building blocks for it:

  • Process pools (Pam\Task\ProcessPool) run a command in a child process while the request Fiber waits without blocking the worker. They work everywhere, including pam dev and single-process servers.
  • Task workers (pam start --task-workers N) are extra PHP workers in your cluster that never receive public traffic. HTTP workers send them payloads with Pam\Shared\Tasks, and the master sends them one tick per second for schedulers and queues.

Neither is a durable job queue. If a task must survive a restart, store it first (database or Redis) and let a queue worker process it; Scheduling shows how Nimbus runs its queue on task workers.

A ProcessPool limits how many child processes run at once and collects their output:

index.php
<?php
declare(strict_types=1);
use Pam\Http\Request;
use Pam\Http\Response;
use Pam\Http\Server;
use Pam\Task\ProcessPool;
$pool = new ProcessPool(maxWorkers: 2);
Server::create(static function (Request $request, Response $response) use ($pool): Response {
$result = $pool->run(['git', 'log', '-1', '--format=%H'], timeout: 5.0);
if (!$result->successful()) {
return $response->json(['error' => trim($result->stderr)], 500);
}
return $response->json(['commit' => trim($result->stdout)]);
})->listen(3000, '127.0.0.1');
public function __construct(
int $maxWorkers = 4, // 1..256 concurrent processes per pool
int $maxOutputBytes = 8 * 1024 * 1024, // per stream; extra output is dropped and flagged
float $terminationGrace = 0.25, // seconds between SIGTERM and SIGKILL on timeout
);

Create the pool once at boot and reuse it; the limit is per pool instance, per worker process.

  • run(array $command, string $stdin = '', float $timeout = 30.0): ProcessResult waits for the process.
  • submit(array $command, string $stdin = '', float $timeout = 30.0): Future returns a future so you can start several and wait with all().
  • php(string $script, array $arguments = [], float $timeout = 30.0) runs a PHP script with the current binary.

Commands are argument lists, never shell strings. PAM starts them with bypass_shell, so arguments cannot be interpreted by a shell, and puts each child in its own process group so a timeout kills the whole tree.

use function Pam\Async\all;
[$thumbnail, $preview] = all([
$pool->submit(['convert', $path, '-resize', '200x200', $thumbPath]),
$pool->submit(['convert', $path, '-resize', '1200x1200', $previewPath]),
]);

Every call returns a Pam\Task\ProcessResult:

Property Description
kind ProcessExitKind::Exited, TimedOut or Signalled
exitCode Exit status, or -1 when it timed out
stdout / stderr Captured output (bounded by maxOutputBytes)
duration Seconds the call took
stdoutTruncated / stderrTruncated Whether output was cut at the limit

successful() is true only for Exited with code 0. A pool that is full waits for a free slot within the same timeout; if none frees up, the result is TimedOut with the message Process timed out while waiting for an execution slot.

Real output from three calls (sleep 0.2, a command that exits with 3, and sleep 5 with a 0.2 second timeout):

[["Exited",0,0.2],["Exited",3,"hi\n",false],["TimedOut",-1]]

Task workers are PHP workers that run your same entry script but listen on a private loopback address. Start a cluster with them:

Terminal window
pam start index.php --workers 4 --task-workers 1

--task-workers accepts a number (at most 64) or auto for one per CPU. The master starts them after the HTTP workers, restarts them like any other worker, and shows them in pam top under the tasks pool.

When an HTTP worker sends a task, PAM makes an HTTP POST / to the task pool with:

  • X-Pam-Task: run (caller waits for a result), dispatch (fire and forget) or tick (once per second, from the master);
  • X-Pam-Task-Token: a random per-cluster token, also present in the task worker’s PAM_TASK_TOKEN environment variable;
  • the payload as the raw body (application/octet-stream).

Your handler decides what a payload means. Check the token, then answer: a run task’s response body is returned to the caller, any non-2xx status is treated as a failure.

index.php
<?php
declare(strict_types=1);
use Pam\Http\Request;
use Pam\Http\Response;
use Pam\Http\Server;
use Pam\Shared\Tasks;
Server::create(static function (Request $request, Response $response): Response {
if (Tasks::isTaskWorker()) {
$token = (string) getenv('PAM_TASK_TOKEN');
$given = (string) $request->getHeader('x-pam-task-token');
if ($token === '' || !hash_equals($token, $given)) {
return $response->status(403)->send('');
}
return match ($request->getHeader('x-pam-task')) {
'tick' => $response->status(204)->send(''),
'dispatch' => (static function () use ($request, $response): Response {
file_put_contents('/tmp/audit.log', $request->body() . "\n", FILE_APPEND);
return $response->status(204)->send('');
})(),
default => $response->send(json_encode([
'square' => json_decode($request->body(), true)['n'] ** 2,
])),
};
}
$results = Tasks::resolve(
[json_encode(['n' => 3]), json_encode(['n' => 4])],
waitMilliseconds: 1000,
);
return $response->json(array_map(
static fn (?string $result) => $result === null ? null : json_decode($result, true),
$results,
));
})->listen(3000, '127.0.0.1');

With --workers 2 --task-workers 1, a request to that server returns:

[{"square":9},{"square":16}]
Method Description
Tasks::available(): bool True in an HTTP worker of a cluster started with task workers
Tasks::isTaskWorker(): bool True inside a task worker (PAM_TASK_WORKER=1)
Tasks::resolve(array $payloads, int $waitMilliseconds): array Runs every payload concurrently and waits; each result is the response body, or null if the task was still running when the wait ended
Tasks::dispatch(array $payloads): void Sends payloads without waiting for them
Tasks::flush(int $timeoutMilliseconds = 5000): int Waits for dispatched payloads to be delivered; returns how many were not

Payloads and results are strings; encode them yourself (JSON is a good default). Results are limited to 256 MiB. resolve() and dispatch() throw RuntimeException when the cluster has no task workers, or when any task fails.

The master sends one tick per second to the task pool and skips a tick while the previous one is still running. Ticks are how schedulers and queue consumers run inside PAM without cron or a separate process.

Situation Use
Run an external binary or script Command::run() or ProcessPool
A blocking PHP extension or legacy driver ProcessPool, or IsolatedPdoPool for databases
CPU-heavy PHP that should not slow HTTP workers Task workers with Tasks::resolve()
Fire-and-forget side effects after a response Task workers with Tasks::dispatch()
Work that must survive a crash or deploy A durable queue (Nimbus RedisJobQueue/DatabaseJobQueue, Laravel queues)
Recurring work Scheduling