16 min read
Job queues and background jobs with BullMQ
In one sentence: A job queue is a list of pending tasks that lives outside the request: the API writes down what can wait, like an email, answers right away, and another process, the worker, does it later and retries it if it fails. In the shop: BullMQ on Redis.
What you will learn
- Explain what a request doesn’t have to wait for, and how the API, the queue and the worker share the work.
- Send the delivery notification and the confirmation email to a BullMQ queue, and watch the email arrive in Mailpit.
- Read the retries with exponential backoff and explain why a job has to survive being done twice.
- Know why the queue’s Redis saves to disk and never deletes keys, and what gap this queue still leaves.
Before you start, read: 00-introduction.md phase-4/07-webhooks.md phase-7/07-compose.md
The problem
Section titled “The problem”Carmen pays for her order. The payment gateway tells the shop with the WebhookAn address on your server that another service sends a request to when something happens, such as a completed payment. Instead of you asking every so often whether something has changed, they let you know.Go to definition from Phase 4, and the shop has two things left to do: notify Fast Delivery, which carries the package, and send Carmen a confirmation email.
Until now, the notification went out with void notifyOfPayment(paid): the shop started it and answered without waiting for it. If Fast Delivery didn’t answer, a notification not delivered was left in the log, as you saw in Phase 6, and nobody tried again. If the API restarted halfway, the notification vanished.
Waiting for it inside the request isn’t an option either: a slow mail server would make the gateway wait. The way out is to write the job down in a list and let another program do it, and retry it if it fails. We promised it in Phase 0 (leave for later what can wait) and in Phase 4: “An email or an invoice would go to a queue.”
The analogy
Section titled “The analogy”The analogy
Think of a restaurant. The waiter writes your order on a ticket, hangs it on the kitchen rail and goes back to serving you: he doesn’t stand there watching the paella cook.
The cook takes the tickets in order. If he steps out for a moment, they pile up on the rail; when he comes back, they go out. Waiter, API; ticket, job; rail, queue; cook, worker.
Where the analogy breaks down
- A ticket is cooked once. A job in a queue can be done twice, and you have to be ready for it.
- The queue retries what fails by itself, waiting longer each time, and gives up after a few attempts.
- Paper tickets are still there if the power goes out. Redis’s are only if it saves them to disk.
How it really works
Section titled “How it really works”A queue, who writes down and who does
Section titled “A queue, who writes down and who does”This is how a payment works now:
- API → Payment gateway200, received
- Queue (Redis) → Workerthe email for order 21
- Workerjob done
- The Message queueA list of pending tasks that lives outside your server. One program adds messages at the end and another takes them from the front, one by one, at its own pace. That way whoever asks for the work does not have to wait for it to finish.Go to definition: a list of pending tasks, outside the API. Here it lives in Redis.
- Who writes down, the API: leaves a Background jobA task that is done after answering the user, not while they wait, such as sending a confirmation email. The request leaves it noted in a queue and another program runs it.Go to definition with what’s needed to do it (the order, as JSON) and moves on.
- Who does, the WorkerA program that does not answer user requests: it keeps taking tasks from a queue and running them. It can be the same code as your server, started with a different command.Go to definition: another process, which takes jobs from the queue and does them.
The gateway gets its 200 as soon as the job is written down, and the queue keeps it even if no worker is running. It’s the last row of the table in Phase 3.
BullMQ: the queue, in the Redis you already had
Section titled “BullMQ: the queue, in the Redis you already had”The shop has had Redis since Phase 7. BullMQ is a Node library that keeps a queue in Redis. The step installs it with exact versions (bullmq@6.3.15, and nodemailer@10.1.7, which sends the emails). In src/queue.ts:
// The queue, if there is Redis, created the first time it's needed: the worker also loads this file// and doesn't use it. The connection is its own: the limits' one does another job.let theQueue: Queue<Job> | undefined;function getQueue(url: string): Queue<Job> { if (!theQueue) { theQueue = new Queue<Job>(QUEUE_NAME, { connection: connectRedis(url), defaultJobOptions: JOB_OPTIONS, }); // The connection's errors (Redis down) go to the log, like the worker's. theQueue.on('error', (error) => log.error({ reason: error.message }, 'queue error')); } return theQueue;}
// Writes the job down in the queue and returns: it doesn't wait for it to be done. The job's name// is its type, so it reads like that in the log and in Redis.// Without Redis (without Docker, as until Phase 8), it's done right here, now, without waiting for// it and without retries: if it fails, it stays in the log and nothing else.export async function enqueue(job: Job): Promise<void> { if (config.REDIS_URL) { await getQueue(config.REDIS_URL).add(job.type, job); return; } log.info({ type: job.type }, 'no REDIS_URL: the job is done in this process, with no queue'); void runJob(job).catch((error: Error) => log.warn({ type: job.type, reason: error.message }, 'job failed, no retries'), );}new Queue(QUEUE_NAME, …): theshopqueue, with its own connection to Redis..add(job.type, job): writes the job down with its type (payment-noticeorconfirmation-email) and its data. Theawaitwaits for Redis to save it, not for it to be done.- With no
REDIS_URL(no Docker), the job runs in the same process, with no retries, as before.
The payment route writes down and answers
Section titled “The payment route writes down and answers”The webhook route, in src/v2.ts:
// By the time it gets here, the signature is already checked and the event matches its schema.// The response has to be quick: if the gateway doesn't get a 2xx in time, it retries. That's why the// long work (the notifications to the delivery company, the email) is left for later, in the queue// (Phase 9).v2.openapi(contract.receivePayment, async (c) => { const event = c.req.valid('json'); const order = await findOrder(event.orderId); if (!order) { return invalidData(c, [{ field: 'orderId', problem: 'No such order' }]); } // The same event again: receipt is acknowledged and nothing else is done. if (!(await recordEvent(event.id))) { return c.json({ received: event.id, repeated: true }, 200); } // Only a pending order becomes paid: a cancelled one stays cancelled. The check is in the same // UPDATE (from 'pending'): if a cancellation arrives just before, it isn't paid. const paid = await changeStatus(order.id, 'paid', 'pending'); if (paid) { // To the queue: one notification for each delivery URL (if one fails, only that one is retried) // and the email. Writing them down is quick; doing them isn't, and the worker does it. One id for // this payment, the same in all the notifications and on every retry: with it, the company // recognises a repeated notification. const eventId = randomUUID(); for (const notificationId of await savedNotifications()) { await enqueue({ type: 'payment-notice', notificationId, order: paid, eventId }); } await enqueue({ type: 'confirmation-email', order: paid }); } return c.json({ received: event.id, repeated: false }, 200);});Where step 36 had void notifyOfPayment(paid), jobs are now written down:
- One notification for each saved URL: if one company fails and another doesn’t, only its own is retried.
eventId: an id for this payment, the same in all the notifications and on every retry.- The email, another job.
notifyOfPayment is now notifyOne, in src/notifications.ts, the job’s function. If the notification doesn’t arrive, or the company doesn’t answer with a 2xx, it throws an error, and that’s how the queue knows it failed.
The worker: the same code, another process
Section titled “The worker: the same code, another process”The worker is scripts/worker.ts, with the same code and the same image as the API. In compose.yaml:
# The worker (Phase 9, lesson 1): the same image as the API, with another command. It doesn't# listen on any port: it takes the jobs from the Redis queue and does them. The same configuration# as the API, because it uses the same things: the database, Redis and the mail server.# docker compose stop worker the jobs wait in the queue# docker compose start worker and they go outworker: build: . command: ['node', 'scripts/worker.ts'] env_file: .env environment: DATABASE_URL: postgres://shop:${POSTGRES_PASSWORD}@db:5432/shop REDIS_URL: redis://redis:6379 SMTP_URL: smtp://mailpit:1025 depends_on: db: condition: service_healthy redis: condition: service_healthy migrate: condition: service_completed_successfully # The image's HEALTHCHECK asks /health, and the worker has none: it isn't a server. Its own # instead: while it takes jobs, the worker writes to /tmp/heartbeat every 5 seconds # (src/heartbeat.ts), and it's healthy if the file is less than 30 seconds old. Hung, or # shutting down, it stops writing. In its first 10 seconds (start_period), Docker asks every # second (start_interval): it's healthy almost as soon as it starts. healthcheck: test: [ 'CMD', 'node', '-e', "process.exit(Date.now() - require('node:fs').statSync('/tmp/heartbeat').mtimeMs < 30000 ? 0 : 1)", ] interval: 10s timeout: 3s retries: 3 start_period: 10s start_interval: 1sThe API’s image with another command and the same configuration, because it uses PostgreSQL, Redis and the mail server. No ports: it doesn’t serve requests. It has no /health either, so its healthcheck is a different one: the worker writes to a file every 5 seconds, its heartbeat (src/heartbeat.ts), and Docker considers it healthy while the file is recent.
Inside, a BullMQ Worker takes jobs from the queue, up to five at a time: a slow notification doesn’t hold up an email. It writes job done or job failed to the log. One codebase and two processes: lesson 5 comes back to it.
Retries with exponential backoff
Section titled “Retries with exponential backoff”What happens when a job fails, in src/queue.ts:
// Five attempts in all. Between one and the next, a wait that doubles (exponential): 1, 2, 4 and 8// seconds. A receiver that is down for a moment has time to come back, and one that is down for good// doesn't get a request every second. Finished jobs are forgotten after the last 1000; those that// fail five times stay (also the last 1000), to look at what happened.export const JOB_OPTIONS = { attempts: 5, backoff: { type: 'exponential', delay: 1000 }, removeOnComplete: 1000, removeOnFail: 1000,} satisfies DefaultJobOptions;attempts: 5: five attempts in total.backoff: between one and the next, an Exponential backoffA way of retrying something that failed by waiting longer each time: one second, then two, then four. It gives the problem time to clear and avoids piling retries onto a service that is already struggling.Go to definition, which starts at 1 second and doubles.removeOnCompleteandremoveOnFail: Redis keeps the last 1,000 jobs done and the last 1,000 failed, so you can look at what happened.
With a company that always answered 500, in “Try it” (Docker’s times are in UTC, the universal time zone):
| Attempt | Time | Wait since the previous one |
|---|---|---|
| 1 | 13:33:41.17 | — |
| 2 | 13:33:42.26 | 1.08 s |
| 3 | 13:33:44.32 | 2.06 s |
| 4 | 13:33:48.36 | 4.05 s |
| 5 | 13:33:56.45 | 8.09 s |
Waiting longer each time gives a receiver time to come back, without drowning one that is down for good. Five attempts in about 15 seconds are enough for practice; a real shop waits hours, and payment services retry for days.
At least once: a job can be done twice
Section titled “At least once: a job can be done twice”Imagine Fast Delivery’s 200 gets lost: the shop thinks the notification failed, and retries. Or the worker shuts down suddenly after sending an email and before marking it as done: BullMQ puts it back in the queue.
That’s why queues promise At-least-once deliveryA queue’s promise that every message will arrive at least once, never zero times. In exchange, it may arrive twice, for example if the worker goes down just before confirming it finished. That is why what the worker does must be idempotent.Go to definition: no job the queue has saved is lost, but some are done twice. What the worker does has to survive being repeated: the idempotency from Phase 4, from the other side.
- The notification carries
X-Event-Id, the same on every retry. Fast Delivery should ignore the ids it has already processed, as the shop does with the gateway. - The email carries no id: if it’s repeated, Carmen gets two. A nuisance; what can’t happen twice, like a charge, needs an id.
The email: Mailpit and short waits
Section titled “The email: Mailpit and short waits”The email job, in src/email.ts, looks up the customer’s address and sends it with Nodemailer, which speaks SMTP, the protocol emails travel over, with the server in SMTP_URL. On your computer that’s Mailpit: it receives the emails, sends them to nobody and shows them in a web inbox.
# Mailpit, pinned by its digest: a practice mail server. It receives by SMTP (1025, only inside# Compose's network) what the shop sends, sends it to nobody and shows it in an inbox at# http://localhost:8025, only on your computer.mailpit: image: axllent/mailpit:v1.31.5@sha256:94f6b70c1436defae6799d9ac7ff0eeff9540465b842026d5cdb018f1c0234ea ports: - '127.0.0.1:8025:8025'The waits are short on purpose. By default, Nodemailer waits up to 2 minutes to connect and 10 without news from the server. With a stuck mail server, docker stop would kill the worker after 10 seconds with the email half sent, and the queue would repeat it. The shop waits 5 seconds at most at each step, as it does for a notification: it fails early, and the queue retries.
On SIGTERM, the worker finishes what it has half done and exits, like the API since Phase 7.
Redis can no longer forget: disk and noeviction
Section titled “Redis can no longer forget: disk and noeviction”Until Phase 8, Redis saved nothing to disk: losing the limiter’s attempts didn’t matter. Losing the queue does: those would be notifications and emails that never go out.
# Redis 8, pinned by its digest: the attempts of the limits, shared by all the copies of the API,# and since Phase 9 the job queue. No published port, like db.# Until Phase 8 it saved nothing to disk: losing the limits' attempts doesn't matter. Losing the# queue does: they would be notifications and emails that never go out. That's why it now writes# every change to disk (--appendonly yes), in a volume, and reads them again when it restarts. And# it never deletes keys to make room (--maxmemory-policy noeviction): with a memory limit# (--maxmemory), when it reached it, it would give an error, and the job that doesn't fit would# fail in plain sight instead of disappearing. It's what BullMQ asks for.redis: image: redis:8@sha256:2c2dff791878316e3b083188be0d578423b24813cdda5de0e80ea4f7b3e6bfd6 command: ['redis-server', '--appendonly', 'yes', '--maxmemory-policy', 'noeviction'] volumes: - redis:/data healthcheck: test: ['CMD', 'redis-cli', 'ping'] interval: 2s timeout: 5s retries: 15--appendonly yes: Redis writes down every change in a file, in theredisVolume (in Docker)A folder Docker keeps outside the containers and mounts inside the ones that ask for it. What’s written to it survives when the container is deleted, so that’s where the data you need to keep goes, like a database’s.Go to definition, and reads it back on startup. It flushes to disk every second: a power cut can cost the last second of changes.--maxmemory-policy noeviction: Redis never deletes keys to make room. If it reaches a memory limit, it returns an error: the job visibly fails instead of disappearing. It’s the default value, but it’s written out: BullMQ warns you if it isn’t.
A cache wants the opposite: it will have its own Redis in lesson 2.
The gap that remains: two writes
Section titled “The gap that remains: two writes”Paying writes in two places: the order, in PostgreSQL; the jobs, in Redis. If the API goes down between one write and the other:
- APIthe API goes down here,
before writing down the jobs - API → Payment gateway200, repeated
- Queue (Redis)no notification, no email
The shop knows evt_1 and repeats nothing: the order is paid, but nobody notifies Fast Delivery or Carmen. If Redis doesn’t answer, await enqueue keeps waiting and the gateway gives up: its retry gets repeated. The jobs go out when Redis comes back, if the API is still alive; if it restarts first, they’re lost.
Left open on purpose: lesson 7 closes it by writing the jobs down in the same TransactionA group of SQL commands that the database treats as one: either all of them are saved, or none. It starts with BEGIN and ends with COMMIT, which saves it, or with ROLLBACK, which undoes all of it.Go to definition as the order (Phase 5).
Other queues: RabbitMQ, Kafka, SQS and PostgreSQL
Section titled “Other queues: RabbitMQ, Kafka, SQS and PostgreSQL”BullMQ fits because the shop already has Redis. There are more:
| Tool | What it is | When it fits |
|---|---|---|
| RabbitMQ | A separate message server, with its own protocol (AMQP) | Programs in several languages passing messages to each other |
| Kafka | A log of events kept for days, in order: several readers read the same thing and can go back | A huge number of events, read by many |
| Amazon SQS | An AWS queue, with no server to maintain; you pay per message | If you already live on AWS |
| PostgreSQL (pg-boss, in Node) | The queue is a table in your database | Low volume, no Redis, and the job in the same transaction as the order |
With all of them, delivering at least once is the norm.
Try it
Section titled “Try it”The goal: watch the email of a paid order arrive, watch the queue retry a notification that fails, and check that, with no worker, jobs wait without getting lost.
The outputs are from October 22, 2026, on a Mac (Apple M1 Pro) with Docker 29 in Colima, a virtual machine with 4 processors and 2 GiB. Your ids, times and secrets will differ.
Get the step ready
Section titled “Get the step ready”Put your project at step 37, as in the introduction:
cd ~/backend-course/phase-3curl -O https://backenddesdecero.com/practicas/shop-api/37-queue.tar.gztar -xzf 37-queue.tar.gzcp -R 37-queue/. shop-api/cd shop-apiYour .env is still the one from Phase 7, with your secrets. Add a line, or change it if you already have it, so the shop notifies the practice company: NOTIFICATION_DEV_HOSTS=carrier.
Then delete the practice data, so order 21 is pending again, and start the shop:
docker compose down -vdocker compose up --build --wait--wait returns when everything is healthy, with two new services: worker and mailpit.
A payment, an email
Section titled “A payment, an email”Order 21 is pending in the sample data. Pay it with the fake gateway from Phase 4, in a Node 26 container:
1. The gateway pays order 21
docker run --rm --network shop_default --env-file .env -e SHOP_URL=http://api:3000 -v "$PWD":/p -w /p node:26 node scripts/payment-gateway.ts 21What you will see:
→ POST /v2/webhooks/payments {"id":"evt_525b03bc-fd35-42af-852d-5d341f49f9f9","type":"payment.completed","orderId":21}← 200 {"received":"evt_525b03bc-fd35-42af-852d-5d341f49f9f9","repeated":false}The container joins the shop’s network, signs with the WEBHOOK_SECRET from your .env and mounts your project (Phase 7). 200 and "repeated":false: the shop answered without waiting for the email. If you get invalid-signature, you changed .env after the up: docker compose up -d recreates the containers.
Then ask Mailpit, with jq (Phase 3):
2. The email, in Mailpit
curl -s http://127.0.0.1:8025/api/v1/messages | jq ".messages[0] | {Subject, To: .To[0].Address}"What you will see:
{"Subject": "Your order 21 is paid","To": "carmen@example.com"}The subject and recipient of the first email: Carmen, the customer of order 21. In the browser, http://127.0.0.1:8025 is the same inbox. If you get null, look at the worker’s log.
3. What the worker did
docker compose logs worker --no-log-prefixWhat you will see:
{"level":30,"time":1792675944666,"pid":1,"hostname":"383a94026ef2","msg":"The worker is waiting for jobs from the queue"}{"level":30,"time":1792675961157,"pid":1,"hostname":"383a94026ef2","id":"1","type":"confirmation-email","msg":"job done"}The worker starts, and job 1, a confirmation-email, is done. With job failed, look at its reason; with no such line, wait and repeat.
Pay order 22 the same way, with 22 at the end of the command: a second email arrives.
A notification that fails five times
Section titled “A notification that fails five times”Now, a delivery company that always answers 500: a Node container, carrier, that writes down every request it receives.
docker run -d --rm --name carrier --network shop_default --network-alias carrier node:26 node --eval "require('node:http').createServer((req, res) => { console.log(req.method, req.url); res.writeHead(500).end(); }).listen(8080)"The shop only notifies internet addresses over https, because of the SSRFSSRF stands for Server-Side Request Forgery.An attack in which someone gives a server a URL to visit, and the server’s request reaches places only it can reach, like its own database, the internal network or the credentials the cloud gives it. It’s stopped by checking which IP address the URL points to before connecting.Go to definition from Phase 6; NOTIFICATION_DEV_HOSTS is the practice exception. Fast Delivery needs its API key, and the script that creates it isn’t in the image: copy it in and run it.
docker compose cp scripts/create-key.ts api:/app/scripts/docker compose exec api node scripts/create-key.ts "Fast Delivery"It shows the key once, starting with shop_. Save it: KEY=shop_…, with yours in full.
4. Fast Delivery’s URL
curl -s -X PUT http://127.0.0.1:3000/v2/delivery/notification -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" -d '{"url":"http://carrier:8080/notice"}'What you will see:
{"url":"http://carrier:8080/notice","secret":"…"}The shop saves the URL and returns the signing secret (hidden, …). If your API is on 3001 (docker compose port api 3000), change the port; ours was. With 401, check $KEY.
5. Pay order 23
docker run --rm --network shop_default --env-file .env -e SHOP_URL=http://api:3000 -v "$PWD":/p -w /p node:26 node scripts/payment-gateway.ts 23What you will see:
→ POST /v2/webhooks/payments {"id":"evt_ede997e3-fe48-423a-a8cd-bf3c86f5434e","type":"payment.completed","orderId":23}← 200 {"received":"evt_ede997e3-fe48-423a-a8cd-bf3c86f5434e","repeated":false}200 right away, even though the notification is going to fail.
Wait about 20 seconds. --timestamps adds Docker’s time, in UTC:
6. Five attempts
docker compose logs --timestamps --no-log-prefix workerWhat you will see:
…2026-10-22T13:33:41.173441878Z {"level":30,"time":1792676021173,"pid":1,"hostname":"383a94026ef2","id":"4","type":"confirmation-email","msg":"job done"}2026-10-22T13:33:41.174151731Z {"level":40,"time":1792676021173,"pid":1,"hostname":"383a94026ef2","id":"3","type":"payment-notice","attempt":1,"of":5,"reason":"notification not delivered: the company answers 500","msg":"job failed: it will be retried"}2026-10-22T13:33:42.257892368Z {"level":40,"time":1792676022256,"pid":1,"hostname":"383a94026ef2","id":"3","type":"payment-notice","attempt":2,"of":5,"reason":"notification not delivered: the company answers 500","msg":"job failed: it will be retried"}2026-10-22T13:33:44.315527786Z {"level":40,"time":1792676024315,"pid":1,"hostname":"383a94026ef2","id":"3","type":"payment-notice","attempt":3,"of":5,"reason":"notification not delivered: the company answers 500","msg":"job failed: it will be retried"}2026-10-22T13:33:48.363756104Z {"level":40,"time":1792676028362,"pid":1,"hostname":"383a94026ef2","id":"3","type":"payment-notice","attempt":4,"of":5,"reason":"notification not delivered: the company answers 500","msg":"job failed: it will be retried"}2026-10-22T13:33:56.452400044Z {"level":40,"time":1792676036452,"pid":1,"hostname":"383a94026ef2","id":"3","type":"payment-notice","attempt":5,"of":5,"reason":"notification not delivered: the company answers 500","msg":"job failed: no attempts left"}We’ve removed the first three lines (…): the worker starting and the emails for orders 21 and 22. Look at:
- Job
3, the notification:attempt1 to 5, with 1, 2, 4 and 8 seconds between the times, andno attempts lefton the last one. - Job
4, the email for the same payment:donein the same millisecond as the first failure, without waiting for the notification.
docker logs carrier shows five POST /notice lines: all five attempts arrived. If you see fewer, wait: the last one comes about 15 seconds after the first.
Remove the carrier and its URL, so the next payment only writes down the email:
docker rm -f carrierdocker compose exec db psql -U shop -c "delete from notifications"With no worker, jobs wait
Section titled “With no worker, jobs wait”7. With no worker, a payment
docker compose stop workerdocker run --rm --network shop_default --env-file .env -e SHOP_URL=http://api:3000 -v "$PWD":/p -w /p node:26 node scripts/payment-gateway.ts 24What you will see:
Container shop-worker-1 StoppingContainer shop-worker-1 Stopped→ POST /v2/webhooks/payments {"id":"evt_876d076d-494e-4bf8-a697-5336c78f58fa","type":"payment.completed","orderId":24}← 200 {"received":"evt_876d076d-494e-4bf8-a697-5336c78f58fa","repeated":false}The gateway gets its 200 all the same: to write a job down, the API doesn’t need the worker.
8. In Mailpit, nothing new
curl -s http://127.0.0.1:8025/api/v1/messages | jq "{total, subjects: [.messages[].Subject]}"What you will see:
{"total": 3,"subjects": [ "Your order 23 is paid", "Your order 22 is paid", "Your order 21 is paid"]}The emails for 21, 22 and 23. None for 24.
9. The job, waiting in Redis
docker compose exec redis redis-cli LRANGE bull:shop:wait 0 -1docker compose exec redis redis-cli HMGET bull:shop:5 name dataWhat you will see:
5confirmation-email{"type":"confirmation-email","order":{"id":24,"productId":1,"quantity":1,"status":"paid","createdAt":"2026-10-08T02:00:00.000Z","customerId":4}}bull:shop:wait, the waiting list of theshopqueue: one job, the5.bull:shop:5, that job: its name and its data, order 24 as JSON. If yours has another number, change it in theHMGET.
10. The worker comes back
docker compose start workerdocker compose exec redis redis-cli LLEN bull:shop:waitcurl -s http://127.0.0.1:8025/api/v1/messages | jq "{total, subjects: [.messages[].Subject]}"What you will see:
Container shop-db-1 WaitingContainer shop-db-1 HealthyContainer shop-migrate-1 StartingContainer shop-migrate-1 StartedContainer shop-redis-1 WaitingContainer shop-migrate-1 WaitingContainer shop-db-1 WaitingContainer shop-db-1 HealthyContainer shop-redis-1 HealthyContainer shop-migrate-1 ExitedContainer shop-worker-1 StartingContainer shop-worker-1 Started0{"total": 4,"subjects": [ "Your order 24 is paid", "Your order 23 is paid", "Your order 22 is paid", "Your order 21 is paid"]}Compose starts the worker. The waiting list, LLEN, ends up at 0, and the email for 24 is in Mailpit.
11. When it went out
docker compose logs --timestamps --no-log-prefix worker | tail -n 3What you will see:
2026-10-22T13:34:16.613256721Z {"level":30,"time":1792676056612,"pid":1,"hostname":"383a94026ef2","msg":"SIGTERM: the worker finishes what it has half done and shuts down"}2026-10-22T13:34:35.035519941Z {"level":30,"time":1792676075034,"pid":1,"hostname":"383a94026ef2","msg":"The worker is waiting for jobs from the queue"}2026-10-22T13:34:35.095686512Z {"level":30,"time":1792676075095,"pid":1,"hostname":"383a94026ef2","id":"5","type":"confirmation-email","msg":"job done"}The SIGTERM is your stop. When it comes back, the worker waits and, 60 milliseconds later, job 5 is done. Nothing was lost. If it doesn’t show up, look at docker compose ps worker.
When you’re done, docker compose down stops everything; with -v, it also deletes the data and the queue.
On your server
Section titled “On your server”With the shop on your server from Phase 8, first copy the files the server reads from its disk, which aren’t in the image. From ~/backend-course/phase-3, with your user and your IP. On Windows, from PowerShell as in Phase 8, with the step downloaded there (curl.exe -O and tar -xzf), and scp instead of rsync -av:
rsync -av 37-queue/compose.production.yaml ubuntu@192.168.5.15:/opt/shop/rsync -av 37-queue/deployment/ ubuntu@192.168.5.15:/opt/shop/deployment/On the server, chmod +x /opt/shop/deployment/*.sh, as in Phase 8. Then, the code: it’s already in your project, so commit and git push from shop-api (your .env isn’t uploaded: .gitignore leaves it out). With the new image, deploy.sh brings the other services up to date:
# The services that aren't from the image (db, redis), up to date with compose.production.yaml: if# one has changed (in Phase 9, Redis keeps the queue on disk), Compose recreates it; if not, it# doesn't touch it. It goes before the backup and the migrations, which need db running. Recreating# redis forgets the limits' attempts, and that doesn't matter.log "the other services, up to date""${compose[@]}" up -d --no-build --no-deps db redisRedis is recreated with disk (it forgets the limiter’s attempts, nothing more), and the API and the worker start with the new image; the rollback covers both. The script waits for both to be healthy: the API, through /health, and the worker, through its heartbeat. A worker that crashes on startup, over and over, never beats, and the deployment rolls back. Check it with docker compose -f compose.production.yaml ps worker.
The email is optional. Without SMTP_URL, the job leaves no SMTP_URL: the confirmation email is not sent in the log and finishes. To send them for real:
- Sign up with an email provider: it gives you an SMTP server, a user and a password.
- Add the TXT records it asks for to your domain’s DNS (Phase 0), almost always SPF, which says which servers send email for your domain, and DKIM, which signs each email. Without them, they end up in spam.
- Put your details in the server’s
.env:
# The mail server (Phase 9), for the confirmation email of a paid order. Without it, the shop works# all the same and sends no emails: the log says which one would have gone out. With an email# provider (it gives you the server, the user and the password), remove the # from the two lines# and put yours, and the sender, an address on your domain. So the emails don't end up in spam, the# provider will ask you for some records in your domain's DNS (SPF and DKIM). The password goes# inside a URL: a symbol is written with its code (an @, %40).# SMTP_URL=smtps://user:password@smtp.provider.example:465# SMTP_FROM=The shop <orders@shop.example>- Recreate the worker:
docker compose -f compose.production.yaml up -d --no-build --no-deps worker.
You have already seen it
Section titled “You have already seen it”- The “order confirmed” email that arrives a few seconds after you pay: a worker sends it.
- A video that is “being processed” after you upload it: it’s converted in the background.
Common mistakes
Section titled “Common mistakes”- Doing the slow work inside the request. Whoever calls waits, and if they give up, they retry. A
voidwith no queue, if it fails, is lost. - Jobs that don’t survive being repeated. What can’t happen twice needs an id, like
X-Event-Id. - The queue in a Redis that forgets. With no disk, a restart takes the jobs away; if it deletes keys to make room, they vanish without an error.
- Retrying without waiting, or without a limit. It drowns the receiver that is down, and an impossible job repeats forever.
- Long waits inside the job.
docker stopkills the worker halfway, and the job is repeated.
Summary
Section titled “Summary”- What a request doesn’t have to wait for goes to a queue: the API writes it down and answers, and the worker does it later.
- BullMQ keeps the queue in Redis; the worker is the API’s code with another command.
- A job that fails is retried with exponential backoff: five attempts, with 1, 2, 4 and 8 seconds between them.
- Queues deliver at least once: every job has to survive being repeated.
- The queue’s Redis saves to disk and never deletes keys. A gap remains: the order and its jobs are written in two steps.
Did you get it?
Section titled “Did you get it?”To review:
Further reading
Section titled “Further reading”- BullMQ documentation: queues, workers and job options.
- Retrying failing jobs:
attemptsand the types ofbackoff. - Redis persistence: how Redis saves to disk and what it can lose.
- Mailpit: the practice mail server and its API.
- RabbitMQ Tutorials: the same ideas, with a separate message server.