Content · Web Development · PHP

PHP Queue Workers: Graceful Shutdown and Retries

A robust worker combines signal-driven drain, retry limits and explicit job acknowledgments.

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

A robust worker combines signal-driven drain, retry limits and explicit job acknowledgments.

What It Does and When to Use It


A CLI consumer finishes or requeues in-flight work after it receives a stop signal. 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. Never acknowledge a message before work commits, or the job may be lost.

Example 1: Basic Operation


A CLI consumer finishes or requeues in-flight work after it receives a stop signal.

<?php
$stop=false;
if (function_exists('pcntl_signal')) { pcntl_async_signals(true); pcntl_signal(SIGTERM,static function () use (&$stop) {$stop=true;}); }
while (!$stop) { /* Fetch one job, process, then acknowledge. */ break; }
echo 'No further messages will be fetched';

Example 2: Behavior and Validation


Send permanently failing jobs for inspection once retry limits are reached.

<?php
$job=['id'=>12,'attempt'=>3]; $limit=5;
$action=$job['attempt'] >= $limit?'dead_letter':'requeue';
echo $action;

Practical Example: Application Use


Apply jitter for transient errors and keep the work idempotent.

<?php
$message=['id'=>'task:204','attempt'=>2];
$delayMs=random_int(0,min(30000,250*2**$message['attempt']));
echo 'Next attempt in ', $delayMs,' ms';

Important Behavior and Edge Cases


The second example highlights: Send permanently failing jobs for inspection once retry limits are reached. The practical example adds: Apply jitter for transient errors and keep the work idempotent.

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 constraintsNever acknowledge a message before work commits, or the job may be lost.

Key Takeaways


  • A robust worker combines signal-driven drain, retry limits and explicit job acknowledgments.
  • Apply jitter for transient errors and keep the work idempotent.
  • Acknowledge completed work and use idempotency to make retries safe.
Share this resourceSend this page to someone who may find it useful.