Backend Case Studies

Topic B10

Message queues and background jobs

Moving slow work onto a queue and workers, so users don't wait.

9 min · intermediate

Watch: without a queue, every user waits for the email to send. With a queue, users are done at once and email goes out behind the scenes.

u1u2u3u4APIemail provider
  • moving now
  • being checked
  • finished / the result
Step 1 of 6

Each sign-up sends a welcome email inside the same request. The email provider takes 3 seconds.

Slow work the user doesn't need to wait for goes onto a queue and is done behind the scenes.

Like a restaurant kitchen

A waiter doesn't stand in the kitchen waiting for each dish. They write down the order, clip it to the ticket rail, and go back to the guests. Cooks take tickets one at a time. When the restaurant is busy, the rail gets longer, but the waiter can still seat new guests. That rail is a queue (Module 1): first in, first done.

Code, for programmersBullMQ in Node.js
import { Queue, Worker } from "bullmq";
const emails = new Queue("emails", { connection: redis });

// in the API: enqueue and answer at once
app.post("/signup", async (req, res) => {
  const user = await db.user.create({ data: req.body });
  await emails.add("welcome", { userId: user.id }, {
    attempts: 5,
    backoff: { type: "exponential", delay: 2000 },   // 2s, 4s, 8s, ...
  });
  res.status(201).json(user);
});

// in a separate worker process
new Worker("emails", async (job) => {
  const user = await db.user.findUnique({ where: { id: job.data.userId } });
  await mailer.send(user.email, "Welcome!");
}, { connection: redis, concurrency: 5 });

Things to think about

  • Retries: outside services sometimes fail. Retry with longer and longer pauses (exponential backoff), and cap the number of attempts.
  • A dead letter queue: jobs that still fail after every attempt move to a separate queue for a human to inspect, instead of vanishing quietly.
  • At least once: most queues promise a job is delivered at least once. If a worker dies right after sending the email but before reporting done, the job runs again and the email goes out twice. Make jobs safe to run more than once (see the idempotency topic).
  • Send an id, not all the data: data can change between when a job is created and when it runs. The worker should read the latest.

Quiz

  1. Which job fits a queue best?

  2. A worker dies after sending an email but before marking the job done. What usually happens?

  3. What is a dead letter queue for?

0 of 3 answered.