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=512MRestart=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, andnow()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 awayat 4 a.m. is a stale-connection signature. declare(ticks=)is dead —pcntl_async_signals(true)replaced it in 7.1; code usingticksis 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_clistays 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/dieinside a job skips cleanup — throw, don't die; let the top level decide.- File descriptors leak too:
fopenwithoutfclosein a loop isEMFILEon a delay fuse.
Was this lesson helpful?
Keep reading
Related articles from the SudoSecurity blog.
PHP 8.6 Finally Turns On the Session Settings You Were Told to Set in 2006
Every PHP hardening guide for two decades has told you to flip the same three session settings. PHP 8.6, due November 19, 2026, flips them for you: strict mode on, HttpOnly on, SameSite set to Lax.
Money Is Not a Float: Decimals, Rounding and Cents in PHP, Python and JavaScript
I ran the same money math through PHP 8.6, Python 3.15 and Node 26. They round 2.675 differently, bcadd('0.1', '0.2') returns 0, PHP's BcMath\Number turns a float 0.1 into 0 with only a deprecation notice, and JSON.parse quietly changes 9007199254740993 to ...992.
PHP OPcache, Preloading and the JIT, Measured on Laravel: One Setting Is 18x, One Costs You 19%, and the JIT Does Nothing
I ran Laravel 13 on PHP 8.6 FPM under six OPcache configurations and timed every one. OPcache itself was worth 18x, revalidate_freq=0 quietly cost 19%, preloading added 9%, and the JIT that doubles Zend's CPU benchmark moved a real page by 1%.
One Slow Call, Three Runtimes: How PHP-FPM, Python ASGI and Node Fall Over When a Dependency Takes 200 ms
I put the same 200 ms wait behind PHP-FPM, FastAPI on uvicorn and a plain Node server, then hit each one with 50 concurrent requests. Handled correctly, the async runtimes served 205-211 req/s against FPM's 19.6. One blocking call in the wrong place took both of them down to 4.98, slower than...