• Home
  • Cloud VPS
    • Hong Kong VPS
    • US VPS
    • Japan VPS
  • Dedicated Servers
    • Hong Kong Servers
    • US Servers
    • Japan Servers
    • Singapore Servers
  • Company
    • Contact Us
    • Blog
logo logo
  • Home
  • Cloud VPS
    • Hong Kong VPS
    • US VPS
    • Japan VPS
  • Dedicated Servers
    • Hong Kong Servers
    • US Servers
    • Japan Servers
    • Singapore Servers
  • Company
    • Contact Us
    • Blog
ENEN
  • 简体简体
  • 繁體繁體
Client Area

Node.js Memory Optimisation on Hong Kong VPS: Prevent Memory Leaks (2026)

October 12, 2026

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 RAMNode.js heap limitmax_memory_restartWorkers
1 GB256 MB300 MB1
2 GB512 MB600 MB1–2
4 GB1024 MB1.2 GB2–4
8 GB2048 MB2.5 GB4–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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • NGINX Unit on Hong Kong VPS: Universal Application Server (2026)
  • CockroachDB on Hong Kong VPS: Distributed SQL for Asia-Pacific (2026)
  • Matrix and Element Chat Server on Hong Kong VPS: Self-Hosted Slack (2026)
  • MediaWiki on Hong Kong VPS: Self-Hosted Wiki for Asia-Pacific (2026)
  • Temporal Workflow Engine on Hong Kong VPS: Durable Code for Asia (2026)

Recent Comments

  1. Cheap Proxies on Php.ini Configuration: session.sid_length
  2. full88vnz on Laravel Octane on Hong Kong VPS: 10x Faster PHP with Swoole (2026)
  3. airport transfer dubai airport to hotel on How to Set Up a WordPress Site on a Hong Kong VPS with aaPanel (Step-by-Step 2026)
  4. Alejandra768 on VPS Backup Strategy for Hong Kong: Restic, B2, and Encryption (2026)
  5. Valerie4779 on CockroachDB on Hong Kong VPS: Distributed SQL for Asia-Pacific (2026)

Knowledge Base

Access detailed guides, tutorials, and resources.

Live Chat

Get instant help 24/7 from our support team.

Submit Sales Ticket

Get custom quotes or bulk pricing from our sales team.

logo
Alipay Cc-paypal Cc-stripe Cc-visa Cc-mastercard Bitcoin
Cloud VPS
  • Hong Kong VPS
  • US VPS
  • Japan VPS
Dedicated Servers
  • Hong Kong Servers
  • US Servers
  • Japan Servers
  • Singapore Servers
More
  • Contact Us
  • Blog
  • Legal
© 2026 Server.HK | Hosting Limited, Hong Kong | Company Registration No. 77008912
Telegram
Telegram @ServerHKBot