Course contentsShow
← JavaScript
Lesson 1882 of 2,72339. Memory Management and GCFree lesson

Server-Side Memory Leaks in Node.js

Identifying long-lived references in servers: request handlers, middleware state, and connection pools.

Server-Side Memory Leaks in Node.js

You'll learn how long-lived server processes in Node.js create unique memory leak risks that don't exist in short-lived browser sessions.

Why Servers Are Different

In the browser, when a user closes a tab or navigates away, the entire JavaScript environment is destroyed. Any memory leaks die with it. Node.js servers run continuously for days, weeks, or months, so even tiny leaks compound into catastrophic memory growth.

Common Long-Lived Reference Traps

Request Handler State

Every incoming HTTP request creates a closure. If you accidentally store request-specific data in module-level variables or closures that outlive the request, you've created a leak:

// BAD: Module-level array grows forever
const requestLog = [];

app.get('/users', (req, res) => {
  requestLog.push({ timestamp: Date.now(), url: req.url }); // Leak!
  // ... handle request
});

Each request adds to requestLog, but nothing removes old entries. After 100,000 requests, you're holding 100,000 objects unnecessarily.

Middleware State

Middleware that attaches data to req or res objects usually cleans up automatically when the response ends. But custom caching or session stores that use plain Maps or Objects without expiration policies grow unbounded.

Connection Pools

Database connection pools, Redis clients, and WebSocket connections are intentionally long-lived. If you create new pools per request instead of reusing a singleton, or if connection event listeners pile up without cleanup, memory balloons.

Key Takeaway: In Node.js servers, any data structure that persists beyond individual requests—cached results, global registries, connection pools—must have explicit size limits, expiration logic, or use WeakMap/WeakSet to avoid leaking memory over time.