r/node • • Aug 10 '24

Common Causes of Memory Leaks in JavaScript

https://www.trevorlasn.com/blog/common-causes-of-memory-leaks-in-javascript
80 Upvotes

30 comments sorted by

5

u/yuuggvo Aug 10 '24 edited Aug 10 '24

I’m not able to see what causes the memory leak in the “Unmanaged callbacks” section

16

u/CUNT_PUNCHER_9000 Aug 10 '24

/u/thickoat

import { setTimeout } from "node:timers/promises"

const TIMEOUT = 10;

const registry = new FinalizationRegistry(console.log);

function fetchData(callback) {
    const data = new Array(1000000).fill('Data');
    registry.register(data, "garbage collecting data");
    setTimeout(() => callback(data), TIMEOUT);
}

function handleData(data) {
    console.log(data[0]);
}

while (true) {
    await setTimeout(TIMEOUT)
    fetchData(handleData);
}

Yeah this is not a memory leak - you can use the FinalizationRegistry to log when the data is garbage collected.

The issue is more memory pressure by holding onto data for the duration of the timeout. But it is eventually garbage collected.

1

u/mindtaker_linux Apr 08 '25

await needs to be inside async function 

2

u/CUNT_PUNCHER_9000 Apr 08 '25

Not with top level await (es6 modules). Try this out yourself (note you have to name the file .mjs to interpret it as a module

% cat foo.mjs 
const fn = () => new Promise(r => setTimeout(r, 1000));

while (true) {
  await fn();
  console.log('ok');
}

https://v8.dev/features/top-level-await

1

u/[deleted] Aug 10 '24

Updated the article

3

u/CUNT_PUNCHER_9000 Aug 10 '24

I still don't get the explanation, or at the very least it's surprising to me.

At the end of handleData there should be no strong reference to data anymore and it should be marked for GC. I'd be interested to try this in a test and see if this could be replicated.

2

u/kurtextrem Aug 12 '24

1

u/CUNT_PUNCHER_9000 Aug 12 '24

This is much more interesting, those links at the bottom are great

1

u/voidvector Aug 10 '24

Same could be said about "Closures Capturing Variables". There are common legitimate use cases for those. It is effectively equivalent to classes instantiation in OOP.

18

u/Himankshu Aug 10 '24

So when someone says node js has memory leak issues, they don’t actually knows how to free up unnecessary memory?

7

u/ethereumfail Aug 10 '24

remember there was an issue with console log preventing garbage collector from freeing up memory? With dependency trees people normally use with updates they keep allowing changing the codebase all the time, it's impossible to track all that stuff manually imo. I just work under assumption there probably is a leak to some degree so I always have automated periodic resets on any long term services

0

u/lIIllIIlllIIllIIl Aug 11 '24

There are some "well known" memory leak issues with Node.js.

For example, if you use the built-in Fetch API and don't read the body of requests and responses, Node will leak memory.

0

u/Himankshu Aug 11 '24

K think thats what typescript also helps in? Because TS will complain if the req or res parameter is not read

0

u/alamakchat Aug 11 '24

Moat of them are specific to v8s opts and deopts, not how you write your code.

2

u/[deleted] Aug 11 '24
  • incorrect use of bind()

  • Circular References

2

u/voidvector Aug 10 '24 edited Aug 10 '24

Might want to include substring memory leak in V8.

When you .substring() in V8, the engine would simply create a fat pointer (pointer with size) into the original string. If the difference of your substring to the original is significant, and you do a lot of those substring operations, there would be leak.

5

u/CUNT_PUNCHER_9000 Aug 11 '24

Pedantic, but that's still not a memory leak though, just an inefficient use of memory. The string and substring would still be garbage collected.

A leak would have to mean that the memory would never be collected.

2

u/voidvector Aug 11 '24 edited Aug 11 '24

This identical behavior to #4 in the linked blog:

  • Blog - "closure variables" get cleaned up when the "inner function" goes out the scope

  • Here - "original string" get cleaned up when the "substring" goes out of the scope

Similarly, closure variables are not technically memory leak, because they are still needed for future execution of the "inner function". The only difference is closure behavior is language semantics, substring behavior is V8 optimization.

1

u/skizzoat Aug 10 '24

404 right there ;)

3

u/voidvector Aug 10 '24

Fixed. I pressed Ctrl-V twice

1

u/[deleted] Aug 14 '24

node seems to be a memory glutton anyway but very convenient for writing backends because of the community so it is hard to part with. at least that is my opinion

1

u/DecentGoogler Aug 10 '24

Thanks, learned something new :)

0

u/[deleted] Aug 10 '24

[deleted]

2

u/m_hans_223344 Aug 11 '24

You can easily create memory leaks in Rust as well.

0

u/[deleted] Aug 12 '24

[removed] — view removed comment

0

u/DoubleAway6573 Aug 12 '24

People more intelligent than me have done it before:

https://doc.rust-lang.org/book/ch15-06-reference-cycles.html#:~:text=We%20can%20see%20that%20Rust,values%20will%20never%20be%20dropped.

Prevent memory leaks is a very complex issue.

0

u/[deleted] Aug 12 '24

[removed] — view removed comment

1

u/DoubleAway6573 Aug 12 '24

Yes, I haven't created any complex in rust. I'm working through "The Rust Programming Language" book by Steve Klabnik and Carol Nichols. And that's the source of the link.

JS si a minefield. And python is not far away. Is rust a much sane language? undoubtedly. But saying it's "Imposible" to get a memory leak sound more like a fanboy or a religious zealot.