一般的なリークパターンの検出と修正
時間とともにヒープを増大させるリークしたクロージャ、無制限のキャッシュ、残存するリスナーを追跡して修正します。
「一般的なリークパターンの検出と修正」はCoddyKit上の無料Node.js Backend Development Bootcampレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはNode.js Backend Development Bootcamp学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Node.js Backend Development Bootcampコースには全4レッスンが含まれています。
このレッスンの一部はまだ翻訳されておらず、英語で表示されています。
What a Real Leak Looks Like
A memory leak in Node.js is not when memory goes up — it is when memory goes up and never comes back down across GC cycles. The V8 heap grows, old-space stays retained, and eventually you hit the default --max-old-space-size ceiling and the process is OOM-killed.
- Normal: heap saws up and down as GC reclaims short-lived objects.
- Leak: the saw-tooth baseline trends upward over hours, even at steady traffic.
In this lesson we hunt the three classic backend offenders: leaking closures, unbounded caches, and lingering event listeners.
Reading the Heap with process.memoryUsage()
Your first cheap signal is process.memoryUsage(). Watch heapUsed over time. If it climbs monotonically under constant load, you have a retention problem.
The snippet below simulates a leak by pushing into a module-level array and logs heap growth every interval — a standalone reproduction you can run.
const leaky = [];
function tick(i) {
// Each call retains a 10k-element array forever.
leaky.push(new Array(10_000).fill(i));
const { heapUsed } = process.memoryUsage();
console.log(`tick ${i}: heapUsed=${(heapUsed / 1024 / 1024).toFixed(1)} MB, retained=${leaky.length}`);
}
for (let i = 1; i <= 5; i++) tick(i);
console.log('Heap keeps growing because `leaky` is never cleared.');Leak Pattern 1: The Capturing Closure
A closure keeps alive everything in its scope chain, even variables it does not use, as long as something holds a reference to the closure. Store such closures in a long-lived structure and you pin large objects forever.
Below, every registered handler closes over a multi-megabyte bigData buffer. The handlers live in a module array, so the buffers can never be collected.
const handlers = [];
function register(id) {
const bigData = Buffer.alloc(1024 * 1024); // 1 MB per registration
// The closure captures bigData even though it only logs id.
handlers.push(() => console.log(`handler ${id} fired`));
return bigData.length;
}
for (let i = 0; i < 3; i++) register(i);
console.log(`${handlers.length} handlers retained; each closure may pin its scope.`);Fixing the Closure Leak
Two fixes:
- Do not capture what you do not need. Pull the needed primitive out before creating the closure so the large object falls out of the closure's scope.
- Do not store closures in long-lived containers unless you also remove them.
Here the closure captures only the small id primitive; bigData is used and discarded, so GC frees it after register returns.
const handlers = [];
function register(id) {
const bigData = Buffer.alloc(1024 * 1024);
const summary = bigData.length; // use it now
// Closure captures only `id` and `summary` (primitives) — bigData is free to GC.
handlers.push(() => console.log(`handler ${id}: ${summary} bytes processed`));
}
register(1);
handlers[0]();
console.log('bigData is no longer reachable and will be collected.');Leak Pattern 2: The Unbounded Cache
The single most common Node leak: a Map or plain object used as an in-memory cache that only ever grows. Every unique key (user id, request hash, session token) adds an entry and nothing evicts it.
This looks innocent in code review but leaks linearly with traffic.
const cache = new Map();
function getUser(id) {
if (!cache.has(id)) {
cache.set(id, { id, profile: Buffer.alloc(50_000) }); // 50 KB each, never evicted
}
return cache.get(id);
}
for (let id = 0; id < 4; id++) getUser(id);
console.log(`cache size=${cache.size} — grows forever with unique ids.`);Fixing the Cache: Bounded LRU + TTL
An in-memory cache MUST have a bound. Use a battle-tested LRU (lru-cache) with max entries and a ttl, or implement a simple capacity-evicting Map. Insertion order in JS Maps makes a basic LRU trivial: delete-then-set bumps recency, and evict the oldest key when over capacity.
class LRU {
constructor(max) { this.max = max; this.map = new Map(); }
get(key) {
if (!this.map.has(key)) return undefined;
const v = this.map.get(key);
this.map.delete(key); this.map.set(key, v); // mark most-recent
return v;
}
set(key, val) {
if (this.map.has(key)) this.map.delete(key);
this.map.set(key, val);
if (this.map.size > this.max) this.map.delete(this.map.keys().next().value); // evict oldest
}
}
const cache = new LRU(2);
cache.set('a', 1); cache.set('b', 2); cache.set('c', 3); // 'a' evicted
console.log('keys:', [...cache.map.keys()]); // [ 'b', 'c' ]Leak Pattern 3: Lingering Event Listeners
Every emitter.on(...) stores a reference. If you attach in a hot path (per request, per socket, per timer) and never call removeListener/off, the emitter's listener array grows without bound — and each listener may close over request-scoped data.
Node warns you: MaxListenersExceededWarning once an emitter passes 10 listeners. Treat that warning as a leak alarm, not noise.
const { EventEmitter } = require('events');
const bus = new EventEmitter();
function handleRequest(reqId) {
// BUG: a new listener every request, never removed.
bus.on('shutdown', () => console.log(`drain req ${reqId}`));
}
for (let i = 0; i < 12; i++) handleRequest(i);
console.log('listenerCount(shutdown):', bus.listenerCount('shutdown'));Fixing Listeners: once, off, and AbortSignal
Match every on with an off, or avoid the accumulation entirely:
- Use
emitter.once(...)when the handler should fire a single time. - Keep the function reference so you can call
emitter.off(event, fn)on cleanup. - Modern APIs accept an
AbortSignal— abort the controller and all bound listeners are removed in one shot.
const { EventEmitter } = require('events');
const bus = new EventEmitter();
function handleRequest(reqId) {
const controller = new AbortController();
bus.on('shutdown', () => console.log(`drain req ${reqId}`), { signal: controller.signal });
// When the request finishes, abort once — listener auto-removed.
return () => controller.abort();
}
const cleanups = [];
for (let i = 0; i < 12; i++) cleanups.push(handleRequest(i));
cleanups.forEach((done) => done());
console.log('after cleanup, listenerCount:', bus.listenerCount('shutdown')); // 0Timers and Streams: The Hidden Retainers
Two retainers people forget:
- setInterval keeps its callback (and its closure) alive until
clearInterval. A per-connection interval that is never cleared leaks the whole connection scope. - Unconsumed streams and un-destroyed sockets buffer data in memory. Always
stream.destroy()on error and handle backpressure.
timer.unref() lets the process exit but does NOT free the callback — you still must clear it to stop retention.
function startWorker(job) {
const buf = Buffer.alloc(500_000); // retained by the interval closure
const t = setInterval(() => {
if (job.done) {
clearInterval(t); // releases the closure -> buf can be collected
console.log('worker stopped, scope released');
}
}, 10);
return t;
}
const job = { done: false };
startWorker(job);
setTimeout(() => { job.done = true; }, 30);WeakMap and WeakRef: Caches That Let Go
When a cache key is an object whose lifetime you do not control, use a WeakMap. Its entries do not prevent the key from being garbage-collected, so associated data disappears automatically when the key dies — no eviction policy needed.
Use WeakRef + FinalizationRegistry for advanced caches that hold values weakly. Note: you cannot iterate a WeakMap and it only accepts object keys, so it is unsuitable for primitive keys like string ids.
const meta = new WeakMap();
function attachMeta(obj) {
meta.set(obj, { seen: Date.now() });
}
let session = { id: 'abc' };
attachMeta(session);
console.log('has meta:', meta.has(session)); // true
// Once `session` is unreachable, its WeakMap entry is collected automatically.
session = null;
console.log('session dropped; WeakMap entry becomes eligible for GC.');Confirming a Leak: Heap Snapshots
Memory counters tell you THAT you leak; heap snapshots tell you WHAT leaks. Workflow:
- Start the process with
node --inspectand openchrome://inspect, OR callrequire('v8').writeHeapSnapshot()from code. - Take snapshot A, exercise the endpoint N times, take snapshot B.
- Use the Comparison view and sort by Delta. Objects whose count grows by exactly N are your leak.
- Inspect Retainers to see which root (a Map, a closure, a listener array) holds them.
For automated detection in CI, node --heapsnapshot-near-heap-limit=2 dumps a snapshot right before OOM.
const v8 = require('v8');
const fs = require('fs');
const file = v8.writeHeapSnapshot();
console.log('wrote heap snapshot:', file);
console.log('size bytes:', fs.statSync(file).size);
console.log('Load this .heapsnapshot in Chrome DevTools > Memory > Load.');Quick Check: Choosing the Right Cache
You add an in-memory cache keyed by string user id in a long-running API. Traffic is unbounded and you must guarantee memory stays bounded. Which approach is correct?
Recap: A Leak-Hunting Checklist
You can now find and fix the three dominant Node.js heap leaks:
- Closures: capture only the primitives you need; never park closures in module-level arrays without removal.
- Caches: every in-memory cache needs a bound — LRU
max+ttl, or aWeakMapwhen keys are objects you do not own. - Listeners & timers: pair every
onwithoff(or useonce/AbortSignal), andclearIntervalevery timer; treatMaxListenersExceededWarningas an alarm.
Workflow: watch heapUsed for a rising baseline, then take comparison heap snapshots and follow the retainer chain to the root. Measure, do not guess.
よくある質問
「一般的なリークパターンの検出と修正」レッスンは無料ですか?
はい。「一般的なリークパターンの検出と修正」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Node.js Backend Development Bootcampコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Node.js Backend Development Bootcampコースには全4レッスンが含まれています。
「一般的なリークパターンの検出と修正」で何を学びますか?
時間とともにヒープを増大させるリークしたクロージャ、無制限のキャッシュ、残存するリスナーを追跡して修正します。 ブラウザで直接実行するハンズオンコードでNode.js Backend Development Bootcampを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
Node.js Backend Development Bootcampを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのNode.js Backend Development Bootcampは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン4/4です。
「一般的なリークパターンの検出と修正」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このNode.js Backend Development Bootcampレッスンでコードを書いて実行できますか?
はい。すべてのNode.js Backend Development Bootcampレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。