BitlystBitlyst
PostsSeriesTopicsAbout

Bitlyst

Short, diagram-first posts on JavaScript, React & Next.js. Follow via RSS or the newsletter.

© 2026 Mohsen Fallahnejad

PostsSeriesTopicsLinksAboutSync devicesRSSllms.txtGitHubX
Posts/nextjs
AI-generated illustration. Every ticking ticket keeps one finished request on the rack.
Intermediate6 min read

Part 5 of Next.js Field Notes

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

A Next.js memory leak where one setTimeout per SSR render kept finished requests in memory. How it was spotted, measured with heap snapshots, and fixed.

Mohsen Fallahnejad

Mohsen Fallahnejad

Nov 30, 2026Discuss

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 requests312 MB
~1,400 requests934 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:

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

AI-generated illustration. The bug wasn't in the parcels. It was at the other end of the string.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":

ts
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,
});

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#

StepWhat to do
NoticeMemory stays high after a forced GC
MeasureProduction build, force GC, then take a heap snapshot
CompareDiff two snapshots: what count grows with requests?
TraceFollow the reference chain back to a GC root
Usual suspectTimers, long promises, caches created during a request
This fixServer cacheTime: Infinity, so no timer starts

Advanced · optional

Going deeper#

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.

Filed under#nextjs#nodejs#memory#performance#react-query

Series

Next.js Field Notes

Tricks and traps from shipping Next.js App Router apps in production.

  1. 1One Line in My Root Layout Turned 158 Static Pages Into 0
  2. 2The Server Action That Ran Twice, but Only on localhost
  3. 3Scrolling My Blog Index Prefetched All 51 Posts. One Config Line Cut It to 90 kB.
  4. 4Next.js use cache, cacheLife and cacheTag: How One View Counter Rebuilt Every Page
  5. 5Next.js Memory Leak: The Timer That Kept Every Request · you are here
  6. 6The redirect() that a try/catch swallowed · coming soon
  7. 7The useSearchParams call that blanked half the page in the HTML · coming soon

New parts land here first — subscribe below to get them in your inbox.

Was this worth your time?

One tap tells me what to write more of.

Mohsen Fallahnejad

Written by

Mohsen Fallahnejad

Frontend engineer explaining JavaScript, React & Next.js internals in posts you can finish over coffee. More about me

X ↗GitHub ↗LinkedIn ↗
← OlderDatabase Indexes: The Back Page of the Book

Start the discussion

Questions, corrections, a better approach? I read and reply to every comment.

Read next

V8 Garbage Collection: Why Middle-Aged Objects Are the Expensive Ones

How V8's generational garbage collector works: scavenges cost per survivor, short-lived objects are nearly free, and pretenuring makes long-lived ones cheap.

Nov 6, 20267 min read

React Server Components vs 'use client': What Actually Ships to the Browser

Server Components send the result; Client Components send the result plus the code. What 'use client' really does, why it doesn't mean browser-only, and where to put it.

Nov 13, 20267 min read

turbopackRustReactCompiler: Running the React Compiler in Rust Inside Next.js

The React Compiler normally runs through Babel in Node.js. Next.js can run a Rust version inside Turbopack instead. Learn what that changes and what it saves.

Nov 10, 20264 min read

Get new posts in your inbox

One email when a new post is out: short, diagram-first explanations of JavaScript, React and Next.js. No spam, unsubscribe any time.

6 min left
Discuss👍 React
👍