Maintenance

Implement Graceful Shutdown for PHP Workers

Stop long-running PHP workers safely so deployments and restarts do not abandon jobs or corrupt application state.

Why graceful shutdown matters

A worker may be processing a job when the host restarts or a deployment replaces the process. Abrupt termination can leave a job marked as active, interrupt a file write or cause a duplicate side effect after retry.

Stop accepting new work

When a shutdown signal is received, set a flag and stop claiming new jobs. Allow the current unit of work to finish within a configured grace period. If the job cannot finish, release or let its lease expire using the queue's documented recovery mechanism.

Make work interruptible at safe points

Long tasks should process bounded chunks and check for shutdown between chunks. Do not interrupt a critical database transaction halfway through application logic; allow it to commit or roll back cleanly.

Use a process supervisor

Run workers under a supervisor that can restart failed processes and send termination signals during deployment. Configure a stop timeout that matches the expected maximum safe completion time. Avoid unlimited job execution.

Preserve idempotency

Even graceful shutdown cannot eliminate every crash. Workers must still tolerate duplicate delivery. Use unique job identifiers, idempotent handlers and durable progress markers where appropriate.

Checklist

  • Handle termination signals where supported.
  • Stop claiming new jobs after shutdown begins.
  • Finish or safely release current work.
  • Use bounded job duration and chunking.
  • Configure supervisor stop timeouts.
  • Keep handlers idempotent.
  • Monitor restarts and abandoned jobs.

References

PHP pcntl · systemd Service Management

Share this page Help other developers discover this resource.