Node.js › Background Jobs & Queues

What is a background job in the context of a Node.js web application, and why can't long-running work simply happen inside a request handler?

Beginner

Answer

A background job is a unit of work executed outside the request/response cycle -- sending emails, generating reports, processing images -- so the HTTP response can return to the user quickly. If long-running work happens directly inside a request handler, the user's connection stays open for the full duration (risking timeouts), and since Node.js runs on a single main thread, a CPU-heavy synchronous task inside that handler also blocks the event loop, delaying every other concurrent request being served by that same process.
// Bad: user waits for the entire report generation before getting a response
app.post('/reports', async (req, res) => {
  const report = await generateHugeReport(req.body); // could take minutes
  res.json(report);
});

// Better: enqueue the work and respond immediately
app.post('/reports', async (req, res) => {
  const jobId = await reportQueue.add('generate', req.body);
  res.status(202).json({ jobId, status: 'processing' });
});
Real-world example A photo-sharing app moves its image-thumbnail generation out of the upload request handler and into a background job queue, so users get an immediate 'upload successful' response while thumbnails are generated by separate worker processes a few seconds later.

Common follow-ups: How does the client find out when a background job has completed, given the response returns before the work is done?;What's the tradeoff between background jobs and simply scaling up the number of server instances handling requests?