Square CloudSquare Cloud

How to run background jobs: queues with BullMQ and Celery

To run background jobs, put each job on a queue in Redis and let a separate worker process run it. The request returns right away, the queue retries failures with backoff, and every job must be idempotent because it can run more than once.

Updated 8 min read

Learning objectives

After reading this article you will be able to:

  • Know when to move work out of the request and onto a queue
  • Build a queue with retries in BullMQ (Node.js) and Celery (Python)
  • Run the worker in production with idempotent jobs and a safe shutdown
On this page

Sending a welcome email, generating a PDF, resizing an image, calling a flaky third-party API: none of it has to finish before the user gets a response. When it does, the request gets slow, can blow past the proxy's timeout and, if the external service fails, the user sees an error for something you could have retried quietly.

The fix is a background job: the API records the work on a queue and responds right away, and another process does it. This guide builds that queue with BullMQ in Node.js and with Celery in Python, and covers retries, idempotency and running the worker in production. If you're still choosing between cron, a worker and a queue, start with cron jobs vs background workers vs queues.

When should work leave the request?#

A background job is any work the application does outside the cycle of an HTTP request. Send work to a queue when it has one of these traits:

  • It takes more than a few hundred milliseconds: email, PDFs, media processing, reports.
  • It depends on an external service that can fail or rate limit you: payments, AI APIs, outgoing webhooks.
  • It arrives in bursts: importing a 10,000-row spreadsheet becomes 10,000 jobs waiting their turn, not one request that never finishes.

Whatever the response depends on, such as validating the form and saving the order, stays in the request. The API returns 202 Accepted, and the client follows the result by polling, a WebSocket or a notification. Work that depends only on the clock, like a nightly cleanup, is a job for a cron job.

How does a job queue on Redis work?#

There are three pieces:

  1. Producer: your API, which adds a job (a name plus JSON data) to the queue.
  2. Broker: where jobs wait. For BullMQ it's always Redis; Celery accepts Redis, RabbitMQ and Amazon SQS. See what is Redis.
  3. Worker: a long-running process that picks up jobs, runs them and acknowledges the result.

The worker runs as a separate process from the API: a heavy job doesn't compete with requests for CPU, and an API deploy doesn't interrupt jobs.

Queues guarantee at-least-once delivery. If the worker crashes after taking a job and before acknowledging it, the job goes back on the queue and runs again. BullMQ calls these jobs stalled and reprocesses them when a worker comes back; Celery with acks_late does the same. That guarantee is what makes idempotency mandatory.

How do you build a queue with BullMQ in Node.js?#

bash
npm install bullmq ioredis express

With "type": "module" in package.json, one shared connection helper covers local Redis and Redis over TLS:

js
// connection.js
import fs from "node:fs";
import IORedis from "ioredis";

export function redis(options = {}) {
  return new IORedis(process.env.REDIS_URL, {
    tls: process.env.REDIS_CA_PATH
      ? { ca: fs.readFileSync(process.env.REDIS_CA_PATH) }
      : undefined,
    ...options,
  });
}

A rediss:// URL turns TLS on by itself in ioredis; REDIS_CA_PATH is only needed when the server uses its own CA. The API adds the job and responds:

js
// server.js
import express from "express";
import { Queue } from "bullmq";
import { redis } from "./connection.js";

const emailQueue = new Queue("emails", {
  connection: redis(),
  defaultJobOptions: {
    attempts: 5,
    backoff: { type: "exponential", delay: 1000, jitter: 0.5 },
    removeOnComplete: { age: 24 * 3600, count: 1000 },
    removeOnFail: { age: 7 * 24 * 3600 },
  },
});

const app = express();
app.use(express.json());

app.post("/signup", async (req, res) => {
  const { userId, email } = req.body;
  // save the user to the database here
  await emailQueue.add("welcome", { userId, email }, { jobId: `welcome-${userId}` });
  res.status(202).json({ status: "queued" });
});

app.listen(Number(process.env.PORT ?? 3000), "0.0.0.0", () => {
  console.log("API up");
});

The worker is another process:

js
// worker.js
import { UnrecoverableError, Worker } from "bullmq";
import { redis } from "./connection.js";

async function sendWelcomeEmail(to, idempotencyKey) {
  // swap in your email provider's SDK, passing the key along
  console.log(`sending welcome email to ${to} (key ${idempotencyKey})`);
}

const worker = new Worker(
  "emails",
  async (job) => {
    if (!job.data.email) throw new UnrecoverableError("job has no email");
    await sendWelcomeEmail(job.data.email, job.id);
  },
  { connection: redis({ maxRetriesPerRequest: null }), concurrency: 5 },
);

worker.on("failed", (job, err) => {
  console.error(`job ${job?.id} failed on attempt ${job?.attemptsMade}:`, err.message);
});

async function shutdown(signal) {
  console.log(`${signal} received, closing the worker`);
  await worker.close();
  process.exit(0);
}
process.on("SIGTERM", () => shutdown("SIGTERM"));
process.on("SIGINT", () => shutdown("SIGINT"));

Run each one in its own terminal, with REDIS_URL=redis://localhost:6379 in .env:

bash
node --env-file=.env server.js
node --env-file=.env worker.js

By default, finished jobs are kept in Redis's completed and failed sets; removeOnComplete and removeOnFail cap how many and for how long. concurrency: 5 lets one worker process five jobs at once, and the worker requires maxRetriesPerRequest: null on its connection.

How do you build a queue with Celery in Python?#

bash
pip install "celery[redis]" flask
python
# tasks.py
import os
import ssl

from celery import Celery

app = Celery("tasks", broker=os.environ["REDIS_URL"])

ca_path = os.environ.get("REDIS_CA_PATH")
if ca_path:
    app.conf.broker_use_ssl = {
        "ssl_cert_reqs": ssl.CERT_REQUIRED,
        "ssl_ca_certs": ca_path,
    }

app.conf.update(
    task_acks_late=True,
    worker_prefetch_multiplier=1,
    broker_connection_retry_on_startup=True,
)


class TemporaryError(Exception):
    """A failure worth retrying: timeout, 429, 5xx."""


@app.task(
    bind=True,
    autoretry_for=(TemporaryError,),
    retry_backoff=True,
    retry_backoff_max=600,
    retry_kwargs={"max_retries": 5},
)
def send_welcome_email(self, user_id, email):
    # swap in your provider's SDK; raise TemporaryError on transient failures
    print(f"sending welcome email to {email}, attempt {self.request.retries + 1}")
python
# app.py
from flask import Flask, request

from tasks import send_welcome_email

app = Flask(__name__)


@app.post("/signup")
def signup():
    data = request.get_json()
    # save the user to the database here
    send_welcome_email.delay(data["user_id"], data["email"])
    return {"status": "queued"}, 202
bash
celery -A tasks worker --loglevel=INFO --concurrency=2
flask --app app run

task_acks_late acknowledges a job only after it finishes, and worker_prefetch_multiplier=1 makes each process reserve one job at a time, which suits long tasks. Without --concurrency, Celery starts one process per CPU the machine reports, each with its own copy of your code: in a small container, pin the number. On Redis, a job not acknowledged within the visibility_timeout (1 hour by default) is handed to another worker and runs again, so split tasks that take longer than that.

How do you set up retries with backoff?#

Exponential backoff means waiting longer and longer between one attempt and the next, so you don't hammer a service that's already struggling. Both libraries ship it:

BullMQ Celery
How many times attempts: 5, counting the first max_retries: 5 after the first (default 3)
Growing wait exponential backoff: 1 s, 2 s, 4 s, 8 s with delay: 1000 retry_backoff=True: 1 s, 2 s, 4 s..., up to retry_backoff_max (default 600 s)
Randomness (jitter) jitter from 0 to 1 (default 0) retry_jitter (on by default)
Fail without retrying throw new UnrecoverableError() only exceptions in autoretry_for are retried

Retry only what's transient: timeouts, 429, 5xx, refused connections. An invalid email address fails the same way on all five attempts; mark it as a permanent failure right away. Jitter spreads retries over time, so a thousand jobs that failed together don't all come back in the same second. If the external service answers 429, honor Retry-After; the mechanics are in API rate limiting.

How do you make a job idempotent?#

A job is idempotent when running it twice leaves the system in the same state as running it once: the customer gets one email, not two, and the card is charged once. The BullMQ docs sum up the rule: small, atomic jobs designed to fail. Three techniques work together, and idempotency in APIs covers each in depth:

  • Deduplicate on the way in. In BullMQ, a fixed jobId (welcome-42) makes the queue ignore a second add with the same id while the first one exists. Once the job is removed, by removeOnComplete for example, the id is free again. It can't contain : or be digits only.
  • Check state before acting. The worker reads from the database whether the work is done (a filled-in welcome_sent_at) and exits early. A UNIQUE constraint closes the race between two workers.
  • Pass an idempotency key to the external service. Payment APIs such as Stripe's accept an Idempotency-Key header: with the job id as the key, a second call returns the first call's result instead of charging again.

How do you run the worker in production?#

Shut down without losing jobs. On a deploy or restart, the environment sends SIGTERM. In BullMQ, the example's worker.close() waits for running jobs before exiting; a worker killed mid-job leaves stalled jobs, which go back on the queue at the next check (the stalledInterval, 30 seconds by default) and are picked up by another worker. Celery treats SIGTERM as a warm shutdown: it finishes the tasks it's running, then exits. A job longer than the time until SIGKILL needs to be split.

Concurrency costs memory. Each Celery process and each concurrent BullMQ job takes RAM. Size for the peak, because a worker killed for lack of memory vanishes with no error in the log (see out of memory errors).

Prepare Redis. The BullMQ docs ask for maxmemory-policy noeviction, so Redis never drops queue keys, and persistence turned on, so jobs survive a server restart.

Expect dropped connections. The network, a restart or a server that closes idle clients will drop the connection now and then. ioredis reconnects on its own by default, and BullMQ's worker waits for the connection to come back without throwing, thanks to maxRetriesPerRequest: null. Celery retries the broker connection and, on Redis, checks the connection every 25 seconds. For the error messages, see Redis connection errors.

Verify it. Add a test job and check the worker's log. Then force a transient failure and watch the spaced-out attempts. Finally, restart the worker with a long job running and confirm it either finishes or goes back on the queue. BullMQ's most common error is this one:

Error: BullMQ: Your redis options maxRetriesPerRequest must be null.
Symptom Cause Fix
maxRetriesPerRequest must be null when creating the Worker The Worker's ioredis connection was created without maxRetriesPerRequest: null Create the worker's connection with that option
Jobs sitting on the queue The worker is down, listening to another queue name or to another Redis Check the process, the queue name and the REDIS_URL on both the API and the worker
Duplicate emails or charges A job without idempotency, retried after a failure A fixed jobId, a state check and an idempotency key

How to do this on Square Cloud#

On Square Cloud, the API and the worker are two separate apps in the same account. The worker runs as a background app, with no subdomain, and uses at least 256 MB of the plan's RAM pool; the API, as a web app, uses at least 512 MB. Containers stay on, with no sleep on inactivity, so the worker keeps listening to the queue, and auto restart (on by default when you deploy from the dashboard) brings it back if it exits with an error. Scaling the worker is up to you: more RAM and more concurrency (concurrency or --concurrency), or another worker app reading the same queue.

An example start command (START) for the worker, to adjust to your project: node worker.js on Node.js or celery -A tasks worker --loglevel=INFO --concurrency=2 on Python. On start, the platform installs dependencies (npm install or pip install -r requirements.txt). You can deploy with a ZIP in the dashboard, the CLI, GitHub or the VS Code extension, and the squarecloud.app file is optional: the dashboard generates it on deploy.

Redis hosting starts on the Standard plan (from R$44.99 a month), in the same datacenter as your apps, with persistence and a single logical database. The connection uses rediss:// with mandatory TLS: the client has to trust the CA the dashboard gives you to download, which is what the examples' REDIS_CA_PATH is for. One app can't read another's variables, so copy the URL into REDIS_URL in both the API and the worker. Redis closes idle clients after 5 minutes, and each database accepts up to 256 connections: use clients that reconnect on their own, like the ones in the examples, and add up the connections of every process.

See the options to host APIs.

API hosting

APIs in always-on containers, with no cold starts

API hosting

FAQs

What's the difference between BullMQ and Celery?

BullMQ is a Node.js queue library that stores jobs in Redis. Celery is the most widely used task queue in Python and accepts Redis, RabbitMQ or Amazon SQS as its broker. The model is the same: producer, queue and worker.

Can the worker run in the same process as the API?

It can, but in production it rarely pays off: a heavy job competes with requests for CPU and memory, and every API deploy interrupts running jobs. As separate processes, you scale and restart each one without touching the other.

Why did a job run twice?

Queues deliver each job at least once: if the worker crashes or runs past its limit before acknowledging, the job goes back on the queue. That's why every job has to be idempotent.

Do I need Redis to use a job queue?

For BullMQ, yes: it keeps everything in Redis. Celery also works with RabbitMQ or Amazon SQS as the broker.

Next articleProduction checklist for your APIA production checklist for your API: environment variables, health check, graceful shutdown, standard errors, authentication, rate limiting, CORS and logs.