Skip to content
jshacks.dev
Node.js

Run a background worker with a job queue

Run background jobs in-process in Node.js 24 with a small queue that limits concurrency and retries failures, and see where in-memory stops being enough.

2 min read
Summarize in AI

Sending a welcome email should not hold up the signup response. For one process, a small in-memory queue with a concurrency limit and retries is enough to move that work off the request path.

queue.mjsJavaScript
function createQueue({ concurrency = 2, retries = 2 } = {}) {
  const waiting = [];
  let running = 0;
  const next = () => {
    if (running >= concurrency || waiting.length === 0) return;
    const job = waiting.shift();
    running++;
    job.fn()
      .catch((err) => {
        if (job.attempt++ < retries) waiting.push(job);
        else console.log(`gave up on ${job.name}: ${err.message}`);
      })
      .finally(() => { running--; next(); });
    next();
  };
  return { add: (name, fn) => { waiting.push({ name, fn, attempt: 0 }); next(); } };
}

const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const queue = createQueue();
queue.add('email', async () => { await sleep(30); console.log('email sent'); });
queue.add('thumbnail', async () => { await sleep(10); console.log('thumbnail done'); });
queue.add('webhook', async () => { throw new Error('503 from partner'); });
Text
thumbnail done
gave up on webhook: 503 from partner
email sent

next starts jobs until concurrency are running and is called again whenever one settles, so there are never more than two in flight. A failed job goes to the back of the line until it has used its retries. The webhook waits for a free slot, which opens when the thumbnail finishes after 10 ms, and then uses all three attempts before the 30 ms email is done, because each attempt rejects at once. See Promise.prototype.finally.

Everything here lives in memory, so a crash or a deploy loses every queued job. Retries also fire immediately; real failures want a delay with backoff. Once losing a job matters, or several processes share the work, move to a queue backed by Redis or a database, such as BullMQ.

Taggednode 24
Share

More snippets

Node.js

Read a text file with fs promises

Read a text file with fs promises in Node.js: await readFile with an encoding, and catch the error code when the file is missing. Node.js 24.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.