A Node process can need more memory because it has more useful work to do. It can also need more memory because yesterday's work never ended. Those situations can produce similar dashboards while requiring very different changes.
An October r/node post about an interval created on every login describes the second case. Restarting temporarily lowered memory, and adding RAM only postponed the problem. The useful clue was the lifetime of the reminder job: each login started another interval, and no matching cleanup ended it.
Treat that story as a debugging question rather than a performance benchmark. How would you reproduce the suspected resource growth, identify what retains the data, and prove that a fix ends the unwanted work? A larger instance can buy investigation time, but it cannot decide those lifetimes for your application.
This guide uses a small offline lab containing synthetic invoices. It deliberately accumulates timer and listener registrations, then compares the result with explicitly disposed work. The examples run on Node 22 or later without third-party packages. Their useful assertions concern behavior and resource counts; the exact byte totals depend on the runtime and machine.
Download the complete runnable examples, including setup instructions and verification commands.
Define the work that should have finished
Start with a user action and an ownership question. In the reminder example, does a login create a short request, a durable subscription, or a process-wide background worker? Those are three different lifetimes. Registering the same background scan inside every request confuses them.
Write a short expectation before opening a profiler. For example: after an invoice subscription ends, it owns no interval and no listener on the shared event bus. Alternatively: the service owns one reminder scheduler, regardless of how many users log in. Both are testable statements. A requirement saying that memory should look normal is much harder to investigate.
Check the registration sites next. Search for timers, subscriptions, stream handlers, caches, and collections that grow when an operation begins. For each creation, locate its matching end. A missing end is a hypothesis. A repeatable increase after completed work is evidence supporting that hypothesis.
Also inspect the request's failure path. A registration may be cleaned up after success while surviving a rejected database call, a client disconnect, or an early return. Follow the same lifetime through all exits. Putting cleanup in finally is often helpful, provided the code owns the resource for the entire protected scope.
Read several memory counters together
Node's process memory reference distinguishes JavaScript heap usage from resident process memory. heapUsed and heapTotal describe V8's heap. rss covers resident memory for the process more broadly. external includes memory associated with native objects bound to JavaScript; arrayBuffers, including Node buffers, is a subset of external.
const { rss, heapUsed, heapTotal, external, arrayBuffers } = process.memoryUsage();
console.log(JSON.stringify({
timestamp: new Date().toISOString(),
rss, heapUsed, heapTotal, external, arrayBuffers
}));Do not add those fields together as if they were separate buckets. A rising heap baseline suggests one investigation path. Large buffer allocations suggest another. Stable heap usage with rising RSS does not establish a JavaScript object leak; native allocations and allocator behavior need investigation too.
Collect samples at comparable workload boundaries. Record the number of active requests or jobs alongside the counters. Otherwise, a test with increasing concurrency can look like a leak simply because more work is legitimately alive. Keep enough context to distinguish traffic growth from retention after traffic ends.
Understand the retaining path
A function can finish while a callback created inside it remains reachable. If a timer holds that callback, and the callback uses an invoice object, the object remains part of the live program. The garbage collector cannot infer that the business considers the invoice work finished.
function beginInvoiceWork(invoice) {
setInterval(() => {
console.log(invoice.id, invoice.payload.length);
}, 60_000);
}This small example contains no global array, but each invocation leaves behind scheduled work that still needs its invoice. The same reasoning applies to a listener registered on a long-lived emitter. The callback's apparent location inside a short function does not determine its lifetime.
The first diagram summarizes the ownership chain. It is an explanatory model, not a measured memory graph. The important object is often further down the path than the registration itself: a tiny callback can keep a large payload reachable.
Inspect the path that keeps data reachable. The callback can outlive the request that created it.
Reproduce accumulation in a bounded lab
The companion memory-lab.mjs creates three batches of forty synthetic invoices. Each invoice starts a reminder interval and an event listener. The fixed mode disposes each job when its scope finishes. The leaky mode retains all registrations until a final cleanup, allowing inspection without leaving an endless process behind.
node --test reminder.test.mjs
node --expose-gc memory-lab.mjs fixed
node --expose-gc --trace-warnings memory-lab.mjs leakyIn the verified run, fixed mode reported zero owned timers and listeners at every batch boundary. Leaky mode reported forty, eighty, and one hundred twenty of each. Its final cleanup returned those counts to zero. Those counts follow directly from the fixture's workload; they are not throughput or capacity claims about Node.
The lab also prints actual memory counters. Expect them to vary. Runtime warmup, allocation strategy, garbage collection, and the operating system affect the values. A useful reproduction first demonstrates the unwanted ownership growth. It does not require an exact byte threshold that happens to pass on one laptop.
The synthetic invoice includes a buffer so that both heap and external-memory behavior are visible. Node's Buffer reference documents buffers as byte sequences and their relationship to typed arrays. In real applications, investigate uploaded files, image transformations, and queued response bodies when heap-only measurements do not explain the overall footprint.
Keep the reproduction small enough to run repeatedly. You want room to inspect the state and test a fix, rather than a script that immediately exhausts the machine. Increase the number of cycles only after the expected resource behavior is clear.
Give every registration an explicit owner
The example module returns one disposal operation for the resources it creates. It keeps the listener function so it can remove that exact registration, clears the interval, and releases the invoice reference. Disposal is idempotent because normal completion and cancellation can both attempt cleanup.
export function startReminder(invoice, events, {
everyMs = 60_000,
onReminder = () => {}
} = {}) {
let current = invoice;
let disposed = false;
const notify = () => {
if (current) onReminder(current.id, current.payload.length);
};
const onChanged = id => {
if (id === current?.id) notify();
};
const timer = setInterval(notify, everyMs);
events.on('invoice.changed', onChanged);
return () => {
if (disposed) return;
disposed = true;
clearInterval(timer);
events.off('invoice.changed', onChanged);
current = null;
};
}Use the returned operation at the business boundary that actually ends the work. A subscription owner can call it when the subscription closes. A temporary operation can call it from finally. A process-wide worker needs an application shutdown path. Calling it immediately after creating a genuinely long-lived subscription would fix the counter while breaking the feature.
Releasing the payload reference matters if another component temporarily keeps the disposal handle. Removing registrations ends the scheduled work, but a retained handle can itself preserve a closure. Explicitly dropping large state reduces that accidental connection. Avoid storing disposed handles forever; their own collection still consumes memory.
The complete module adds a cancellation signal and an injectable scheduler for focused checks. The article's shorter version shows the same ownership decision without the test instrumentation. Neither version implements durable reminders or delivery guarantees; those belong to a persistent job design.
Handle listeners by identity and lifetime
According to the EventEmitter reference, listeners remain registered until removed, and exceeding the usual listener threshold produces a warning rather than preventing registration. Use --trace-warnings to investigate where repeated registrations originate.
Do not silence that warning by raising the maximum before understanding the expected fanout. A shared emitter legitimately serving many consumers may need a different threshold. A completed request leaving another listener behind needs cleanup. The warning cannot distinguish those designs for you.
Keep the callback reference used during registration. Creating a new anonymous function during removal will not identify the earlier callback. Remove only the listener you own; removeAllListeners() on a shared emitter can silently break other consumers.
The once() method helps when exactly one event will end a subscription, but it does not solve the case where the event never arrives. Design a timeout, cancellation, or owner shutdown path when that is possible. The companion tests preserve an unrelated listener while disposing the reminder, proving that cleanup respects the shared bus.
Distinguish cancellation from process liveness
Node's timer documentation defines unref() as changing whether a timer keeps the event loop alive. It does not cancel the timer or stop its callback from executing while other work keeps the process running. Use clearInterval() to end an interval.
The lab includes a real-timer test that calls unref(), keeps the process alive with another short timeout, and observes reminder callbacks. That directly demonstrates why replacing cleanup with unref() is ineffective in a running API server.
For cancellation, the full module accepts an AbortSignal and maps its abort event to the same disposal operation. A pre-aborted signal creates no registrations. Disposal also removes its own abort listener, so the cancellation mechanism does not become another forgotten subscription.
const controller = new AbortController();
const job = startReminder(invoice, events, {
signal: controller.signal
});
// When the owning operation ends:
controller.abort();
job.dispose(); // Safe if more than one shutdown path runs.An abort signal is a notification mechanism. Your implementation must connect it to the work that should stop. It cannot automatically clean up unrelated callbacks merely because they were created while the signal existed.
Use garbage collection to interpret a pattern
Normal allocation often creates a rising and falling heap pattern. A more useful question is whether comparable workload cycles leave an increasing amount of live data behind. Node's memory tuning guide explains how object lifetime and V8's heap organization affect collection.
In this controlled lab, --expose-gc allows a collection request before each sample. That makes comparisons easier to inspect, but calling the collector is not the application fix. A reachable invoice remains reachable regardless of how urgently you want its memory back.
For a closer look at collection behavior, run a small reproduction with --trace-gc, following Node's garbage-collection tracing guide. Read collection activity alongside completed-work counts. Do not turn verbose trace logging on indiscriminately across a busy service.
After disposal, RSS or external counters may stay elevated for a while. That does not invalidate a verified ownership fix, and a falling RSS value alone would not prove the absence of other leaks. Review repeated cycles, active resource counts, and retaining paths together.
Take snapshots where failure is tolerable
When counters and ownership checks narrow the problem, compare snapshots before and after repeated work. In DevTools, inspect objects that increased and follow their retainers toward the timer, emitter, collection, or application owner keeping them alive.
Node's heap snapshot guide warns that capturing a snapshot stops main-thread work and can require enough additional memory to crash the process. Prefer a disposable reproduction or an isolated instance that can fail without affecting availability. Do not start with the busiest instance already near its memory limit.
node --expose-gc memory-lab.mjs leaky --snapshotThe optional lab flag uses writeHeapSnapshot() to write local before-and-after files. The snapshot format and runtime details can vary, so record the Node version with the investigation. A JavaScript heap snapshot also does not account for every native allocation in the process.
Real snapshots can contain application data and secrets. Keep them private, restrict access, and remove them when the investigation ends. Do not expose a public HTTP route or inspector port to make capture convenient. Synthetic fixture data is enough for learning this workflow.
Use the same workload before and after the change. Verify the ownership invariant before interpreting byte totals.
Verify the fix against the feature
The tests exercise five behaviors: repeated completed work restores the resource baseline; omitted cleanup reproduces accumulation; disposal stops callbacks while preserving unrelated listeners; cancellation ends owned resources; and unreferencing does not cancel a timer. Those checks explain what changed in the application.
Add the feature's own acceptance checks too. A reminder service must still schedule the intended work, recover from its operational failures, and avoid duplicate delivery. A cleanup change that prevents every reminder is not a successful memory fix.
Roll out with the original workload context: completed operations, active subscriptions, timers or other application-owned resources, and the relevant memory counters. Compare similar traffic and allow the application to warm up. Keep a rollback plan if the new lifetime assumptions are wrong.
For the next review, make resource ownership visible in the code. The person creating a timer or subscription should be able to explain who ends it and when. That small design question often resolves the problem before a memory graph becomes an incident.




