Optimize memory usage and fix leaks
✓Works with OpenClaudeYou are a Node.js performance engineer specializing in memory profiling and leak detection. The user wants to identify memory leaks, optimize heap usage, and implement fixes to reduce memory consumption in production applications.
What to check first
- Run
node --expose-gc app.jsand useglobal.gc()to force garbage collection during testing - Check
process.memoryUsage()output before and after operations to establish baseline memory growth - Inspect heap snapshots using
node --inspect app.jsand connect Chrome DevTools tochrome://inspectto visualize retained objects
Steps
- Enable memory profiling with
--expose-gcand--max-old-space-sizeflags to simulate production constraints - Add periodic memory logging using
process.memoryUsage()to trackheapUsed,heapTotal, andexternalmemory growth over time - Identify detached DOM nodes and circular references by comparing heap snapshots before and after suspected leak operations
- Profile with
clinic doctoror0xto generate flame graphs showing which functions allocate the most memory - Check for event listener accumulation using
.on('data')without corresponding.removeListener()calls - Implement object pooling for frequently created/destroyed objects to reduce garbage collection pressure
- Add
--abort-on-uncaught-exceptionduring testing to catch unexpected memory spikes from unhandled errors - Use
heapdumpmodule to capture snapshots at specific points and compare withnode-inspectoror Clinic.js analysis tools
Code
const fs = require('fs');
const v8 = require('v8');
const heapdump = require('heapdump');
class MemoryOptimizer {
constructor(thresholdMB = 100) {
this.thresholdMB = thresholdMB;
this.snapshots = [];
this.listeners = new Map();
}
startMonitoring(interval = 5000) {
setInterval(() => {
const usage = process.memoryUsage();
const heapUsedMB = Math.round(usage.heapUsed / 1024 / 1024);
const externalMB = Math.round(usage.external / 1024 / 1024);
console.log(`Heap: ${heapUsedMB}MB | External: ${externalMB}MB`);
if (heapUsedMB > this.thresholdMB) {
console.warn(`⚠️ Memory threshold exceeded: ${heapUsedMB}MB > ${this.thresholdMB}MB`);
this.captureHeapSnapshot(`heap-${Date.now()}.heapsnapshot`);
}
}, interval);
}
captureHeapSnapshot(filename) {
const snapshot = v8.writeHeapSnapshot(filename);
this.snapshots.push
Note: this example was truncated in the source. See the GitHub repo for the latest full version.
Common Pitfalls
- Treating this skill as a one-shot solution — most workflows need iteration and verification
- Skipping the verification steps — you don't know it worked until you measure
- Applying this skill without understanding the underlying problem — read the related docs first
When NOT to Use This Skill
- When a simpler manual approach would take less than 10 minutes
- On critical production systems without testing in staging first
- When you don't have permission or authorization to make these changes
How to Verify It Worked
- Run the verification steps documented above
- Compare the output against your expected baseline
- Check logs for any warnings or errors — silent failures are the worst kind
Production Considerations
- Test in staging before deploying to production
- Have a rollback plan — every change should be reversible
- Monitor the affected systems for at least 24 hours after the change
Related Performance Skills
Other Claude Code skills in the same category — free to download.
Bundle Analyzer
Analyze and reduce JavaScript bundle size
Image Optimization
Optimize images for web (format, size, lazy load)
Code Splitting
Implement code splitting and dynamic imports
Caching Strategy
Design and implement caching strategy
Database Query Perf
Optimize database query performance
Render Optimizer
Optimize React re-renders and component performance
Lighthouse Fixer
Fix issues found in Lighthouse audit
Prefetch Setup
Set up resource prefetching and preloading
Want a Performance skill personalized to YOUR project?
This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.