Node.js Code Challenges & Debugging Lab - Finding & Fixing Production Bugs

Real-world engineering is 20% writing new code and 80% reading, debugging, and optimizing existing systems. In this interactive lab, you will analyze broken code snippets representing real production defects and learn how to fix them.

Challenge 1: The Hanging Request Bug

Symptom: Clients send a GET request to /api/user, but the browser loader spins indefinitely until a 504 Gateway Timeout occurs.

// BROKEN CODE:
app.get('/api/user', async (req, res, next) => {
  try {
    const user = await User.findById(req.query.id);
    if (!user) {
      res.status(404); // BUG: Forgot .json() or .send()! Connection hangs!
      return;
    }
    res.json(user);
  } catch (err) {
    // BUG: Caught error but forgot to call next(err) or send a 500!
  }
});

// CORRECTED FIX:
app.get('/api/user', async (req, res, next) => {
  try {
    const user = await User.findById(req.query.id);
    if (!user) {
      return res.status(404).json({ error: 'User not found' }); // Fixed!
    }
    res.status(200).json(user);
  } catch (err) {
    next(err); // Fixed: Forward error to global error handler!
  }
});

Challenge 2: The Event Loop Starvation Bug

Symptom: Whenever one user triggers an export, all other users' web requests are completely blocked for 15 seconds.

// BROKEN CODE:
app.get('/api/export-data', (req, res) => {
  // Synchronous JSON parsing of a 400MB string on the main thread!
  const hugeData = fs.readFileSync('huge-dataset.json', 'utf8'); // Blocks!
  const parsed = JSON.parse(hugeData);                           // Blocks!
  res.json({ count: parsed.length });
});

// CORRECTED FIX: Use Streams or Worker Threads!
const { Worker } = require('worker_threads');

app.get('/api/export-data', (req, res, next) => {
  const worker = new Worker('./workers/parseWorker.js', {
    workerData: { filePath: 'huge-dataset.json' }
  });

  worker.on('message', (data) => res.json(data));
  worker.on('error', next);
});

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. What is the most effective way to debug a freezing Node.js server?

Start the process with 'node --inspect server.js' and open Chrome DevTools (chrome://inspect). Take a CPU profile to identify functions consuming 100% CPU time, and inspect the performance tab to detect blocking synchronous loops or excessive regular expressions.

Explore Related Node.js Tutorials & Next Steps

Boost your server-side JavaScript proficiency by studying these closely connected core modules:

Performance Profiling

Tools to diagnose memory leaks and event loop lag.

Error Handling Best Practices

Best practices for writing bug-free code.

50+ Practice Programs

Reference working code implementations.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!