A Node.js process that slowly grows in memory until the VPS OOM-killer terminates it is one of the most common production issues. On a Hong Kong VPS with fixed RAM, a memory leak that might be tolerable on an auto-scaling cloud cluster instead brings down your entire application. This guide covers heap tuning, leak detection, and production memory monitoring for Node.js.
Step 1: Set Appropriate Heap Limits
<code"># By default, Node.js sets heap to ~1.5 GB on 64-bit systems
# On a 2 GB VPS running Node + PG + Redis, this is too generous
# In ecosystem.config.cjs (PM2):
module.exports = {
apps: [{
name: 'api',
script: 'dist/index.js',
node_args: '--max-old-space-size=512', // 512 MB heap limit
instances: 2,
exec_mode: 'cluster',
max_memory_restart: '600M', // PM2 restarts if process exceeds 600 MB
}]
}
# Rule of thumb: max-old-space-size = (Available RAM - OS - DB - Redis) / workers
# 4 GB VPS: (4096 - 512 OS - 512 PG - 256 Redis) / 2 workers = ~1280 MB / 2 ≈ 640 MB
Step 2: Detect Memory Leaks with Clinic.js
<code"># npm install -g clinic autocannon # Run a heap profile under load clinic heapprofiler -- node dist/index.js & APP_PID=$! # Apply load autocannon -c 100 -d 60 http://localhost:3000/api/products # Stop and view report kill $APP_PID clinic heapprofiler --open # Common leak patterns to look for in the report: # - Growing arrays/maps that are never cleared (event listeners, caches without TTL) # - Closures holding large objects longer than needed # - Buffers not released (image processing, file reads)
Step 3: Common Node.js Memory Leaks
<code"># LEAK 1: Event listeners not removed
const EventEmitter = require('events')
const emitter = new EventEmitter()
// BAD — adds a listener on every request, never removed:
app.get('/data', (req, res) => {
emitter.on('data', (data) => res.json(data)) // LEAK
})
// GOOD — use once() or remove listener after use:
app.get('/data', (req, res) => {
emitter.once('data', (data) => res.json(data)) // Auto-removes after fire
})
# LEAK 2: Cache without size limit
const cache = new Map()
// BAD — grows forever:
function getUser(id) {
if (!cache.has(id)) cache.set(id, fetchUser(id))
return cache.get(id)
}
// GOOD — use lru-cache with max size:
const LRU = require('lru-cache')
const cache = new LRU({ max: 500, ttl: 300_000 })
# LEAK 3: Global variable accumulation
let requests = [] // BAD if you push to this but never clear
// GOOD — limit size:
if (requests.length > 1000) requests = requests.slice(-500)
Step 4: Memory Monitoring in Production
<code"># Expose memory metrics via an endpoint
app.get('/metrics/memory', (req, res) => {
const mem = process.memoryUsage()
res.json({
rss_mb: Math.round(mem.rss / 1024 / 1024),
heap_used_mb: Math.round(mem.heapUsed / 1024 / 1024),
heap_total_mb: Math.round(mem.heapTotal / 1024 / 1024),
external_mb: Math.round(mem.external / 1024 / 1024),
heap_pct: Math.round(mem.heapUsed / mem.heapTotal * 100),
})
})
# Alert when heap exceeds 80%
setInterval(() => {
const { heapUsed, heapTotal } = process.memoryUsage()
const pct = heapUsed / heapTotal * 100
if (pct > 80) {
console.error(`HEAP WARNING: ${pct.toFixed(1)}% used`)
// Send alert to your monitoring system
}
}, 30_000)
Step 5: Heap Snapshot for Deeper Analysis
<code"># Take a heap snapshot when memory is high (no restart needed)
const v8 = require('v8')
const fs = require('fs')
// Trigger via HTTP endpoint (protect with admin auth)
app.get('/admin/heapdump', adminAuth, (req, res) => {
const filename = `/tmp/heap-${Date.now()}.heapsnapshot`
const snapshot = v8.writeHeapSnapshot(filename)
res.json({ snapshot })
})
# Transfer and analyse in Chrome DevTools:
scp root@VPS_IP:/tmp/heap-*.heapsnapshot ./
# Chrome → DevTools → Memory → Load profile → open .heapsnapshot
# Sort by "Retained Size" to find largest object trees
Step 6: Global GC Tuning
<code"># Force more aggressive garbage collection (at slight CPU cost):
node --max-old-space-size=512 \
--gc-interval=100 \ # GC every 100 allocations (default: 1000)
dist/index.js
# Expose GC metrics:
node --expose-gc dist/index.js
# Then in code: global.gc() forces a GC cycle (useful in tests)
# Use PM2 with memory monitoring:
pm2 start ecosystem.config.cjs
pm2 monit # Real-time memory per process
Memory Targets by VPS Size
| VPS RAM | Node.js heap limit | max_memory_restart | Workers |
|---|---|---|---|
| 1 GB | 256 MB | 300 MB | 1 |
| 2 GB | 512 MB | 600 MB | 1–2 |
| 4 GB | 1024 MB | 1.2 GB | 2–4 |
| 8 GB | 2048 MB | 2.5 GB | 4–8 |
Conclusion
Node.js memory management on a Hong Kong VPS requires explicit heap limits, LRU caches instead of unbounded Maps, and diligent event listener cleanup. Set --max-old-space-size and PM2’s max_memory_restart to act as a safety net — a well-configured process restarts quickly rather than slowly consuming all VPS RAM until the OOM-killer terminates it catastrophically. Heap profiling with Clinic.js surfaces the root cause of leaks; fixing them at the source is the sustainable solution.
Run Node.js efficiently: Browse Server.HK Hong Kong VPS plans — a 2–4 GB plan handles optimised Node.js with PM2, PostgreSQL, and Redis for most production applications.