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
| Approach | What changes |
|---|---|
| Producer, consumer and scheduler | A producer publishes work, a consumer executes it, and the broker or scheduler controls delivery and retries. |
| Choosing safely | Acknowledge completed work and use idempotency to make retries safe. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Acknowledging a job before it finishes | Mark delivery successful only after durable processing succeeds. |
| Treating retries as harmless | Use idempotency keys and a bounded retry policy with dead-letter handling. |
| Skipping operational constraints | Reset 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.