Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug: extremely high memory usage with next dev #42514

Closed
1 task done
budchirp opened this issue Nov 5, 2022 · 68 comments
Closed
1 task done

Bug: extremely high memory usage with next dev #42514

budchirp opened this issue Nov 5, 2022 · 68 comments
Labels
bug Issue was opened via the bug report template. Developer Experience Issues related to Next.js logs, Error overlay, etc.

Comments

@budchirp
Copy link

budchirp commented Nov 5, 2022

Verify canary release

  • I verified that the issue exists in the latest Next.js canary release

Provide environment information

Operating System:
  Platform: android
  Arch: arm64
  Version: #2 SMP PREEMPT Fri Aug 5 15:52:33 AST 2022
Binaries:
  Node: 18.10.0
  npm: 8.19.2
  Yarn: 1.22.19
  pnpm: N/A
Relevant packages:
  next: 13.0.3-canary.0
  eslint-config-next: 13.0.2
  react: 18.2.0
  react-dom: 18.2.0

What browser are you using? (if relevant)

Chrome Canary v109.0.5400.0 (Android)

How are you deploying your application? (if relevant)

Vercel

Describe the Bug

The memory usage on the last next 13 (13.0.3-canary.0 and 13.0.2) releases are too high. next dev command uses about 1gb of ram. Next 12 is using about 300mb-500mb's of ram.

Screenshot_20221104-225938_Termux

Expected Behavior

next dev should use less ram.

Link to reproduction

.

To Reproduce

  1. Create project with Next 13
  2. Run next dev
  3. Check the ram usage
@budchirp budchirp added the bug Issue was opened via the bug report template. label Nov 5, 2022
@remorses
Copy link
Contributor

remorses commented Nov 6, 2022

Probably related to #42349, when I profiled memory half of the heap was strings and they were also increasing with each request

@ariesclark

This comment was marked as outdated.

@ariesclark
Copy link

issue still persists in v13.0.3.

@AlonHor
Copy link

AlonHor commented Nov 13, 2022

I also have this issue.

@arthureberledev
Copy link

Same for me. A couple of times a day i get this error. Restarting the dev server helps

@budchirp
Copy link
Author

Same for me. A couple of times a day i get this error. Restarting the dev server helps

Restarting the server helps but it's annoying to restart the server everytime.

@AlonHor
Copy link

AlonHor commented Nov 15, 2022

Yeah after the server crashes for JavaScript heap out of memory I just start up the server again, but it's inconvenient and annoying. Also it's taking a lot of memory usage while the app is running, so that's also very annoying since the app is functioning slower and compiling slower (by a lot).

@arthureberledev
Copy link

Same for me. A couple of times a day i get this error. Restarting the dev server helps

Don't misunderstand me, this was just meant as a temporarily fix. I also find it extremely annoying and i am worried that this might also happen in production...

@AlonHor
Copy link

AlonHor commented Nov 16, 2022

Same for me. A couple of times a day i get this error. Restarting the dev server helps

Don't misunderstand me, this was just meant as a temporarily fix. I also find it extremely annoying and i am worried that this might also happen in production...

It'll probably not happen in production since its being compiled while building it and also it's a lot more optimized but yeah that's worrying.

@remorses
Copy link
Contributor

For me it happens in production too, Next 12 was working well with 500 Mb of RAM, now it gets out of memory on the first page reload

@adshodgson
Copy link

Seems to constantly crash for me on Next13

image

@Alexandredc
Copy link

Alexandredc commented Nov 18, 2022

Same problem here !
If a page have lot of <Link>, Next prebuilt all of these pages resulting high memory consumption and slow down of the app.

@AlonHor
Copy link

AlonHor commented Nov 18, 2022

Release 13.0.4 seemed to had fixed it for me. You can update by doing:

npm i next@13.0.4 # npm
# or
yarn add next@13.0.4 # yarn

on your current project. It shouldn't break stuff that's already working. Also try to eliminate some dependencies that you don't need or that have a lighter alternative.

Here's the release.

@arthureberledev
Copy link

I am on 13.0.4 and it still happened to me a couple of times today. This is the latest stack trace:

`<--- Last few GCs --->

[21540:000001D236F10AA0] 1498088 ms: Mark-sweep 4065.1 (4138.6) -> 4053.0 (4142.6) MB, 270.3 / 0.1 ms (average mu = 0.208, current mu = 0.056) allocation failure scavenge might not succeed
[21540:000001D236F10AA0] 1498502 ms: Mark-sweep 4069.0 (4142.6) -> 4056.9 (4146.6) MB, 396.8 / 0.1 ms (average mu = 0.115, current mu = 0.040) allocation failure scavenge might not succeed

<--- JS stacktrace --->

FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory
1: 00007FF62B780AAF v8::internal::CodeObjectRegistry::~CodeObjectRegistry+124015
2: 00007FF62B70C866 v8::internal::wasm::WasmCode::safepoint_table_offset+64182
3: 00007FF62B70D8E2 v8::internal::wasm::WasmCode::safepoint_table_offset+68402
4: 00007FF62C041CE4 v8::Isolate::ReportExternalAllocationLimitReached+116
5: 00007FF62C02C2AD v8::SharedArrayBuffer::Externalize+781
6: 00007FF62BECF88C v8::internal::Heap::EphemeronKeyWriteBarrierFromCode+1468
7: 00007FF62BECC9A4 v8::internal::Heap::CollectGarbage+4244
8: 00007FF62BECA320 v8::internal::Heap::AllocateExternalBackingStore+2000
9: 00007FF62BEE8030 v8::internal::FreeListManyCached::Reset+1408
10: 00007FF62BEE86E5 v8::internal::Factory::AllocateRaw+37
11: 00007FF62BEFA68E v8::internal::FactoryBasev8::internal::Factory::AllocateRawArray+46
12: 00007FF62BEFD2CA v8::internal::FactoryBasev8::internal::Factory::NewFixedArrayWithFiller+74
13: 00007FF62BEFD523 v8::internal::FactoryBasev8::internal::Factory::NewFixedArrayWithMap+35
14: 00007FF62BD03B96 v8::internal::HashTablev8::internal::NameDictionary,v8::internal::NameDictionaryShape::EnsureCapacityv8::internal::Isolate+246
15: 00007FF62BD0193A v8::internal::Dictionaryv8::internal::NameDictionary,v8::internal::NameDictionaryShape::Addv8::internal::Isolate+58
16: 00007FF62BD09B66 v8::internal::BaseNameDictionaryv8::internal::NameDictionary,v8::internal::NameDictionaryShape::Add+118
17: 00007FF62BC16858 v8::internal::Runtime::GetObjectProperty+1720
18: 00007FF62C0CF9C1 v8::internal::SetupIsolateDelegate::SetupHeap+494417
19: 000001D23A365117
error Command failed with exit code 134.`

@ariesclark
Copy link

Release 13.0.4 seemed to had fixed it for me. You can update by doing:

npm i next@13.0.4 # npm
# or
yarn add next@13.0.4 # yarn

on your current project. It shouldn't break stuff that's already working. Also try to eliminate some dependencies that you don't need or that have a lighter alternative.

Here's the release.

13.0.4 does not resolve the memory issue for me, still have the random out of memory crashes in development, I haven't encountered any issues in production though.

@AlonHor
Copy link

AlonHor commented Nov 20, 2022

Release 13.0.4 seemed to had fixed it for me. You can update by doing:

npm i next@13.0.4 # npm
# or
yarn add next@13.0.4 # yarn

on your current project. It shouldn't break stuff that's already working. Also try to eliminate some dependencies that you don't need or that have a lighter alternative.
Here's the release.

13.0.4 does not resolve the memory issue for me, still have the random out of memory crashes in development, I haven't encountered any issues in production though.

I know that Material UI has some issues with NextJS 13, so if you're using that I'd suggest removing it and using a lighter solution. If you're not using it, try to remove dependencies that may cause an extremely high memory usage. Of course it's NextJS 13's fault, but removing dependencies might improve it.

@LorenzoBloedow
Copy link
Contributor

This is still happening to me on next 13.0.4

@andrewdoro
Copy link

still happening to me

@adshodgson
Copy link

Still bugging for me also 13.0.4

@Mistwell
Copy link

Still happening 13.0.5-canary.4

@pedronauck
Copy link

Still happening for me on 13.0.4 also 😕

@AlonHor
Copy link

AlonHor commented Nov 23, 2022

For me in 13.0.4 the memory is still high but improved since 13.0.3

@budchirp
Copy link
Author

Still not fixed in 13.0.5

@soylemezali42
Copy link

still happening 13.0.6-canary.2

@OtisTemler
Copy link

Same issue here with latest canary.
Just after start 2,5GB of ram for a rather simple app, and after a bit of time = crash.

@Nefcanto
Copy link

Nefcanto commented Dec 4, 2022

This is an extremely annoying problem. We are a website design agency. We migrated one of our websites to Next.js 13 (13.0.5) and it's using more than 900MBs of RAM. The same site in ASP.NET Core Pages used less than 100 MBs.

Vercel, at least give us hints on how to debug this issue on our side.

@m1nsuplee
Copy link

The same problem happened to me.

I am using version 13.0.5, and the same problems have occurred frequently in previous versions.

@aaronkchsu
Copy link

same problem here, using the with apollo example from here https://github.com/vercel/next.js/tree/canary/examples/with-apollo

image

kodiakhq bot pushed a commit that referenced this issue Dec 12, 2022
## Context

There has been [some reports ](#42514 OOMs-related crashes with Next 13. Whilst we're fixing the memory leaks that are causing this, some of which are caused by upstream issues, this PR makes Next.js' dev server restarts if it detects that it is gonna crash soon.

You can disable this behaviour by passing `__NEXT_DISABLE_MEMORY_WATCHER=1` to the env process.

## Details

Under the hood, we're using Node's cluster API to create a child worker that will basically watch the memory usage after every request and then kill itself if it goes over 90% of the maximum heap allowance.


## Test plan

I added manually a  leaking function that I called before handling a request. I then manually tested that the server re-started when we were near the limit.

```

function createMemoryLeak() {
  console.log('createMemoryLeak', process.memoryUsage().heapUsed / 1024 / 1024)
  for (let i = 0; i < 10; i++) {
    buffer.push(new Array(1000000).fill('a'))
  }
}

```


## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have a helpful link attached, see [`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [ ] [e2e](https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs) tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have a helpful link attached, see [`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm build && pnpm lint`
- [ ] The "examples guidelines" are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)
@feedthejim
Copy link
Contributor

The fix has landed on canary, please try it out and let me know if it makes your experience better.

We're still blocked on the Node.js bug and we're investigating how we can solve this but I don't expect that it'll be fixed fast :/ .

@adshodgson
Copy link

adshodgson commented Dec 13, 2022

@feedthejim Thanks, it seems a combination of solutions you've implemented has eased the amount of crashing that occurs in the latest Canary release.

One thing that i find really strange is how slow my app takes to compile when switching pages during development mode,

Could this be some cause of the prefetching of links you described earlier?
I can sometimes wait in excess of 8-10 seconds for a page change. (Turbo unfortunately doesn't work for me)

In Production, this is a non-existent issue - lightning fast, but developing is really tedious at the moment.

@soylemezali42
Copy link

I have tested the app with last canary release. We aren't writing "yarn dev" any more .(heyy). We have lost our productivity on the server after migrating 13. We were expecting to see magics that announced on everywhere. Working on this server now is just so frustrating.

@feedthejim
Copy link
Contributor

Thanks for the feedback @adshodgson @soylemezali42!

@adshodgson I will surface that to the team... that's definitely something on my mind as well.

@soylemezali42 can you expand more on not using yarn dev anymore? Also, is your other feedback related to page slowness?

timneutkens pushed a commit that referenced this issue Dec 13, 2022
## Context

There has been [some reports ](#42514 OOMs-related crashes with Next 13. Whilst we're fixing the memory leaks that are causing this, some of which are caused by upstream issues, this PR makes Next.js' dev server restarts if it detects that it is gonna crash soon.

You can disable this behaviour by passing `__NEXT_DISABLE_MEMORY_WATCHER=1` to the env process.

## Details

Under the hood, we're using Node's cluster API to create a child worker that will basically watch the memory usage after every request and then kill itself if it goes over 90% of the maximum heap allowance.


## Test plan

I added manually a  leaking function that I called before handling a request. I then manually tested that the server re-started when we were near the limit.

```

function createMemoryLeak() {
  console.log('createMemoryLeak', process.memoryUsage().heapUsed / 1024 / 1024)
  for (let i = 0; i < 10; i++) {
    buffer.push(new Array(1000000).fill('a'))
  }
}

```


## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have a helpful link attached, see [`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [ ] [e2e](https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs) tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have a helpful link attached, see [`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm build && pnpm lint`
- [ ] The "examples guidelines" are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)
@Nefcanto
Copy link

How about the production environment?

@feedthejim
Copy link
Contributor

Hi @Nefcanto, can you open a new issue with a repro of your setup/what operations you noticed increased memory usage?

@feedthejim feedthejim changed the title Extremely high memory usage Bug: extremely high memory usage with next dev Dec 16, 2022
@JustinPraas
Copy link

Watching this carefully, as I have a Next project with about 12 pages and 260 static pages. 547MB free mem, and it dies rather quickly

@adshodgson
Copy link

The Production build seems to run fine for me, really quick.

The fixes @feedthejim suggested, regarding changing the Memory Limit, and also the patches introduced have stopped the server from crashing in Development mode.

I think the only serious problem for me, seems to be how slow the App is in Development mode - when trying to navigate between pages, I can sometimes wait for up to 8-10 seconds for each page to switch - Whilst in production it's almost instantaneous.

I'm unsure the cause, just hinders productivity quite dramatically.

@Alexandredc
Copy link

The Production build seems to run fine for me, really quick.

The fixes @feedthejim suggested, regarding changing the Memory Limit, and also the patches introduced have stopped the server from crashing in Development mode.

I think the only serious problem for me, seems to be how slow the App is in Development mode - when trying to navigate between pages, I can sometimes wait for up to 8-10 seconds for each page to switch - Whilst in production it's almost instantaneous.

I'm unsure the cause, just hinders productivity quite dramatically.

Do you fetch data in layout ? I just found out that fetching in layout reduce a lot development mode.

@feedthejim
Copy link
Contributor

@adshodgson do you mind sharing a repro (preferably via codesanbox or similar tool)? I can take a look.

There's a few things that can slow down dev times:

  • we changed the strategy around serving routes for the app router in dev, where we have to bundle server and client in order to render a page. This is not slow per-se but if you're using really big packages like react-icons where it bundles a huge amount of files, this might affect you. I'm investigating ways we can make that better.
  • you might be doing some blocking work in a top-level layout/middleware file like @Alexandredc mentioned that may not be properly wrapped with a suspense boundary, something like:

async function Layout() {
  const somethingThatDoesntNeedToBlockRendering = await something();

  return <>
      {somethingThatDoesntNeedToBlockRendering && <Foo />
      {children}
  </>
}

// better alternative that leverages streaming

function SomethingThatDoesntNeedToBlockRendering() {
  return somethingThatDoesntNeedToBlockRendering && <Foo />
}

function Layout() {
  return <>
      <React.Suspense fallback={null}>
       <SomethingThatDoesntNeedToBlockRendering />
     </React.Suspense>
      {children}
  </>
}

@Nefcanto
Copy link

Nefcanto commented Dec 16, 2022

@feedthejim I sent you an invitation here. This is one of our real-world examples. We are a website design company. We use Next.js as our website tech and other technologies for our backend and API. We're still using Next.js 12. We used ASP.NET Core Razor Pages before and we had much more density per server. We could host 10 websites per 1GB of RAM. Now we're limited to 1 or 2 at most. This has increased our hosting costs drastically and we're thinking of migrating to another tech, like Qwik maybe.

But if we can get lower RAM in production, then we're good to continue using Next.js.

@feedthejim, I would gladly send you remote access to my PC and I would continue the debugging session with you if you want to. I would guide you through our architecture (though it's not hard at all), and explain how we use Next.js. Just let me know. Thank you so much.

@tomscript
Copy link

I'm also encountering this and can share a repo.

  • in case it helps im on a Macbook Air M1, 2020, 16GB, Ventura

  • this is from running npm run dev only

image

"next": "^13.0.8-canary.0",

One thing that i find really strange is how slow my app takes to compile when switching pages during development mode,

  • this is exactly what i notice as well

@hamza512b
Copy link

Hi all!
I do not know if this helpful, but this happens also when testing with next/jest when you I run jest --watch.

@quiet-node
Copy link

Any official fix yet? still happening for me and export NODE_OPTIONS=--max_old_space_size=8192 won't help at all. I'm running next 13.0.3-canary.0

@feedthejim
Copy link
Contributor

@logann131 can you try upgrading and report back if it still happens?

@mooijtech
Copy link

Also facing this issue, memory climbs to ~5GB while it should be ~30MB.
Trying to remove all code until it's fixed to find the cause.

@feedthejim
Copy link
Contributor

@mooijtech on a dev or prod instance?

@mooijtech
Copy link

@feedthejim Long story short, turns out the memory leak is not related to NextJS but Tauri (https://tauri.app/) caused by the tauri-plugin-persisted-scope.

I will open an issue there.

Thanks for your reply.

@dexter4life
Copy link

I notice using dynamic to render component seems to provide some improvement mostly if the SSR is set to true, just in case anyone here want to experiment on that too.

@dexter4life
Copy link

image
I am having this error, sometimes, can someone explain this?

@feedthejim
Copy link
Contributor

@dexter4life can you perhaps open an issue with a repo?

I'll be closing this issue as the frequency of the reports seems to have lessened a bit. Please open an issue with repro steps if you encounter issues again!

@github-actions
Copy link
Contributor

This closed issue has been automatically locked because it had no new activity for a month. If you are running into a similar issue, please create a new issue with the steps to reproduce. Thank you.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Feb 22, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
bug Issue was opened via the bug report template. Developer Experience Issues related to Next.js logs, Error overlay, etc.
Projects
None yet
Development

No branches or pull requests