Closures in callbacks
Middleware and job queues often store callbacks. If each callback closes over a large request scope, memory accumulates.
Broken code
Section titled “Broken code”examples/node/03-closure-cache-leak.js:
const jobs = [];
setInterval(() => { const big = new Array(80_000).fill({ v: Math.random() }); jobs.push(() => big.length);}, 300);Fixed code
Section titled “Fixed code”examples/node/03-closure-cache-fixed.js — store only needed fields, bound job queue with max size.
Run it
Section titled “Run it”node examples/node/03-closure-cache-leak.jsnode examples/node/03-closure-cache-fixed.jsflowchart TD queue[jobs array] fn1[callback] fn2[callback] big1[big array] queue --> fn1 queue --> fn2 fn1 --> big1