Click here to close now.





















Welcome!

@CloudExpo Authors: Liz McMillan, Pat Romanski, Blue Box Blog, Elizabeth White, Yeshim Deniz

Related Topics: @BigDataExpo, @CloudExpo, @ThingsExpo, @DevOpsSummit

@BigDataExpo: Article

Node.js Memory Leaks | @ThingsExpo #IoT #BigData #DevOps #Microservices

Memory leaks can be a serious problem in Node.js, potentially affecting the performance of your Node apps

Understanding Node.js Memory Leaks

By Omed Habib

Memory leaks can be a serious problem in Node.js, potentially affecting the performance of your Node apps. Although it might look like a predicament in the back-end is causing the application to fail, the real source of a bug could be a Node.js memory leak. It’s important to understand what memory leaks are, why they occur, and how to detect and solve memory leaks in Node.js, to get ultimately to the bottom of fixing memory leaks.

What Is a Memory Leak?

A memory leak occurs when an application takes over part of a computer’s memory and fails to release it at the appropriate time. Over time, this can lead to the computer running out of memory, causing a decrease in performance. When a Node.js memory leak occurs, the affected application may run slowly or freeze completely. A memory leak can cause a serious performance problem that needs to be diagnosed and solved.

How Does Node.js Manage Memory?

Complications with the V8 garbage collector (Google’s Javascript engine) potentially lead to Node.js memory leaks. V8 is an open source engine that runs Node.js applications, although it was not designed specifically for Node. V8 deals with memory management on behalf of the Node.js applications, making life easier for Node developers because it takes away the manual task of writing code that deals with the management of memory. However, automatic memory management can also be a problem because it takes control away from application developers.

When V8 needs to allocate memory to an object in a Node.js application, it usually does so by using a pointer to assign an object or variable to a new piece of memory. Eventually, the available memory starts to run out, at which point V8 begins a process of garbage collection to free up memory.

The V8 garbage collector must identify which regions of memory can be reallocated without affecting the performance of the application. It follows pointers to find out which objects are currently live and which can not be reached by the existing set of pointers. Memory that contains unreachable objects is called a “dead” region, and can safely be reallocated.

What Causes Memory Leaks?

To avoid memory leaks, V8 needs to know the exact locations of all objects in memory. If objects are identified incorrectly as pointers, memory leaks can result. Memory leaks can occur when the actual memory used by an object extends beyond the memory that has been allocated to that object.

Another potential cause of memory leaks is a callback function, a Javascript function that can be passed as an argument to other code. The V8 garbage collector does not always know whether it is safe to remove objects used in a callback function that can be called multiple times, leading to memory not being reallocated when it should. Callback functions are examples of closures, functions that have access to the variables of the function that called it. Closures are a well-known cause of memory problems because the variables must be left in the memory for as long as closure functions could need to use them.

Node.js memory leaks most commonly occur in objects that contain large collections of data, such as arrays or hashmaps. However, Node.js memory leaks can also occur in other object types, such as strings.

Sometimes, the cause of a memory leak in a Node.js application is not in the application’s code, but rather in an upstream code that the application depends on for its execution. This makes Node.js memory leaks difficult to diagnose. If you have been staring at your Javascript code for ages, and you are convinced that it is not causing your memory leak, then consider looking at the upstream code for the source of your problem.

In summary, you should consider the following potential causes of a Node.js memory leak:

  • Callbacks and closures
  • Leaky constructors of classes you have defined
  • Collection objects, such as arrays and hashmaps
  • Upstream code

What Are the Symptoms of a Memory Leak in a Node.js Application?

Memory leaks can affect the performance of Node.js applications, causing them to run slowly, malfunction or freeze up completely. Many leaks begin very slowly, but over time, they can cause the app to slow down as V8 needs to spend more and more time in garbage collection mode to manage the app’s memory uses.

Memory leaks can also cause odd behavior in a Node.js application. For example, you might notice that your application stops being able to open new database connections. This occurs because the leaking code is hanging onto references to the resources that the app needs to open new connections. You may find that you need to restart the app to restore its performance.

Not all memory leaks cause noticeable symptoms during the development or testing phase. However, it is still worth trying to find memory leaks in your application so you can eliminate them. As your app becomes more popular, the greater the number of users that will make demands from it. Even a relatively slow memory leak can damage the performance of an app, slowing it down and preventing it from offering the best possible performance to your users. If you let a memory leak continue unchecked, your app will eventually crash, which can be extremely embarrassing and damaging to your reputation among your customers and the online community at large.

Making more RAM available for your app or restarting your service every time its memory usage starts to get out of hand can prevent a crisis. However, it is better to track down the problem and fix it, so your app runs efficiently and consistently without the constant need for you to monitor it or worry about it breaking down.

How Do You Diagnose a Memory Leak in a Node.js Application?

Many metrics can diagnose memory leaks in a Node.js application. These include heap usage, heap growth and frequency of garbage collection. You can also use tools to help you detect leaks in Node.js applications, some of which are listed in this summary from Mozilla.

A heap profiler is an extremely useful tool for diagnosing memory leaks in Node applications. A non-leaky memory profile shows memory usage increasing in response to incoming requests. After the requests are dealt with, you should see memory usage decrease as objects that are no longer needed are destroyed, and the used memory is released.

A leaky memory profile looks very different from a normal profile. Memory usage increases over time. The longer the application is open, the less memory is available, until you reach the point where you must restart the app to reduce the memory usage to normal and restore the app’s performance. Note that memory leaks can be rapid, in which case they are quick and easy to notice in the heap memory usage, or slow, in which case memory usage increases much more gradually.

Taking a look at the instance counts of various types of objects can help to pin down the source of the memory leak in a Node.js application. If the instance count of a particular type of object grows strongly and does not come back down, then this type of object is likely to be the source of the memory leak. Usually, you would expect instance counts of each object to come back down after each garbage collection cycle, so look for objects that don’t have this behavior.

Analyzing these metrics can help you work out which part of your code is causing the problem so you can track down the bug and fix it as quickly as possible. For example, if you have written a leaky class called myClass, then you are likely to see objects of type myClass using up most of the memory in the heap stack. You can then check your definition of the myClass class to look for code that allows a memory leak to occur.

Also, pay attention to the frequency with which the V8 engine runs the garbage collection. When this happens, you might notice your app slowing down. The leakier your code, the more often V8 needs to perform garbage collection.

Dealing With Node.js Memory Leaks

It is important to diagnose and control memory leaks while developing your Node application. Be aware that your application might be experiencing memory leaks from more than one source, so when you think you have eliminated a memory leak, repeat your tests to make sure that the leaks are gone.

Although diagnosing and eliminating memory leaks takes some time, it is worth making the effort to wipe out leaks while developing your app. If you try to build on a leaky code to add more functionality to your app later on, you may find that its performance becomes too detrimental for the app to be useful to your users.

By learning to deal with Node.js memory leaks, you can train yourself to build better apps that work well. You’ll learn to consider the possibility of memory leaks when writing new code. For example, when creating a new class, you need to watch out for constructors that create large objects that don’t get deleted when they should be. You can help to prevent Node.js memory leaks by always considering how and when objects will be created and destroyed while you write your code.

The post Understanding Node.js Memory Leaks appeared first on Application Performance Monitoring Blog | AppDynamics.

More Stories By AppDynamics Blog

In high-production environments where release cycles are measured in hours or minutes — not days or weeks — there's little room for mistakes and no room for confusion. Everyone has to understand what's happening, in real time, and have the means to do whatever is necessary to keep applications up and running optimally.

DevOps is a high-stakes world, but done well, it delivers the agility and performance to significantly impact business competitiveness.

@CloudExpo Stories
Containers are revolutionizing the way we deploy and maintain our infrastructures, but monitoring and troubleshooting in a containerized environment can still be painful and impractical. Understanding even basic resource usage is difficult - let alone tracking network connections or malicious activity. In his session at DevOps Summit, Gianluca Borello, Sr. Software Engineer at Sysdig, will cover the current state of the art for container monitoring and visibility, including pros / cons and li...
Nowadays, a large number of sensors and devices are connected to the network. Leading-edge IoT technologies integrate various types of sensor data to create a new value for several business decision scenarios. The transparent cloud is a model of a new IoT emergence service platform. Many service providers store and access various types of sensor data in order to create and find out new business values by integrating such data.
There are many considerations when moving applications from on-premise to cloud. It is critical to understand the benefits and also challenges of this migration. A successful migration will result in lower Total Cost of Ownership, yet offer the same or higher level of robustness. Migration to cloud shifts computing resources from your data center, which can yield significant advantages provided that the cloud vendor an offer enterprise-grade quality for your application.
The modern software development landscape consists of best practices and tools that allow teams to deliver software in a near-continuous manner. By adopting a culture of automation, measurement and sharing, the time to ship code has been greatly reduced, allowing for shorter release cycles and quicker feedback from customers and users. Still, with all of these tools and methods, how can teams stay on top of what is taking place across their infrastructure and codebase? Hopping between services a...
Manufacturing has widely adopted standardized and automated processes to create designs, build them, and maintain them through their life cycle. However, many modern manufacturing systems go beyond mechanized workflows to introduce empowered workers, flexible collaboration, and rapid iteration. Such behaviors also characterize open source software development and are at the heart of DevOps culture, processes, and tooling.
Between the compelling mockups and specs produced by analysts, and resulting applications built by developers, there exists a gulf where projects fail, costs spiral, and applications disappoint. Methodologies like Agile attempt to address this with intensified communication, with partial success but many limitations. In his session at DevOps Summit, Charles Kendrick, CTO and Chief Architect at Isomorphic Software, will present a revolutionary model enabled by new technologies. Learn how busine...
The last decade was about virtual machines, but the next one is about containers. Containers enable a service to run on any host at any time. Traditional tools are starting to show cracks because they were not designed for this level of application portability. Now is the time to look at new ways to deploy and manage applications at scale. In his session at @DevOpsSummit, Brian “Redbeard” Harrington, a principal architect at CoreOS, will examine how CoreOS helps teams run in production. Attende...
The buzz continues for cloud, data analytics and the Internet of Things (IoT) and their collective impact across all industries. But a new conversation is emerging - how do companies use industry disruption and technology enablers to lead in markets undergoing change, uncertainty and ambiguity? Organizations of all sizes need to evolve and transform, often under massive pressure, as industry lines blur and merge and traditional business models are assaulted and turned upside down. In this new da...
IT data is typically silo'd by the various tools in place. Unifying all the log, metric and event data in one analytics platform stops finger pointing and provides the end-to-end correlation. Logs, metrics and custom event data can be joined to tell the holistic story of your software and operations. For example, users can correlate code deploys to system performance to application error codes.
Containers are changing the security landscape for software development and deployment. As with any security solutions, security approaches that work for developers, operations personnel and security professionals is a requirement. In his session at @DevOpsSummit, Kevin Gilpin, CTO and Co-Founder of Conjur, will discuss various security considerations for container-based infrastructure and related DevOps workflows.
NHK, Japan Broadcasting, will feature the upcoming @ThingsExpo Silicon Valley in a special 'Internet of Things' and smart technology documentary that will be filmed on the expo floor between November 3 to 5, 2015, in Santa Clara. NHK is the sole public TV network in Japan equivalent to the BBC in the UK and the largest in Asia with many award-winning science and technology programs. Japanese TV is producing a documentary about IoT and Smart technology and will be covering @ThingsExpo Silicon Val...
The cloud has reached mainstream IT. Those 18.7 million data centers out there (server closets to corporate data centers to colocation deployments) are moving to the cloud. In his session at 17th Cloud Expo, Achim Weiss, CEO & co-founder of ProfitBricks, will share how two companies – one in the U.S. and one in Germany – are achieving their goals with cloud infrastructure. More than a case study, he will share the details of how they prioritized their cloud computing infrastructure deployments ...
WebRTC converts the entire network into a ubiquitous communications cloud thereby connecting anytime, anywhere through any point. In his session at WebRTC Summit,, Mark Castleman, EIR at Bell Labs and Head of Future X Labs, will discuss how the transformational nature of communications is achieved through the democratizing force of WebRTC. WebRTC is doing for voice what HTML did for web content.
Developing software for the Internet of Things (IoT) comes with its own set of challenges. Security, privacy, and unified standards are a few key issues. In addition, each IoT product is comprised of at least three separate application components: the software embedded in the device, the backend big-data service, and the mobile application for the end user's controls. Each component is developed by a different team, using different technologies and practices, and deployed to a different stack/...
Overgrown applications have given way to modular applications, driven by the need to break larger problems into smaller problems. Similarly large monolithic development processes have been forced to be broken into smaller agile development cycles. Looking at trends in software development, microservices architectures meet the same demands. Additional benefits of microservices architectures are compartmentalization and a limited impact of service failure versus a complete software malfunction....
There are so many tools and techniques for data analytics that even for a data scientist the choices, possible systems, and even the types of data can be daunting. In his session at @ThingsExpo, Chris Harrold, Global CTO for Big Data Solutions for EMC Corporation, will show how to perform a simple, but meaningful analysis of social sentiment data using freely available tools that take only minutes to download and install. Participants will get the download information, scripts, and complete en...
As-a-service models offer huge opportunities, but also complicate security. It may seem that the easiest way to migrate to a new architectural model is to let others, experts in their field, do the work. This has given rise to many as-a-service models throughout the industry and across the entire technology stack, from software to infrastructure. While this has unlocked huge opportunities to accelerate the deployment of new capabilities or increase economic efficiencies within an organization, i...
Interested in leveraging automation technologies and a cloud architecture to make developers more productive? Learn how PaaS can benefit your organization to help you streamline your application development, allow you to use existing infrastructure and improve operational efficiencies. Begin charting your path to PaaS with OpenShift Enterprise.
DevOps and Continuous Delivery software provider XebiaLabs has announced it has been selected to join the Amazon Web Services (AWS) DevOps Competency partner program. The program is designed to highlight software vendors like XebiaLabs who have demonstrated technical expertise and proven customer success in DevOps and specialized solution areas like Continuous Delivery. DevOps Competency Partners provide solutions to, or have deep experience working with AWS users and other businesses to help t...
Data loss happens, even in the cloud. In fact, if your company has adopted a cloud application in the past three years, data loss has probably happened, whether you know it or not. In his session at 17th Cloud Expo, Bryan Forrester, Senior Vice President of Sales at eFolder, will present how common and costly cloud application data loss is and what measures you can take to protect your organization from data loss.