Content · Web Development · PHP

Handling Graceful Shutdown of Workers

Shutdown orchestration needs a stop flag, bounded drain time and acknowledgment after completion.

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

Shutdown orchestration needs a stop flag, bounded drain time and acknowledgment after completion.

What It Does and When to Use It


Set a signal flag and stop fetching new work after the current task. 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. A process manager may send SIGKILL after its timeout, so job work must be retry-safe.

Example 1: Basic Operation


Set a signal flag and stop fetching new work after the current task.

<?php
if (!function_exists('pcntl_signal')) throw new RuntimeException('PCNTL required in Unix CLI');
$stop=false;
pcntl_async_signals(true);
pcntl_signal(SIGTERM, static function () use (&$stop): void { $stop=true; });
while (!$stop) { usleep(100000); /* Poll broker for one job here. */ }
echo 'Worker stopped accepting jobs';

Example 2: Behavior and Validation


Acknowledge the message after success, not immediately on delivery.

<?php
$inFlight=true;
try { /* Process an acknowledged job only after it succeeds. */ }
finally { if ($inFlight) error_log('Job completion must be confirmed'); }

Practical Example: Application Use


Check PCNTL availability and supervisor grace time before deployment.

php -m | grep pcntl
systemctl show php-worker -p TimeoutStopUSec

Important Behavior and Edge Cases


The second example highlights: Acknowledge the message after success, not immediately on delivery. The practical example adds: Check PCNTL availability and supervisor grace time before deployment.

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 constraintsA process manager may send SIGKILL after its timeout, so job work must be retry-safe.

Key Takeaways


  • Shutdown orchestration needs a stop flag, bounded drain time and acknowledgment after completion.
  • Check PCNTL availability and supervisor grace time before deployment.
  • Acknowledge completed work and use idempotency to make retries safe.
Share this resourceSend this page to someone who may find it useful.