Yaygın Sızıntı Kalıplarını Belirleme ve Giderme
Zamanla yığını büyüten sızıntılı kapanışları, sınırsız önbellekleri ve geride kalan dinleyicileri bulun.
Yaygın Sızıntı Kalıplarını Belirleme ve Giderme, CoddyKit'te ücretsiz bir Node.js Backend Development Bootcamp dersidir. Bu, 4 dersinin 4. dersidir. Aşağıdan dersin tamamını ücretsiz okuyabilir, sonra tarayıcıda yerleşik kod editörü ve 7/24 yapay zeka koçu ile uygulamalı olarak pratik yapabilirsin. Bu, Node.js Backend Development Bootcamp öğrenme yolunun bir parçasıdır ve ilerlemeniz web ve CoddyKit uygulaması arasında senkronize olur. Node.js Backend Development Bootcamp kursu toplamda 4 dersten oluşur.
Bu dersin bazı bölümleri henüz çevrilmemiş olup İngilizce olarak gösterilmektedir.
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.
Sıkça Sorulan Sorular
“Yaygın Sızıntı Kalıplarını Belirleme ve Giderme” dersi ücretsiz mi?
Evet — “Yaygın Sızıntı Kalıplarını Belirleme ve Giderme” dersin tüm metni burada web'de ücretsiz olarak okunabilir. Etkileşimli olarak pratik yapmak (yerleşik kod editörü ve 7/24 yapay zeka koçu) ve Node.js Backend Development Bootcamp kursunun geri kalanını açmak için CoddyKit PRO'ya yükselt. Node.js Backend Development Bootcamp kursu toplamda 4 dersten oluşur.
“Yaygın Sızıntı Kalıplarını Belirleme ve Giderme” dersinde ne öğreneceğim?
Zamanla yığını büyüten sızıntılı kapanışları, sınırsız önbellekleri ve geride kalan dinleyicileri bulun. Node.js Backend Development Bootcamp ile uygulamalı kodu tarayıcıda doğrudan çalıştırarak pratik yaparsın ve 7/24 yapay zeka koçu dersi çalışırken sorularını yanıtlar.
Node.js Backend Development Bootcamp öğrenmeye başlamak için deneyim gerekli mi?
Önceden deneyim gerekmez. CoddyKit'te Node.js Backend Development Bootcamp, başlangıçtan ileri seviyeye kadar yapılandırıldığı için buradan başlayabilir veya başından başlayıp kendi hızında ilerleme yapabilirsin. Bu, 4 dersinin 4. dersidir.
“Yaygın Sızıntı Kalıplarını Belirleme ve Giderme” dersi ne kadar sürer?
Çoğu CoddyKit dersi yaklaşık 5–10 dakika sürer. Her biri kısa ve etkileşimli olduğu için sabit ilerleme yaparsın ve web ile uygulama arasında tam olarak bıraktığın yerden devam edebilirsin.
Bu Node.js Backend Development Bootcamp dersinde kod yazıp çalıştırabilir miyim?
Evet. Her Node.js Backend Development Bootcamp dersi yerleşik bir kod editörü içerir, bu sayede tarayıcıda gerçek kod yazıp çalıştırabilir ve anlık yapay zeka geri bildirimi alırsın — yerel kurulum gerekli değildir.
Bu kursun tüm dersleri
- V8 Yığını, Nesilsel GC ve Nesne Ömürleri
- Yığın Anlık Görüntülerini Yakalama ve Karşılaştırma
- Sıcak Yollar için CPU Profilleme ve Alev Grafikleri
- Yaygın Sızıntı Kalıplarını Belirleme ve Giderme