In a perfect world, a web developer shouldn’t deal with memory leaks. In reality, memory issues are a known Node’s gotcha one must be aware of. Above all, memory usage must be monitored constantly. In the development and small production sites, you may gauge manually using Linux commands or npm tools and libraries like node-inspector and memwatch. The main drawback of this manual activities is that they require a human being actively monitoring – for serious production sites, it’s absolutely vital to use robust monitoring tools e.g. (AWS CloudWatch, DataDog or any similar proactive system) that alerts when a leak happens. There are also few development guidelines to prevent leaks: avoid storing data on the global level, use streams for data with dynamic size, limit variables scope using let and const.
From the blog Dyntrace:
... ”As we already learned, in Node.js JavaScript is compiled to native code by V8. The resulting native data structures don’t have much to do with their original representation and are solely managed by V8. This means that we cannot actively allocate or deallocate memory in JavaScript. V8 uses a well-known mechanism called garbage collection to address this problem.”
From the blog Dyntrace:
... “Although this example leads to obvious results the process is always the same:
Create heap dumps with some time and a fair amount of memory allocation in between
Compare a few dumps to find out what’s growing”
From the blog Rising Stack:
... “fault, Node.js will try to use about 1.5GBs of memory, which has to be capped when running on systems with less memory. This is the expected behavior as garbage collection is a very costly operation.
The solution for it was adding an extra parameter to the Node.js process:
node –max_old_space_size=400 server.js –production ”
“Why is garbage collection expensive? The V8 JavaScript engine employs a stop-the-world garbage collector mechanism. In practice, it means that the program stops execution while garbage collection is in progress.”
웹 개발자는 메모리의 누수를 만들어서는 안된다.
실제로, 메모리 문제는 노드의 잘 알려진 문제이다.
무엇보다 메모리의 사용량을 지속적으로 처리해야 한다.
개발 및 작은 제품에서 당신은 리눅스 명령어 또는 node-inspector 및 memwatch와 같은 npm 라이브러리를 통해 수동으로 측정할 수 있다.
수동 작업의 주요한 단점은 사람이 적극적으로 모니터링 해야 한다는 것이다. 중요한 제품에서 메모리의 누수를 알려주는 강력한 모니터링 도구(AWS CloudWatch, DataDog 또는 이와 유사한 선제적 시스템)를 사용하는 것은 절대적으로 중요하다.
메모리의 누수를 방지하기 위한 몇가지 지침은 다음과 같다. 전역에서 데이터를 저장하지 말 것, 동적 데이터의 스트림을 사용할 것, let, const를 사용하여 변수 범위를 제한할 것.