Skip to main content
// half-baked code · #01
easy3-5 min58% solve rate1,567 attempts

The Event Listener Memory Leak

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

Node.jsMemory

The Code

This code passed code review and works in development. But it has a bug that will cause problems in production.

websocket.js
javascript
1const WebSocket = require('ws');
2const EventEmitter = require('events');
3
4const notifications = new EventEmitter();
5
6const wss = new WebSocket.Server({ port: 8080 });
7
8wss.on('connection', (ws) => {
9 console.log('Client connected');
10
11 // Listen for notifications
12 const handler = (data) => {
13 ws.send(JSON.stringify(data));
14 };
15
16 notifications.on('new-notification', handler);
17
18 ws.on('message', (message) => {
19 console.log('Received:', message);
20 });
21
22 ws.on('close', () => {
23 console.log('Client disconnected');
24 });
25});
26
27// This WebSocket server has a memory leak.
28// It will grow unbounded over time.
29// What's missing?
// need a hint?

Progressive Hints

0 of 3 revealed
Hint 1 locked
Hint 2 locked
Hint 3 locked
// ready for the answer?

Ready for the Solution?

Enter your email to get the full solution with explanation, the fix, and why this bug is so common.

No spam. Unsubscribe any time.