In this lesson, you will learn how to read garbage collection (GC) logs to spot when your application is pausing too long to clean up memory.
Why GC Logs Matter
Node.js uses the V8 engine, which automatically frees up memory via Garbage Collection. When V8 performs a "Major GC" (a full heap cleanup), it often triggers a "stop-the-world" event. During this time, your JavaScript execution freezes. If your logs show that these pauses are becoming frequent or taking too long, your application will suffer from high latency spikes, even if your CPU usage seems low.
Reading the Logs
To see these logs, you start your Node.js application with the --trace-gc flag:
node --trace-gc app.js
When you run this, you will see lines like this in your console:
[12345:0x123456789] 50 ms: Scavenge 12.5 (15.2) -> 8.2 (16.2) MB, 0.8 / 0.0 ms (average mu = 0.995, current mu = 0.998) allocation failure
Here is how to interpret the critical parts:
- The timestamp: The
50 mstells you when the GC occurred since the process started. - Memory usage:
12.5 (15.2) -> 8.2 (16.2) MBshows how much memory was used before vs. after the collection. If the number after the arrow is consistently close to the number in parentheses, it means your heap is nearly full and V8 is struggling to find space. - The duration: The
0.8 / 0.0 mspart is vital. It represents the time spent in the GC pause. If you see values here climbing into the hundreds of milliseconds, your application is experiencing "stop-the-world" latency that will impact your users' experience.
Spotting Issues
You are looking for a pattern where the "After" memory usage grows steadily over time, leading to increasingly frequent and longer GC pauses. This is often a sign of a memory leak—objects are staying in memory longer than intended, forcing V8 to work harder to clean up the mess. If the logs show "allocation failure" frequently, it means the heap is exhausted, and your code is likely churning through memory too quickly.
Key Takeaway: Use the --trace-gc flag to monitor pause durations; if your GC pause times are consistently growing or exceeding your latency budget, you likely have a memory management issue in your application code.