Memory

Leak Detection

Detect common Node.js memory leaks in AxilJS — listener build-up, tracked timers, cache overflow and global pollution — with automatic cache pruning.

2 min readUpdated DocumentationEdit this page
On this page4

What is detected

detectAndFix(autoFix = true) runs these checks (the MemoryMonitor calls it on every scan):

CheckReported asAuto fix
Tracked emitter has more listeners than its getMaxListeners()event-listenerWarns
More than 3 listeners on a process event (uncaughtException, unhandledRejection, exit, SIGINT, SIGTERM)event-listenerWarns
More than 100 tracked timers / 50 tracked intervals still activetimer / intervalWarns
Tracked cache larger than its maxSizecache-overflowPrunes oldest entries
Large unknown values on globallarge-stringWarns

Note

Only resources you register with the track* helpers are inspected. High heap usage is handled by the monitor (GC plus the optimizer on critical), and module-cache clearing is an opt-in optimizer step, not part of leak detection.

Track resources

TypeScript
TS
1import { trackTimer, trackInterval, trackCache, trackEmitter, untrackTimer } from '@axiljs/memory'
2
3const timer = trackTimer(setTimeout(work, 5000))
4const tick  = trackInterval(setInterval(poll, 1000))
5const cache = trackCache('sessions', new Map(), 10000)   // maxSize defaults to 10000
6trackEmitter(bus, 'EventBus')
7
8clearTimeout(timer)
9untrackTimer(timer)

Run a scan manually

TypeScript
TS
import { detectAndFix } from '@axiljs/memory'

const leaks = await detectAndFix(true)   // pass false to report without pruning

Per-request

TypeScript
TS
import { memoryMiddleware } from '@axiljs/memory'

app.use(memoryMiddleware({ leakThresholdMb: 50, exposeHeader: true, logFlagged: true }))
OptionDefaultDescription
leakThresholdMb50Log requests whose heap delta exceeds this many MB
exposeHeaderfalseAdd X-Memory-Usage (and X-Memory-Delta when positive) response headers
logFlaggedtrueLog flagged requests to the console

Was this page helpful?

Help improve the documentation

AxilJS is open source and documentation improvements are welcome.

AxilJS DocumentationMIT License · Built by SyntaxilitY