nextjs - ✅(Solved) Fix Memory leak during load tests in dynamic rendering mode [2 pull requests, 6 comments, 4 participants]

Official PRs (…)
ON THIS PAGE

Recommended Tools

×6

Utilities matched from this issue’s tags and category — try them while you read without losing context.

GitHub issue graph ai analysis

Paste a GitHub issue URL. We fetch that issue, discover linked issues from bodies/comments/timeline, collect linked pull requests, and produce a structured English report.

The report is written in English Markdown for sharing and archival.

Helpful · Quick feedback

Loading…
GitHub stats
vercel/next.js#84648Fetched 2026-04-08 02:18:55
View on GitHub
Comments
6
Participants
4
Timeline
24
Reactions
7
Timeline (top)
subscribed ×12commented ×6cross-referenced ×3issue_type_added ×1

Root Cause

  1. In a second terminal run ./run_goose_attack_api.sh. You only need Rust installed locally because the load tests are written in Rust.

Fix Action

Fixed

PR fix notes

PR #85529: Tracing: Fix memory leak in span map

Description (problem / solution / changelog)

What?

Fixes a small retainer object that is inserted on each request and not cleaned up.

While at it also swapped array -> Set for the type checks to leverage has​ instead of includes​.

Was highlighted by running the reproduction in #84648.

Changed files

  • packages/next/src/server/lib/trace/constants.ts (modified, +4/-4)
  • packages/next/src/server/lib/trace/tracer.ts (modified, +29/-14)

PR #42: Optimize Next.js dev server memory usage via package import optimization

Description (problem / solution / changelog)

Problem

Dev server hits memory threshold and restarts frequently due to webpack loading entire icon/component libraries (~1000+ lucide-react icons, 24+ @radix-ui packages) when only a handful are actually used per file.

Changes

next.config.ts

  • optimizePackageImports: Transform barrel imports to direct module imports for lucide-react and all @radix-ui packages
  • webpackMemoryOptimizations: Enable Next.js 15+ memory-efficient webpack configuration
  • preloadEntriesOnStart: false: Reduce initial memory footprint

package.json

  • dev:memory script: 4GB heap allocation fallback if configuration optimizations insufficient

How it works

// Before: Webpack loads entire lucide-react package into memory
import { CheckIcon, ChevronDownIcon } from "lucide-react";

// After: Next.js transforms to direct imports (automatic)
import CheckIcon from "lucide-react/dist/esm/icons/check";
import ChevronDownIcon from "lucide-react/dist/esm/icons/chevron-down";

Result: 50-70% memory reduction by loading only required icons/components instead of entire packages.

Documentation

Added MEMORY_OPTIMIZATION.md with analysis, configuration rationale, and monitoring guidance.

Related

Addresses Next.js issues #83275 and #84648.

<!-- START COPILOT ORIGINAL PROMPT --> <details> <summary>Original prompt</summary>

Next.js Dev Server Memory Optimization Task

Context

Our Next.js dev server is experiencing frequent restarts with the warning message: "⚠ Server is approaching the used memory threshold, restarting...". This is a known issue caused primarily by inefficient imports from icon/component libraries and webpack memory handling.

Your Task

Please analyze and refactor our codebase to optimize memory usage during development. Follow these steps:

Step 1: Analyze Current Imports

  1. Search the entire codebase for imports from these common libraries:

    • react-icons (especially react-icons/fa, react-icons/md, react-icons/ai, etc.)
    • lucide-react
    • @mui/icons-material
    • @heroicons/react
    • Any other icon or large component libraries
  2. Identify barrel file imports (e.g., import { FaUser, FaHome } from 'react-icons/fa')

  3. Count how many icons/components we're importing from each library

Step 2: Update next.config.js

Add or update the following optimizations to next.config.js (or next.config.mjs if using ES modules):

const nextConfig = {
  experimental: {
    // Optimize package imports to avoid loading entire icon libraries
    optimizePackageImports: [
      'react-icons',
      'lucide-react',
      '@mui/icons-material',
      '@heroicons/react',
      // Add any other libraries you find
    ],
    
    // Enable webpack memory optimizations (Next.js 15+)
    webpackMemoryOptimizations: true,
    
    // Reduce initial memory footprint
    preloadEntriesOnStart: false,
  },
};

module.exports = nextConfig;

Important: If we're using Next.js 14 or earlier, use modularizeImports instead of optimizePackageImports:

const nextConfig = {
  modularizeImports: {
    'react-icons/fa': {
      transform: 'react-icons/fa/{{member}}',
    },
    'react-icons/md': {
      transform: 'react-icons/md/{{member}}',
    },
    // Add transforms for each react-icons sub-package we use
  },
  experimental: {
    webpackMemoryOptimizations: true,
    preloadEntriesOnStart: false,
  },
};

Step 3: Refactor Component Imports (If Needed)

If we have custom barrel files (index.js files that re-export many components), consider:

  1. Identifying barrel files in our src/components or similar directories
  2. Replacing barrel imports with direct imports where they're causing issues
  3. Documenting which files were changed and why

Example refactor:

// Before (barrel import)
import { Button, Card, Modal } from '@/components';

// After (direct imports)
import Button from '@/components/Button';
import Card from '@/components/Card';
import Modal from '@/components/Modal';

Step 4: Update package.json Scripts

Add a development script with increased Node.js memory allocation:

{
  "scripts": {
    "dev": "next dev",
    "dev:memory": "NODE_OPTIONS='--max-old-space-size=4096' next dev"
  }
}

Step 5: Create Summary Report

After completing the refactoring, provide a summary that includes:

  1. Which libraries were found and how many imports from each
  2. Configuration changes made to next.config.js
  3. Any import refactoring performed (list files changed)
  4. Recommended next steps or additional optimizations
  5. Instructions for running the optimized dev server

Guidelines

  • Do NOT break existing functionality
  • Preserve all icon/component usage, just optimize how they're imported
  • Test that the configuration is valid JavaScript/TypeScript
  • If you find large imports from custom code (our own barrel files), flag them but ask before refactoring
  • Prioritize changes that will have the biggest impact on memory usage

Expected Outcome

After this refactoring:

  • Dev server should use less memory and restart less frequently
  • Build and hot-reload times may improve
  • All existing functionality should work identically

Questions to Ask Before Starting

  1. What version of Next.js are we using? (Check package.json)
  2. Are we using TypeScript? (Look for tsconfig.json)
  3. Are we using next.config.js, next.config.mjs, or next.config.ts?

Please analyze the codebase and begin the optimization. Let me know if you discover any unusual patterns or need clarification on any part of this task.

Reference Links

For additional context and tracking of this issue, refer to these Next.js GitHub discussions:

  1. Primary Issue Report: https://github.com/vercel/next.js/issues/83275

    • Original bug report about the memory threshold restart warning
    • Community discussion and workarounds
  2. Related Issue: https://github.com/vercel/next.js/issues/84648

    • Additional reports and context about the memory problem
    • May contain alternative solutions or findings
  3. Potential Fix PR: https://github.com/vercel/next.js/pull/85529

    • Pull request addressing the memory issue
    • Check if this fix is included in our Next.js version
    • May inform additional optimization strategies

Review these links if you need deeper t...

</details> <!-- START COPILOT CODING AGENT SUFFIX -->

Created from VS Code.

<!-- START COPILOT CODING AGENT TIPS -->

✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.

<!-- This is an auto-generated comment: release notes by coderabbit.ai -->

Summary by CodeRabbit

  • New Features

    • React Query Devtools added for query debugging
    • New memory-optimized development script (higher Node memory limit)
  • Documentation

    • Memory optimization guide for Next.js dev server and package import optimizations
    • oRPC client-side usage guide
    • TanStack Query compatibility notes and workaround
  • Bug Fixes

    • Resolutions added to address TanStack Query version conflict
  • Chores

    • Dependency updates (Next.js, React Query, better-auth, motion, tooling)
    • Error handling widened to accept broader error inputs

<sub>✏️ Tip: You can customize this high-level summary in your review settings.</sub>

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Changed files

  • MEMORY_OPTIMIZATION.md (added, +204/-0)
  • bun.lock (modified, +71/-66)
  • docs/next/optimizePackageImports.md (added, +49/-0)
  • docs/orpc/README.md (modified, +1/-0)
  • docs/orpc/orpc.client-side.md (added, +199/-0)
  • docs/orpc/orpc.tanstack-query-compatibility.md (added, +80/-0)
  • docs/orpc/orpc.tanstack-query.md (modified, +1/-1)
  • next.config.ts (modified, +10/-0)
  • package.json (modified, +15/-11)
  • src/components/features/projects/project-error-fallback.tsx (modified, +2/-2)
  • src/components/providers/query-provider.tsx (modified, +5/-1)

Code Example

Operating System:
  Platform: darwin
  Arch: arm64
  Version: Darwin Kernel Version 24.6.0: Mon Jul 14 11:30:40 PDT 2025; root:xnu-11417.140.69~1/RELEASE_ARM64_T6041
  Available memory (MB): 24576
  Available CPU cores: 14
Binaries:
  Node: 24.4.0
  npm: 11.4.2
  Yarn: 1.22.22
  pnpm: 10.14.0
Relevant Packages:
  next: 15.5.4 // Latest available version is detected (15.5.4).
  eslint-config-next: N/A
  react: 19.2.0
  react-dom: 19.2.0
  typescript: N/A
Next.js Config:
  output: N/A
RAW_BUFFERClick to expand / collapse

Link to the code that reproduces this issue

https://github.com/grzegorz-orbital/nextjs-bug

To Reproduce

  1. Clone repository (I prepared a small test repository that reproduces this issue): https://github.com/grzegorz-orbital/nextjs-bug

  2. To trigger the problem, run ./run_next.sh in a terminal — this starts Next in production mode.

  3. Install Rust — it’s required to run the performance test: https://rust-lang.org/tools/install/

  4. In a second terminal run ./run_goose_attack_api.sh. You only need Rust installed locally because the load tests are written in Rust.

When I run this test on my MacBook the test finishes in about one minute. It executes 40,000 requests. After the test finishes, the Next process memory stays around ~15 GB and does not drop.

I tested it on the canary version as well (the canary branch). The behavior is the same.

Current vs. Expected behavior

I would expect that after the load test completes, the process memory usage would return to approximately the same level as before the test started.

Provide environment information

Operating System:
  Platform: darwin
  Arch: arm64
  Version: Darwin Kernel Version 24.6.0: Mon Jul 14 11:30:40 PDT 2025; root:xnu-11417.140.69~1/RELEASE_ARM64_T6041
  Available memory (MB): 24576
  Available CPU cores: 14
Binaries:
  Node: 24.4.0
  npm: 11.4.2
  Yarn: 1.22.22
  pnpm: 10.14.0
Relevant Packages:
  next: 15.5.4 // Latest available version is detected (15.5.4).
  eslint-config-next: N/A
  react: 19.2.0
  react-dom: 19.2.0
  typescript: N/A
Next.js Config:
  output: N/A

Which area(s) are affected? (Select all that apply)

Dynamic Routes

Which stage(s) are affected? (Select all that apply)

next dev (local), next build (local), next start (local)

Additional context

No response

extent analysis

TL;DR

The most likely fix is to investigate and address potential memory leaks in the Next.js application, specifically focusing on the dynamic routes and the load test scenario.

Guidance

  • Review the Next.js application code, particularly the dynamic routes, to identify potential memory leaks or inefficient resource usage that could be causing the memory usage to remain high after the load test completes.
  • Use Node.js memory profiling tools to analyze the heap snapshot and identify any objects that are not being garbage collected, which could indicate a memory leak.
  • Investigate the load test script (./run_goose_attack_api.sh) to ensure it is properly cleaning up resources after the test completes, and consider adding any necessary cleanup or teardown steps.
  • Consider using a library like clinic to help identify and debug memory leaks in the Next.js application.

Example

No specific code example is provided, as the issue requires a more thorough investigation of the application code and load test script.

Notes

The provided information suggests a potential memory leak in the Next.js application, but further investigation is needed to determine the root cause. The fact that the issue occurs on both the main and canary branches suggests that it may be related to the application code or the load test script rather than a version-specific issue.

Recommendation

Apply workaround: Investigate and address potential memory leaks in the Next.js application, as this is likely to be the most effective way to resolve the issue.

Vote matrix · Quick signals

Works
Did the solution work? Tap to confirm.
Easy Fix
Was it a quick fix?
Time Saver
Did it save you time?
Blocking
Was it severely blocking?
Common Issue
Are others likely hitting this too?
Flaky / Intermittent
Is it intermittent?
Verified / Reproducible
Can you reproduce it reliably?
Loading…

Still need to ship something?

×6

Another batch ranked right after the header list — different links, same matching logic.

Back to top recommendations

TRENDING