Taming memory
How I tracked down why a large Next.js app kept running out of memory — and why raising the limit was never the fix.
The problem
Under load, the app's server pods kept crashing with “JavaScript heap out of memory”. The tempting fix is to give Node more memory. That only moves the crash later, and makes every crash more expensive.
So the question wasn't how much memory do we need. It was what is holding on to memory that it should have let go?
How I looked for it
I listed everything that could keep memory alive across a request, then ranked each suspect by two things: how likely it was to cause these crashes, and how much memory it could hold at its worst. That gave three tiers, and I worked strictly from the top.
What I found
- Timeouts and retries that multiplied. Outgoing calls waited up to 120 seconds, and a retry setting overrode the safe default. In the worst case, one slow upstream call could keep its data in memory for about 494 seconds.
- No circuit breaker. When a dependency slowed down, new requests kept piling onto it, each one holding memory while it waited.
- Image processing used roughly 4× the file size in memory, with heavier formats like HEIC on top.
- File proxying loaded entire files into memory instead of streaming them through.
- Deep copies of large responses in 27 places, each one doubling that data for a moment.
- 22 pages forced to render on every request, skipping caching that would have taken load off entirely.
Seeing it coming
Fixes help; visibility keeps them working. I added a health check that compares the real heap against the container's memory limit. When it gets close, the pod reports itself unhealthy and stops taking traffic — before it crashes, not after.
The fix plan
- Cap timeouts and retries, and add a circuit breaker for slow dependencies.
- Stream files instead of buffering them, and limit upload sizes.
- Remove unnecessary deep copies.
- Cache pages that never needed to be dynamic.
Results
What I took from it
Don't raise the limit; find what's holding on. Memory problems are rarely one big leak. They are a few reasonable decisions that become dangerous together, under load, on a bad day.