Content · Web Development · PHP

Handling Persistent State in Long-Running PHP Workers

Persistent PHP workers retain static state and object references between jobs.

1 views Published Oct 17, 2026 Updated Oct 17, 2026 Admin

Persistent PHP workers retain static state and object references between jobs.

What It Does and When to Use It


Reset tenant-specific state after each job to prevent information crossing job boundaries. A producer publishes work, a consumer executes it, and the broker or scheduler controls delivery and retries.

Requirements, Inputs and Expected Behavior


Confirm the runtime, extension, environment variables, and permissions before running the examples in production. Reset tenant context and resource handles after every task to prevent cross-request leaks.

Example 1: Basic Operation


Reset tenant-specific state after each job to prevent information crossing job boundaries.

<?php
final class JobContext { public ?string $tenantId=null; public function reset(): void { $this->tenantId=null; } }
$context=new JobContext();
foreach (['tenant-a','tenant-b'] as $tenant) {
    try { $context->tenantId=$tenant; echo $context->tenantId, PHP_EOL; }
    finally { $context->reset(); }
}

Example 2: Behavior and Validation


Track memory trends across jobs rather than measuring a single request.

<?php
$handled=0;
while (++$handled <= 3) { gc_collect_cycles(); echo 'Memory: ',memory_get_usage(true),PHP_EOL; }

Practical Example: Application Use


Reset singleton caches or shared services before handling a new tenant.

<?php
final class WorkerCache { private array $entries=[]; public function reset(): void {$this->entries=[];} }
$cache=new WorkerCache(); $cache->reset(); echo 'Cleared per-job cache';

Important Behavior and Edge Cases


The second example highlights: Track memory trends across jobs rather than measuring a single request. The practical example adds: Reset singleton caches or shared services before handling a new tenant.

Comparison with Related Approaches


ApproachWhat changes
Producer, consumer and schedulerA producer publishes work, a consumer executes it, and the broker or scheduler controls delivery and retries.
Choosing safelyAcknowledge completed work and use idempotency to make retries safe.

Common Beginner Mistakes


MistakeCorrect approach
Acknowledging a job before it finishesMark delivery successful only after durable processing succeeds.
Treating retries as harmlessUse idempotency keys and a bounded retry policy with dead-letter handling.
Skipping operational constraintsReset tenant context and resource handles after every task to prevent cross-request leaks.

Key Takeaways


  • Persistent PHP workers retain static state and object references between jobs.
  • Reset singleton caches or shared services before handling a new tenant.
  • Acknowledge completed work and use idempotency to make retries safe.
Share this resourceSend this page to someone who may find it useful.