Skip to content

Lesson 12 of 14 · 20m

PHP Off the Request: CLI, Workers, and Queues

The CLI SAPI breaks your FPM assumptions: leaks compound, signals matter, and at-least-once means dedupe yourself.

php worker.php runs the CLI SAPI, and everything the request cycle gave you for free is gone. No $_GET, no $_SERVER['HTTP_*'], no session, no max_requests recycling, no opcache (opcache.enable_cli=0 by default — pointless per-process anyway). The process you start today is still running next week, holding every byte it leaked. Shared-nothing was the safety net; in a worker there is no net.

The assumptions that break

max_execution_time defaults to 0 under CLI — unlimited. memory_limit still applies, but RSS is what the OOM killer reads. Every per-request habit — building a container, loading config, connecting to the DB — now runs once at boot, which is the win, and every leak compounds, which is the cost. A per-request 100 KB leak is invisible under FPM; in a worker it's death by a million iterations. memory_get_usage(true) is the truth serum: check it after each job, and when it crosses a threshold, exit cleanly and let the supervisor respawn you.

Signals work differently too: a request handler ignores them; a daemon lives by them. pcntl_async_signals(true) (PHP 7.1+) makes SIGTERM interrupt your loop mid-tick — handle it by finishing the current job and exiting, not by dying mid-write.

The queue contract

Queues are at-least-once. Redis BLPOP, RabbitMQ ack, SQS visibility timeouts — every system redelivers, which means "process exactly once" is something you build on top: dedupe on the job's own ID (SETNX or a DB unique key), make the handler idempotent, and ack after the work, never before. The inverted order — ack, then work, then crash — is how messages evaporate.

Retry with backoff, then dead-letter after N attempts. A poisoned message retried hot is a tight loop burning workers. And check your Redis era: BRPOPLPUSH has been deprecated since Redis 6.2 (2021) in favor of BLMOVE/LMOVE; still seeing it in code is a fingerprint of a 2021-era tutorial. For consumer groups and pending-ack tracking, Streams (XREADGROUP/XACK/XAUTOCLAIM) is the grown-up primitive.

Supervision is not optional

Your process manager is systemd, not hope:

[Service]
ExecStart=/usr/bin/php /var/app/worker.php
Restart=always
RestartSec=2
MemoryMax=512M

Restart=always plus a small delay converts worker death from an outage into a recycle. MemoryMax gives the kernel a bound that turns runaway leaks into restarts instead of host OOMs. Worker concurrency is process count, not threads — scale with more units or a worker.php that loops pcntl_fork children you manage deliberately. Laravel Horizon and Symfony Messenger exist because naive while(true) consumers die in production; you can write your own, but supervision, backoff, and graceful shutdown are the parts people skip and then relearn.

The craft parts

  • gc_collect_cycles() on each loop tick — PHP's cycle collector otherwise lets object graphs pile up.
  • date_default_timezone_set('UTC') — workers inherit the box's TZ, and now() becomes a lie at DST edges.
  • fwrite(STDERR, ...) or Monolog → stdout, JSON lines; the journal collects it.
  • Close and reconnect DB/Redis handles on a schedule — MySQL server has gone away at 4 a.m. is a stale-connection signature.
  • declare(ticks=) is dead — pcntl_async_signals(true) replaced it in 7.1; code using ticks is a museum piece.

Try this

Run a consumer that sleeps 50 ms per job and leaks an array append per job. Watch memory_get_usage(true) print and RSS climb in ps. Then add the threshold-exit and systemd restart, kill it with SIGTERM mid-job, and confirm it finishes the unit of work before dying. That loop — leak, recycle, graceful exit — is the whole craft.

Pitfalls

  • opcache.enable_cli stays off: per-process bytecode cache buys nothing.
  • Singletons and "per-request" caches become per-process — that's a feature for memoization and a bug for anything keyed to a request ID.
  • exit/die inside a job skips cleanup — throw, don't die; let the top level decide.
  • File descriptors leak too: fopen without fclose in a loop is EMFILE on a delay fuse.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.