Skip to content

Production Toolkit

PAM HTTP includes small contracts for the infrastructure a production API needs, without choosing that infrastructure for you. Each one ships with a bounded in-memory implementation for development and tests; in a multi-worker deployment you back the contract with Redis, a database or a message broker.

SyncEventDispatcher calls listeners in registration order, in the same request. A listener is a callable or the name of an invokable class resolved from the container:

use Pam\Api\Events\EventDispatcher;
use Pam\Api\Events\SyncEventDispatcher;
$events = (new SyncEventDispatcher($app->container()))
->listen(OrderPlaced::class, SendOrderConfirmation::class)
->listen(OrderPlaced::class, static fn (OrderPlaced $event) => Metrics::increment('orders'));
$app->container()->instance(EventDispatcher::class, $events);
$this->events->dispatch(new OrderPlaced($order->id));

Listeners run synchronously. Push slow work to a job instead.

The jobs contracts describe an at-least-once lifecycle that durable adapters implement:

  • JobDispatcher::dispatch($job, maximumAttempts: 3, delaySeconds: 0) enqueues a job and returns a JobEnvelope.
  • JobQueue reserves a job with a lease, then completes it, releases it with a delay or moves it to the dead-letter set.
  • JobWorker runs one job at a time against any JobQueue.

MemoryJobDispatcher implements both JobDispatcher and JobQueue with a bound of 10,000 queued jobs:

use Pam\Api\Jobs\JobOutcome;
use Pam\Api\Jobs\JobWorker;
use Pam\Api\Jobs\MemoryJobDispatcher;
$queue = new MemoryJobDispatcher();
$queue->dispatch(new SendInvoice($invoiceId), maximumAttempts: 3);
$worker = new JobWorker(
$queue,
static function (object $job): JobOutcome {
// Do the work.
return JobOutcome::Complete;
},
leaseSeconds: 30,
retryDelaySeconds: 5,
);
$result = $worker->runOne(); // JobRunResult::Idle, Completed, Retried or DeadLettered

Attempts are counted when a lease is reserved, and expired leases can be reclaimed. A thrown exception or JobOutcome::Retry releases the job after the retry delay until it runs out of attempts; then, or with JobOutcome::DeadLetter, it moves to the dead-letter set. Only the failure class name is kept, never the exception message.

Cross-process queues should store jobs as data, never as serialized PHP objects. Implement SerializableJob and encode through a JobCodec that lists the allowed job classes:

use Pam\Api\Jobs\JobCodec;
use Pam\Api\Jobs\SerializableJob;
final readonly class SendInvoice implements SerializableJob
{
public function __construct(public int $invoiceId) {}
public static function jobName(): string
{
return 'billing.send-invoice';
}
public function toJobPayload(): array
{
return ['invoiceId' => $this->invoiceId];
}
public static function fromJobPayload(array $payload): self
{
return new self($payload['invoiceId']);
}
}
$codec = new JobCodec([SendInvoice::class]);
$json = $codec->encode(new SendInvoice(42));
$job = $codec->decode($json);

The envelope is versioned JSON limited to 64 KiB and a nesting depth of 16. Job names are lowercase identifiers (at most 128 bytes), and a codec accepts at most 1,000 job types. The codec never instantiates a class name taken from the payload.

Implement HealthCheck and collect checks in a HealthRegistry:

use Pam\Api\Health\HealthCheck;
use Pam\Api\Health\HealthRegistry;
use Pam\Api\Health\HealthResult;
use Pam\Api\Health\HealthState;
final readonly class QueueHealthCheck implements HealthCheck
{
public function check(): HealthResult
{
return new HealthResult(HealthState::Healthy, ['pending' => 0]);
}
}
$health = (new HealthRegistry())
->add('database', new DatabaseHealthCheck($arcano))
->add('queue', new QueueHealthCheck());
$app->get('/health/ready', static function (Request $request, Response $response) use ($health): Response {
$report = $health->run();
return $response->json($report, $report['state'] === HealthState::Healthy->value ? 200 : 503);
});

run() returns the worst state (Healthy = 1, Degraded = 2, Unhealthy = 3) and each check’s state and details. Keep secrets and connection strings out of the details.

RetryPolicy retries an operation with exponential backoff. The operation receives the attempt number:

use Pam\Api\Resilience\RetryPolicy;
$retry = new RetryPolicy(
attempts: 3,
initialDelayMilliseconds: 10,
when: static fn (Throwable $error): bool => $error instanceof TransientNetworkError,
);
$rates = $retry->run(static fn (int $attempt) => $client->fetchRates());

The delay doubles after each failure (10 ms, 20 ms, …). Without when, every exception is retried.

use Pam\Api\Resilience\CircuitBreaker;
use Pam\Api\Resilience\CircuitOpenException;
$breaker = new CircuitBreaker(failureThreshold: 5, cooldownSeconds: 30);
try {
$profile = $breaker->call(static fn () => $crm->profile($id));
} catch (CircuitOpenException) {
$profile = null; // fail fast while the dependency recovers
}

After failureThreshold consecutive failures the circuit opens and calls fail immediately with CircuitOpenException. After the cooldown it is HalfOpen and lets a call through; a success closes it. The breaker’s state lives in the object: register it as a singleton to share it across requests in a worker.

Observers see every request from start to finish, after the response is built and before the request scope is destroyed. Implement RequestLifecycleObserver and register it with observe():

use Pam\Api\Lifecycle\RequestLifecycleObserver;
final class SlowRequestLogger implements RequestLifecycleObserver
{
private array $started = [];
public function starting(Request $request): void
{
$this->started[spl_object_id($request)] = hrtime(true);
}
public function finished(Request $request, Response $response, ?Throwable $failure): void
{
$elapsed = (hrtime(true) - ($this->started[spl_object_id($request)] ?? hrtime(true))) / 1e6;
unset($this->started[spl_object_id($request)]);
if ($elapsed > 500) {
error_log(sprintf('slow %s %s %.1fms', $request->method, $request->path, $elapsed));
}
}
}
$app->observe(new SlowRequestLogger());

Observers start in registration order and finish in reverse order. They receive the failure when the request threw. An observer that throws during finished() is logged and cannot stop the remaining observers or the scope cleanup.

MemoryProfiler is a bounded observer for development and tests. It is disabled unless you pass a mode:

use Pam\Api\Profiler\MemoryProfiler;
use Pam\Api\Profiler\ProfilerMode;
$profiler = new MemoryProfiler(ProfilerMode::Development, maximumProfiles: 500);
$app->observe($profiler);

Each profiled response gets an x-debug-token header. Look profiles up with find($token) or list them with recent(50). A RequestProfile keeps only the method, path, status, duration, memory delta and failure class; headers, tokens and bodies are never stored.

For metrics, ObserveRequestMiddleware reports one RequestObservation per request to your RequestObserver: method, the route pattern (such as /users/{id}, which keeps metric cardinality low), status, duration in seconds and the exception class, if any.

use Pam\Api\Middleware\ObserveRequestMiddleware;
use Pam\Api\Observability\RequestObservation;
use Pam\Api\Observability\RequestObserver;
final readonly class PrometheusObserver implements RequestObserver
{
public function record(RequestObservation $observation): void
{
// $observation->method, ->route, ->status, ->durationSeconds, ->exceptionClass
}
}
$app->middleware(new ObserveRequestMiddleware(new PrometheusObserver(), $app->container()));

PAM itself also exports runtime and route metrics; see Observability.

  • Keep request, user, tenant and transaction state in scoped bindings.
  • Replace every memory store with a shared, atomic adapter before running more than one worker.
  • Validate configuration at boot with Configuration.
  • Run migrations as a deployment step, not at worker start.
  • Test success, validation failure, exception, timeout and cancellation paths with the test client, then exercise the real listener.
  • Run pam doctor after dependency changes.