Thursday 21 November 2019

Interview Question: What are some common causes of memory leaks in Node? How might you detect and address them?

Hey all,New-ish dev here. I recently went on an interview where I was asked "What are some common causes of memory leaks in Node? How might you address them?" I thought this was a really good interview question and I hadn't been asked it before.I'd appreciate any feedback on my response.Forgetting to unregister event listeners.Objects, global or otherwise, that are being referenced multiple times and aren't being garbage collectedClosures could be maintaining references to large objects.[this is all I could think of on the spot]"I haven't yet dealt with a memory leak problem but I would try to get some preliminary data. Ideally, we would be using PM2 or some other process monitoring tool in production for monitoring/logging and gather some metrics and insights. Is memory growing sharply or gradually over time? Is there one particular process or is it spread across multiple? If this is an API server, is there a particular offending endpoint?To further isolate the issue we can use node inspector and do some snapshot comparisons. Trigger a garbage collection to start from a clean state, then initiate a snapshot. Once we are finished profiling, we can do a comparison of the heap before and after. We can then use the inspector to drill into which objects seem to maintaining the largest size. If there is a clear offender, we can go back to the code and see if we can remediate the memory leak. We repeat the same process to test if we were successful."Anything else I might be missing or that I could improve upon?

Submitted November 21, 2019 at 02:56PM by brodega

No comments:

Post a Comment