memtracker
v1.0.0
Published
A lightweight Node.js module for tracking memory usage of in-process data structures, with system resource monitoring and adaptive pressure detection.
Readme
memTracker
A lightweight Node.js module for tracking memory usage of in-process data structures, with system resource monitoring and adaptive pressure detection.
Features
- Track any data structure - Register Maps, Sets, Arrays, Objects and get periodic reports on their type, count and estimated memory size.
- System monitoring - Polls CPU usage, load average, memory and uptime at a configurable interval.
- Adaptive pressure detection - Computes a pressure score from CPU and memory usage, with hysteresis-based level transitions (LOW / NORMAL / HIGH / CRITICAL) to avoid flapping.
- Pressure callbacks - Get notified when the system pressure level changes.
- File reports - Optionally save JSON reports to disk, with rotation support.
- Non-blocking - All timers use
.unref()so the tracker never prevents your process from exiting.
Requirements
Node.js >= 14.0.0
Installation
npm install memtrackerQuick start
const MemTracker = require('memtracker');
const tracker = new MemTracker({
reportInterval: 30000,
logLevels: ['HIGH', 'CRITICAL'],
log: { status: 'prettyJson' },
autoStart: true
});
// Register data structures to track
const myCache = new Map();
tracker.register('myCache', () => myCache);
// Later, stop everything
tracker.stop();API
new MemTracker(options?)
Creates a new tracker instance. Nothing starts until you call start(), unless autoStart is set to true.
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| reportInterval | number | 60000 | How often (ms) to generate a memory report. |
| logLevels | string[] | ['HIGH', 'CRITICAL'] | Pressure levels at which the heap summary line is logged to console. |
| log.status | string | — | Console output format: 'table', 'json' or 'prettyJson'. Omit to disable console output of the entries table. |
| log.path | string | — | Directory path to save JSON report files. Omit to disable file output. |
| log.rotate.enabled | boolean | false | Enable report file rotation. |
| log.rotate.keep | number | 10 | Number of rotated report files to keep. |
| autoStart | boolean | false | Start tracking immediately on construction (no need to call start()). |
| system.pollInterval | number | 5000 | How often (ms) to poll CPU, memory and uptime. |
| system.logPressureChanges | boolean | false | Log pressure level transitions to the console. |
tracker.start()
Starts the system monitor and the periodic report interval.
tracker.stop()
Stops all timers (report interval and system polling).
tracker.register(name, getter)
Register a named data structure to track.
name— A string identifier for the entry.getter— A function that returns the value to measure. Called on each report cycle.
tracker.register('sessions', () => sessionStore);
tracker.register('requestQueue', () => queue);tracker.unregister(name)
Remove a previously registered entry by name.
tracker.report()
Manually trigger a report (normally called automatically by the interval).
tracker.onPressureChange(callback)
Register a callback that fires when the system pressure level changes.
tracker.onPressureChange((level, score) => {
console.log(`Pressure is now ${level} (score: ${score})`);
if (level === 'CRITICAL') {
// shed load, clear caches, etc.
}
});tracker.systemInfo
Read-only property returning the current system snapshot:
{
cpu: { usage: 42.5, loadAvg: [1.2, 0.8, 0.6] },
memory: { free: 4000000000, freePct: 0.25, total: 16000000000, used: 12000000000, usedPct: 75.0 },
pressure: { score: 55.1, level: 'NORMAL', prevLevel: 'LOW', levelSince: 1700000000000 },
uptime: 3600
}Pressure levels
The pressure score is a weighted average of CPU usage (60%) and memory usage (40%), smoothed over a 2-minute sliding window. Level transitions use hysteresis thresholds to prevent rapid flapping:
| Level | Transitions up | Transitions down | |-------|---------------|-----------------| | LOW | NORMAL >= 25, HIGH >= 60, CRITICAL >= 85 | — | | NORMAL | HIGH >= 60, CRITICAL >= 85 | LOW < 20 | | HIGH | CRITICAL >= 85 | LOW < 20, NORMAL < 50 | | CRITICAL | — | NORMAL < 50, HIGH < 75 |
Full example
const MemTracker = require('memtracker');
const tracker = new MemTracker({
reportInterval: 30000,
logLevels: ['HIGH', 'CRITICAL'],
log: {
status: 'prettyJson',
path: './logs/',
rotate: { enabled: true, keep: 5 }
},
system: {
pollInterval: 5000,
logPressureChanges: true
}
});
const users = new Map();
const eventQueue = [];
tracker.register('users', () => users);
tracker.register('eventQueue', () => eventQueue);
tracker.onPressureChange((level, score) => {
if (level === 'CRITICAL') {
eventQueue.length = 0; // emergency flush
}
});
tracker.start();
// On graceful shutdown
process.on('SIGTERM', () => {
tracker.stop();
process.exit(0);
});License
ISC
