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.

Where
adventure.inc, Adventure Dhaka Limited
Type
Production audit
Stack
Next.js, Node.js, AWS
Read
~4 min

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

Tier 1Requests that never let go
  • 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.
Tier 2Whole files in memory
  • 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.
Tier 3Work the server didn't need to do
  • 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

[CONFIRM WHICH OF THESE SHIPPED, AND ADD ANYTHING ELSE YOU CHANGED]

Results

[X]%[METRIC — e.g. lower peak heap]
[X][METRIC — e.g. fewer restarts per week]
0[CONFIRM — OOM crashes since]

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.

Next highlight Performance is a feature