How to debug memory leak causing high CPU usage in Next.js app?

14 replies
Last updated: Jan 28, 2026
Hey, random question here. I have a memory leak issue inside my Next js application. My node js CPU gets over 200/300% randomly.
Is there a way I can debug the code to see where the memory leak is located or what is causing it?
AI Update

This sounds like a general Next.js/Node.js performance issue rather than something specific to Sanity. Memory leaks and high CPU usage can happen for various reasons in Next.js applications. Here are some practical debugging approaches:

1. Use Node.js built-in profiling tools:

Start your Next.js dev server with the --inspect flag:

NODE_OPTIONS='--inspect' npm run dev

Then open chrome://inspect in Chrome to access DevTools for profiling memory and CPU usage.

2. Generate heap snapshots:

You can take heap snapshots to compare memory over time:

NODE_OPTIONS='--inspect --max-old-space-size=4096' npm run dev

In Chrome DevTools, go to Memory tab and take snapshots before and after the leak occurs to see what's accumulating.

3. Check for common Next.js memory leak causes:

  • Event listeners not being cleaned up in useEffect hooks
  • Subscriptions (like Sanity's client.listen()) not being unsubscribed
  • Large data fetching without proper pagination
  • Image optimization issues with too many concurrent optimizations
  • API routes that don't properly close connections

4. If you're using Sanity client:

Make sure you're properly cleaning up any real-time listeners:

useEffect(() => {
  const subscription = client.listen(query).subscribe(update => {
    // handle update
  })
  
  return () => subscription.unsubscribe() // Important!
}, [])

5. Use clinic.js for detailed diagnostics:

npm install -g clinic
clinic doctor -- node server.js

This will generate detailed reports about performance bottlenecks.

6. Monitor in production:

Consider using tools like Vercel Analytics, New Relic, or Datadog to track memory usage patterns over time.

The 200-300% CPU usage suggests multiple threads are maxing out, which could indicate runaway promises, infinite loops, or heavy computational work that's not being throttled. Start with the Chrome DevTools approach—it's the quickest way to see what's consuming resources in real-time.

Show original thread
14 replies

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?