PHP › PHP CLI Scripting
What memory management considerations apply specifically to long running PHP CLI scripts, such as queue workers, that might process thousands of jobs without ever restarting?
AdvancedAnswer
Unlike a typical web request where PHP's memory is completely reset at the end of every single request, a long running CLI process accumulates memory usage across many iterations of its main loop, meaning any unintentional memory leak, such as an ever growing array or unreleased resource, can gradually consume all available memory over time, which is why long running workers often include periodic memory usage monitoring and are commonly configured to automatically restart themselves after processing a certain number of jobs, providing a clean memory reset on a predictable schedule.
$jobsProcessed = 0;
while (true) {
processNextJob();
$jobsProcessed++;
if ($jobsProcessed >= 1000 || memory_get_usage() > 256 * 1024 * 1024) {
exit(0); // process manager restarts a fresh worker
}
}Real-world example A queue worker configured to automatically exit after processing one thousand jobs, with a process manager immediately restarting a fresh worker process, avoids a subtle memory leak in a third party library from ever accumulating enough to cause an actual out of memory crash.