Just spent 2 days chasing a memory leak in my PHP worker, it was a single line

jt_loves_tacos

New Member
Messages
75
Reaction score
0
Location
Phoenix, AZ

Been running a PHP worker that processes image uploads for a side project. Noticed it was eating RAM like crazy, would hit the 512M limit in about 4 hours and die. Spent two days profiling with xdebug and blackfire, added gc_collect_cycles, nothing. Turns out I had a static array that was accumulating log entries for every job. Never cleared it. One line: self::$log = []; at the end of each loop. Facepalm.

Anyone else got a stupid simple leak story? I feel like an idiot but also relieved it wasn't something worse.

marcus1987

New Member
Messages
66
Reaction score
0
Location
Sydney, NSW

Ha, the classic static array graveyard. Been there.

Mine wasn't PHP but I had a Node worker scraping odds off a few books for a Plinko bot I was messing with, and I was pushing every response into a module level array "just in case I need to debug later." Guess what, never debugged, just watched RSS climb until the VPS started swapping and my fills got rejected. Took me way too long to figure out because I kept blaming the exchange API lol.

The gc_collect_cycles thing is such a trap too. You convince yourself it's a cycle problem because that's the sexy answer, when really it's just you hoarding references like a raccoon. One line fix, two days of your life gone.

Honestly the fact it took 4 hours to die is almost merciful. Mine would creep for like a day and a half so I'd forget it was even happening until it wasn't.

emilyb85

New Member
Messages
67
Reaction score
0
Location
Amsterdam, NL

The raccoon line got me, that's exactly what it is.

But I'll push back on one thing. gc_collect_cycles isn't the sexy answer, it's the lazy one. Nobody reaches for it because they genuinely suspect a reference cycle. They reach for it because it's a one-liner you can paste in, run, and feel like you did something while the actual leak keeps chugging along. Two days of profiling would've caught this in hour one if the first instinct had been "what am I still holding onto" instead of "how do I make the GC work harder."

And the fix itself bugs me a little. Blanking the array at the end of the loop works, sure, but you've still got an unbounded log living inside a long-running process. That's a leak with a manual reset button. Bounded ring buffer, or ship the logs somewhere external and stop treating the worker like a debug console.

Marcus, did you ever actually go back and read any of that scraped odds data, or was it pure hoarding? I ask because I've got a /tmp directory full of JSON dumps from 2023 that says I already know the answer.

sarah_2891

New Member
Messages
50
Reaction score
0
Location
Denver, CO

Emily's right about the manual reset button, I've done exactly that and felt clever about it too. Blanking the array "fixes" it right up until someone adds a second log path or forgets the line in a refactor. Then you're back to square one with a 4 hour time bomb and a git blame that points at yourself.

But hour one is generous. xdebug won't hand you a static that grows across iterations unless you're manually diffing memory snapshots, and nobody does that on the first pass. Blackfire will if you compare two profiles, but the default instinct is to stare at the flamegraph and the wall time, decide the bottleneck is the image resize, and go optimize that instead. I've lost more time to "the profiler says everything is fine" than to any actual leak.

My dumbest one was a PDO connection cache keyed by DSN in a worker. Same deal, array never cleared, every retry with a slightly different connection string added an entry. Took me a week to notice because the worker only leaked when the DB was flaky, which is also when you're already staring at logs and not at RSS.

Emily, what do you actually do for logging in long-running processes? Everything to stdout and let the supervisor deal with it, or something fancier?

greg_ohio

New Member
Messages
71
Reaction score
0
Location
Columbus, OH

bhai log this thread is making me feel better about my own stupidity 😅

Mine was a tiny python scraper I wrote to track welcome bonus pages on a few slot sites (yes I know, but the bonus hunting is real lol). Appending every page HTML to a list so I could "compare later". Never compared. Died every night around 3am, took me a week to connect the dots because I only checked it in the morning and it had always already restarted. The raccoon line from marcus is painfully accurate.

sarah the PDO thing sounds brutal, a leak that only shows up when the DB is flaky is evil, it hides exactly when you're already stressed and not looking at RSS. And emily what do you actually mean by shipping logs somewhere external? Like just print to stdout and let the supervisor rotate it? Asking because my current "fix" is literally blanking a list at the end of the loop and now I'm paranoid 😂

marcus1987

New Member
Messages
66
Reaction score
0
Location
Sydney, NSW

No Emily, I never read a single byte of it. Went back like a month after I "fixed" it, opened one of the dumps, and it was 40k lines of the same three bookmaker JSONs with timestamps that differed by milliseconds. Deleted the whole folder and felt nothing. Pure hoarding, you called it.

Sarah's right that hour one is generous though. The "profiler says everything is fine" thing is real, I've burned whole evenings staring at a flamegraph convinced the resize was the problem while the actual leak was just sitting there in a module scope collecting dust. Blackfire only tells you what you ask it to compare. If you don't snapshot twice and diff, you're just looking at pretty colors.

On the logging question, since Greg asked and I do this for a living now: stdout only, and let the container runtime deal with it. I run my workers in docker with the json-file driver capped at like 10m and 3 files, so it rotates itself and I literally cannot leak into a file handle I forgot about. If you need in-process buffering for some reason, use something bounded (deque with maxlen, or a ring buffer) so the worst case is "I lost old logs" instead of "I lost the whole worker at 3am." Blanking the list works but it's a chore you'll forget in the next refactor, and sarah already said that better than I did.

greg your scraper dying every night at 3am and you only checking in the morning is genuinely the funniest version of this. The bug was hiding from you on a schedule.

tommy2k

New Member
Messages
69
Reaction score
0
Location
Mexico City, MX

The raccoon line is doing a lot of work in this thread and it deserves it.

Emily's point about the manual reset is the one that'll bite people though. I did the exact same thing with a Laravel queue worker, static cache keyed by user ID that I "cleared per job" except I only cleared it in the happy path. Any job that threw skipped the reset. So the leak only happened when things were already going wrong, which is the worst time to add memory pressure. Took a week because I kept blaming the queue driver.

Greg, on the logging thing, marcus is right, stdout and let the runtime rotate it. The paranoid fix nobody mentions is just capping the array in the first place. If you're gonna buffer in-process at least make it a bounded structure so the failure mode is "old logs gone" instead of "worker dead at 3am." I've got a whole thread's worth of opinions on worker stuff over in the backend section if you want more, we go back and forth on it constantly.
https://websiteforums.info/forums/php-and-backend-development.6/

Sarah the PDO leak gated behind flaky DB is genuinely evil though. That's the kind of thing that makes you distrust your own logs.

da_real_mvp

New Member
Messages
69
Reaction score
0
Location
Atlanta, GA

Emily and Sarah are kind of talking past each other on the "hour one" thing and honestly Sarah's got the better of it. The problem was never which tool you reached for. It's that the flamegraph is a CPU story and the leak was a memory story. You stare at that thing, see image resize eating 60% of wall time, and go optimize the resize. Meanwhile RSS is quietly climbing in a corner nobody's looking at. I did this exact thing last year, spent an afternoon profiling a worker convinced the JSON parse was the villain, turned out to be Guzzle handler stacks getting rebuilt every call. Nothing wrong with the profiler, I was just asking it the wrong question.

The thing nobody in this thread has mentioned yet though: put a soft ceiling on the worker. Not the 512M hard kill, an actual watchdog. My workers check memory_get_usage(true) every N jobs and if we're past 350M they finish the current one and exit clean, supervisor brings them back up. Yeah it's a bandaid over a leak, but it turns "dies mid-upload at 3am" into "restarts gracefully and I get a log line." Caught two real leaks that way, ones I never would've found staring at profiles.

tommy2k's happy-path-only reset is the actually scary version of this bug though. That one survives code review because the line IS there, it just doesn't run when the job throws, which is precisely when you're already in trouble. Greg, if you're keeping the manual reset, at least stick it in a finally block. Or do the bounded thing marcus suggested and stop worrying about it.

rk_designs

New Member
Messages
68
Reaction score
0
Location
Vancouver, BC

da_real_mvp's watchdog idea is the only thing in here I'd actually ship. Everyone's arguing about bounded buffers and stdout while my workers get their sessions nuked every few hours anyway, because the books I'm polling don't much like my exit node. If the process is gonna die on you regardless, may as well make it die on your terms. I check memory every 50 jobs, bail clean past 300M, let systemd bring it back. Caught a leak last month I'd have never found otherwise.

Mine was dumber than all of yours though. I keyed a connection cache by "session id" for a book that rotates session ids on every reconnect. VPN drops, reconnect, new id, new entry, forever. The cache was supposed to save me from re-authing and instead it just ate RAM every time my tunnel got flaky. Blamed the VPN for a week. Which, tbh, is usually the right call with these clowns, so it felt like a safe assumption.

Emily's right that blanking the array is a leak with a reset button. But for this kind of work I'll take the reset button, these processes are disposable by design. I just don't want the leak taking the whole box down at 4am while I'm asleep and missing a fill. Bounded is better, but a watchdog that fails loud beats a bounded buffer that fails silent imo.

You must log in or register to reply here.