Node.js & Memory

Code Review: Node.js Memory Leak

hardCode ReviewJS / TS

Problem Statement

Review the following WebSocket stream manager and query cache. Identify why process memory grows continuously over time, locate uncleaned event listeners/timers, and propose a leak-free implementation.

Code under review

JAVASCRIPT• handler.js
const EventEmitter = require('events');
const globalBus = new EventEmitter();

const queryCache = {};

function handleClientConnection(socket, req) {
  const userId = req.headers['x-user-id'];

  globalBus.on('system_broadcast', (msg) => {
    socket.send(JSON.stringify({ type: 'broadcast', data: msg }));
  });

  socket.on('query', async (queryStr) => {
    if (!queryCache[queryStr]) {
      queryCache[queryStr] = await runHeavyQuery(queryStr);
    }
    socket.send(JSON.stringify(queryCache[queryStr]));
  });

  setInterval(() => {
    socket.send(JSON.stringify({ ping: Date.now() }));
  }, 5000);
}

Read only. Write down what you would flag below, then compare with the reference notes.

JavaScript & TypeScript versions included
Run this as a live interview

Practice solo

Write down what you would flag in this code, then compare it with the reference notes.

Write your findings first, then check yourself against the notes.

Get new interview exercises

Practice problems and review drills, sent when we publish new ones. No spam.

Unsubscribe anytime. We never share your address.