Skip to main content
Menu
Challenges/The WebSocket That Won't Forget
// challenge_EV

The WebSocket That Won't Forget

This WebSocket handler looks clean but will slowly consume all your memory.

easyNode.jsMemory3-5 min
Attempts
1,567
Solved
58%
Avg time
7min
Published
2024-03-15
// the code

Here's what passed code review.

A standard pattern. Nothing in this code is obviously wrong. It works perfectly in dev. It works perfectly in staging. It even works in production — for a while.

websocket.jsjavascript
const WebSocket = require('ws');
const EventEmitter = require('events');

const notifications = new EventEmitter();

const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', (ws) => {
  console.log('Client connected');

  // Listen for notifications
  const handler = (data) => {
    ws.send(JSON.stringify(data));
  };

  notifications.on('new-notification', handler);

  ws.on('message', (message) => {
    console.log('Received:', message);
  });

  ws.on('close', () => {
    console.log('Client disconnected');
  });
});

// This WebSocket server has a memory leak.
// It will grow unbounded over time.
// What's missing?
// stuck? progressive hints

Reveal hints one at a time.

Each hint nudges you closer without giving it away. Use as many as you need.

hint_01Start here →+
What happens when a client disconnects?
hint_02Need another nudge?+
The event listener is added but never removed.
hint_03Need another nudge?+
After many connections, how many listeners exist?
// submit your guess
// solution lands in your inbox

Want more code challenges? Subscribe.

New challenge every two weeks. Production bugs that passed review. ~5 min reads.