1
头图

When the Node.js process of a web application running in server-side rendering mode encounters a memory leak, we can usually observe frequent memory spikes and pod restarts, as shown in the Dynatrace tool below:

The key to analyzing memory leak problems is to collect multiple memory dumps at different points in time and compare the object growth between each collection, such as shortly after a Pod restart and before memory saturation.

You can collect and load Memory Dump in Chrome from browser developer tools > Memory (heap snapshot should be selected) > Load.

After creating Memory Dumps over different time periods, you can use the embedded comparison tool to quickly identify the objects that have grown the most between two points in time.

Using the Chrome Inspector tool, it is possible to connect to a remote target and observe memory usage in real time. If the memory leak problem can be reproduced locally, then you can debug it with Storefront running locally.

Run the Node.js application in debug mode, go to chrome://inspect, and if localhost:9229 is configured in the port forwarding, you should now be able to see the application and debug it.

One of the most common mistakes that cause memory leaks in JS Storefront applications is subscribing to events without unsubscribing after the component is destroyed. Here's an example of preventing this memory leak - the key is to review your code and make sure you unsubscribe from any events in ngOnDestroy().

The same happens when using an EventService and forgetting to unregister from the event source Observable. Anytime an event service is used, it should be unregistered using the tear down function returned by register().

SSR Caching

One of the most powerful tools for improving memory consumption in JS Storefront applications running in SSR mode is the SSR cache, there are two approaches:

  • Deprecated practice: Cache rendered SSR pages directly on the server. This is not recommended in a production environment, as it does not scale well and will end up consuming more memory than it would without SSR caching enabled.
  • Recommended practice: Cache rendered SSR pages on the CDN. This can improve the performance of SSR applications because it will reduce the number of requests to the SSR server, while storing prerendered pages on a server built specifically for this purpose.

注销
1k 声望1.6k 粉丝

invalid