Background Jobs

Run work outside the normal request/response cycle, so users don't wait for slow tasks to finish.

What is it?

Some work doesn't fit in the short window of a single request. Sending a confirmation email, resizing an image, generating a large report, or a nightly cleanup can take seconds, minutes, or longer. That's far too long for a user to stare at a spinner.

Background jobs run outside the normal request/response cycle. The server quickly acknowledges the request and hands the slow work off to run separately:

  • right away in the background,
  • on a queue processed by separate worker processes, or
  • later on a schedule (like "every night at 2 AM").

Explain like I'm 10

A restaurant doesn't make you stand at the counter until your food is ready. It takes your order, hands you a buzzer, and the kitchen (a background worker) cooks while you sit. You get an immediate 'order received' without waiting on the slower work.

Examples

Handing off slow work to a queue

app.post("/signup", async (req, res) => {
  const user = await createUser(req.body);

  // Instead of sending the email right here and making the user wait...
  await emailQueue.add("welcome-email", { userId: user.id });

  res.status(201).json({ ok: true }); // responds immediately
});

// Elsewhere: a separate worker process consumes the queue
emailQueue.process("welcome-email", async (job) => {
  const user = await db.users.findById(job.data.userId);
  await sendEmail(user.email, "Welcome!");
});

The handler stays fast because it only enqueues the job. The slow email sending happens in a separate worker process, so the user never waits for it.

A scheduled background job

const cron = require("node-cron");

// Runs automatically every day at 2:00 AM, with no request involved at all
cron.schedule("0 2 * * *", async () => {
  await deleteExpiredSessions();
  logger.info("cleanup_complete");
});

No user request triggers this job. It runs on a fixed schedule, independent of the request/response cycle.

How it works

Instead of doing slow work inline, the request handler records that the work needs doing, often by pushing a small message describing the job onto a queue (backed by something like Redis). Then it responds right away.

One or more separate worker processes watch the queue, pick up jobs as they arrive, and do the work, independent of any web request. Scheduled jobs are similar but are triggered by a timer (a cron schedule) instead of an event, so they run whether or not any request happens.

Why does it exist?

If every request had to finish all related work before responding, slow operations would make the app feel unresponsive. A spike in slow work (like a burst of signups all needing welcome emails) could overwhelm the web server itself.

Background jobs separate "acknowledge the request quickly" from "get the slow work done." That work can then be scaled, retried, and monitored separately from the web servers handling live traffic.

When to use it

Use background jobs for anything slow, not needed for the immediate response, or safe to retry: sending emails, processing images, generating reports, syncing with third-party services, or recurring scheduled maintenance.

When not to use it

If you need the result before you can respond meaningfully, do the work inline. For example, a login endpoint must confirm the password matches before saying 'success'.

Common mistakes

  • Putting time-sensitive work (like checking a password) into a background job when the request can't respond correctly without its result.

  • Not handling job failures. A job that fails silently with no retry or alert quietly drops real work, like an email that's never sent.

  • Assuming a job that worked once always will, without planning retries for when a dependency (like an email provider) is briefly down.

Practice exercises

  1. Easy:

    Decide which of these belongs in a background job and which inline in a request: validating a login password, sending a password-reset email, resizing a profile photo.

  2. Medium:

    Sketch a signup endpoint that enqueues a welcome email job instead of sending the email inline, and explain why that keeps the endpoint fast.

  3. Hard:

    Describe what should happen if a job that sends a confirmation email fails partway through, and how you'd make sure the email still gets sent eventually.

Interview questions

What is a background job and why would you use one?

Work done outside the normal request/response cycle. It's used for slow or non-essential tasks so the user doesn't wait for them before getting a response.

What's the difference between a queued job and a scheduled job?

A queued job is triggered by an event (like a signup) and processed by a worker as soon as possible. A scheduled job runs automatically on a fixed timer, independent of any request.

Why shouldn't login password verification be handled as a background job?

The request needs the result right away to decide how to respond. Deferring it would leave the server unable to tell the user whether login succeeded.

Why does a job queue typically need a separate worker process rather than running jobs inside the same process that handles web requests?

Slow jobs in the same process would compete with incoming HTTP requests for CPU and memory, defeating the point of offloading. A separate worker can be scaled, deployed, and monitored independently of the web servers.

What happens to a queued job if the worker processing it crashes partway through?

A well-configured queue only marks a job done after the worker confirms success. A crash leaves the job unacknowledged, so it becomes available for another worker to retry instead of being silently lost.

Why does a background job need to tolerate being run more than once, i.e. be idempotent, given retry behavior?

A queue can redeliver a job that seems to have failed, e.g. if a worker crashes right after finishing but before acknowledging. So a job may run twice. An idempotent job checks whether its effect already happened, so it gives the same correct result either way, instead of double-charging a card or sending a duplicate email.

What's a dead-letter queue, and why is it useful?

A separate place a job moves to after failing past a retry limit, instead of retrying forever or being dropped. The team can inspect and handle stuck jobs by hand, without endless retries eating worker capacity.

Why use exponential backoff between retries of a failed background job instead of retrying immediately and repeatedly?

If a dependency is overloaded or down, instant repeated retries add load when it can least handle it. Spacing retries out with growing delays gives it time to recover and makes it less likely the retries worsen the outage.

What's the difference between a job queue backed by Redis, like BullMQ, and one backed by a relational database table?

A Redis-backed queue is usually faster and comes with delayed jobs, priorities, and retries built in. A database-table queue needs no new infrastructure if you already use a relational database, but it's usually slower and you implement more of the queue logic yourself.

Why is it important to monitor background job failure rates separately from the web server's own error rate?

A failed job produces no HTTP error anyone notices, since the user already got a success response. Without separate monitoring of the job system, a job that always fails could go unnoticed indefinitely.

How could a cron-scheduled job unintentionally run more than once at the same scheduled time?

If several app instances each run their own in-process scheduler, each fires the same cron job at the same time, duplicating work meant to happen once. Guard against it with a distributed lock or by running the scheduler on one designated instance.

Why does image resizing make sense as a background job, but validating a signup form's fields typically doesn't?

Resizing is slow and its result isn't needed to respond, so the response can say 'upload received' right away. Validation decides whether the request succeeds at all, so the caller needs that result before any response.

What does a job typically carry on a queue, versus what the worker does with it?

The job usually carries just enough to identify the work, like an id and a job type, not the full state. The worker uses that id to fetch current data when it runs, instead of trusting possibly stale data captured earlier.

Why might a background job re-fetch data from the database at the time it runs, instead of using the data captured when it was enqueued?

Time can pass between queueing and processing. Re-fetching means the job acts on current state (e.g. confirming the user hasn't deleted their account since), not a stale snapshot.

What's a concurrency limit on a worker, and why would you configure one?

The maximum number of jobs a worker runs at once. It stops a burst of jobs from overwhelming a limited resource, like memory, CPU, or a downstream API's rate limit, by controlling how much runs in parallel.

Why does a worker process need to handle graceful shutdown — finishing or safely stopping in-progress jobs before exiting — during a deployment?

A worker killed mid-job during a deploy or restart can leave the job half-done or lost, depending on the queue's guarantees. Handling shutdown signals to finish or cleanly abandon in-progress work, so it can be retried later, avoids that during routine deploys.