DEV Community

Cover image for Next.js Memory Leak: The Timer That Kept Every Request
Mohsen Fallahnejad
Mohsen Fallahnejad

Posted on Originally published at bitlyst.blog

Next.js Memory Leak: The Timer That Kept Every Request

Picture a Next.js server sitting at 5 GB of memory. It isn't crashing and it isn't spiking. It sits there, day after day. The garbage collector runs, and nothing comes back.

That's what Rohit Kashyap's team at Zepto saw, and his write-up is a great detective story. It's also long and heavy. Here's the same story in plain words: how they noticed it, how they measured it, what caused it, and how they fixed it.

The whole idea in one picture

Think of a cloakroom at a party. Every guest (a request) hands over a coat. When the guest leaves, the coat should go too.

Now picture someone pinning a 5-minute timer ticket to every coat, and a house rule: you can't clear a coat while its ticket is still ticking. Guests leave, but the coats pile up for five minutes each. With lots of guests, the rack is always full.

Any setTimeout created while a request is being rendered keeps that whole request in memory until the timer fires.

That's the bug. Everything else is how they found the ticket and took it off.

How they noticed: memory that never goes down

First, a quick reminder of how memory gets freed in JavaScript. The garbage collector doesn't hunt for "unused" things. It starts from a few roots (globals, the call stack, pending timers) and keeps everything it can still reach. Everything else gets thrown away. (More on that in how garbage collection works.)

So when memory stays high even after the garbage collector runs, it means one thing: something still points at that memory.

They measured this on a production build (not next dev, which is full of dev-only stuff) and forced a garbage collection before each measurement, so only memory that's really stuck would show:

After… Heap after forced GC
Warm-up (56 requests) 112 MB
+280 requests 312 MB
~1,400 requests 934 MB

About 1 MB kept per request, and none of it came back. That's the cloakroom filling up.

How they found it: follow the string back

A heap snapshot is a photo of everything in memory and who points at whom. They took one before the load and one after, and compared them.

One line gave it away: ServerResponse 336. They had sent exactly 336 requests, and every response was still alive, minutes after it finished.

The usual tool, the "biggest objects" view, didn't help, because nothing was big. It was hundreds of small coats, not one giant one. So they asked a different question: what chain of references, starting from a root, still reaches this response? They wrote a small script to walk the snapshot from the roots and print that chain.

Every chain looked the same:

pending 5-minute timer        ← a GC root
  → react-query Query
  → QueryClient
  → the request's context
  → ServerResponse            ← the finished request
Enter fullscreen mode Exit fullscreen mode

AI-generated illustration. The bug wasn't in the parcels. It was at the other end of the string.

Why a timer kept the request

Three small things added up:

  1. react-query v3 starts a timer for every query. In the browser that's useful: "if nobody uses this data for 5 minutes, clear it." Normally a component subscribes and cancels it, but that happens in useEffect, and effects never run on the server. So during server rendering, the timer ticks for 2 to 5 minutes for nothing.
  2. Node pins the request to the timer. Next.js runs each request inside AsyncLocalStorage. That's what makes cookies() and headers() work. Every timer you create copies that request context, in case the callback needs it later. Node can't know if it will, so it keeps it.
  3. Pending timers are roots. Anything a waiting timer can reach can't be freed.

So: one timer per query, each holding a whole request (response, buffers, data) for minutes. Under real traffic, that's a full rack all the time.

The fix: don't start the timer on the server

react-query skips the timer when the cache time is Infinity. On the server, each QueryClient lives for one request and is thrown away after it anyway, so "never expire" really means "expire with the request":

class ServerQueryCache extends QueryCache {
  build(client, options, state) {
    return super.build(client, { ...options, cacheTime: Infinity }, state);
  }
}

const queryClient = new QueryClient({
  queryCache: isServer ? new ServerQueryCache() : undefined,
});
Enter fullscreen mode Exit fullscreen mode

The browser keeps its normal cache. Only the server changes.

The result: the local heap stayed flat (70 MB → 84 MB after about a thousand requests), and in production, memory per pod dropped from about 4.8 GiB to 1.2 GiB.

One honest warning from the article: their autoscaler was scaling on memory. Once memory dropped, fewer pods ran and latency went up. If you fix a memory problem, keep an eye on your scaling for a few days.

Say it in an interview

"On a Node server, any timer created during a request keeps that request's context alive until it fires, because AsyncLocalStorage attaches the context to the timer and pending timers are GC roots. In one real case, react-query started a 5-minute cache timer per query during SSR, so every finished request stayed in memory for minutes. They found it by diffing heap snapshots after a forced GC and following retainer paths from the roots, and fixed it by setting the server cache time to Infinity so the timer never starts."

Cheat sheet

Step What to do
Notice Memory stays high after a forced GC
Measure Production build, force GC, then take a heap snapshot
Compare Diff two snapshots: what count grows with requests?
Trace Follow the reference chain back to a GC root
Usual suspect Timers, long promises, caches created during a request
This fix Server cacheTime: Infinity, so no timer starts

Going deeper

Advanced and optional. Everything above is enough to explain this in an interview. This part is for the curious: full numbers, edge cases and what's still unproven.

Why upgrading react-query isn't enough

react-query v4 and v5 default the cache time (gcTime in v5) to Infinity on the server. But if your hooks pass their own finite value, a real timer still starts during SSR. The article points to TanStack/query#11320 and notes that, as of November 2026, the fix wasn't merged. If you set gcTime per hook, you still need a guard like the one above.

Why the "biggest objects" view missed it

A dominator tree shows who alone owns a big chunk of memory. Here, hundreds of small, separate references each held one request. No single object was big, so nothing stood out. Shortest paths from the GC roots (a breadth-first search over the snapshot, skipping weak references) found them.

Taking snapshots safely

Snapshots of a leaking server get huge. The author's first script joined all the chunks into one string and hit the maximum string size. Stream the chunks straight to a file instead, and call HeapProfiler.collectGarbage (twice) before taking the snapshot.

Other timers to watch for

The same thing happens with any library written for the browser that sets timers: cache eviction, polling, debouncing, retries. If it runs during SSR, it can pin the request.


Originally published on Bitlyst.

Top comments (1)

Collapse
 
sunnatulla_dev profile image
Sunnatulla •

The finite gcTime doesn't have to come from a hook. A 24h gcTime in new QueryClient({ defaultOptions }) does it too, and that's the setup the persister docs suggest. I ran 200 fake requests through AsyncLocalStorage on query-core 5.108.4: all 200 request stores stayed alive behind 200 pending timers. Calling queryClient.clear() after the render brought both to 0, so you don't need the custom QueryCache.