Sikau

System design · Day 10 · about 45 min

Queues and at-least-once delivery

Hand slow work to a queue; acks, redelivery and a dead-letter box.

Don't make the learner wait

A learner finishes a course and Sikau must email a certificate, update a leaderboard and ping Discord. Doing all of that before answering makes the page slow, and if the email service is down the whole request fails. Instead the web server drops a small job into a message queue and replies at once. Separate workers pick jobs up when they can.

The hard part: a worker can crash halfway. So a job isn't deleted when it is handed out; it is only *hidden* for a while. If the worker acks (acknowledges) in time, the job is removed. If not, it reappears and another worker tries again. That is at-least-once delivery.

Visibility timeout and the dead-letter box

function createQueue({ visibility = 30, maxAttempts = 3, now = () => Date.now() } = {}) {
  const jobs = [];
  const dead = [];
  let nextId = 1;
  return {
    send(body) {
      const id = nextId++;
      jobs.push({ id, body, attempts: 0, hiddenUntil: 0 });
      return id;
    },
    receive() {
      const t = now();
      for (let i = 0; i < jobs.length; ) {
        const j = jobs[i];
        if (j.hiddenUntil > t) { i++; continue; }
        if (j.attempts >= maxAttempts) { jobs.splice(i, 1); dead.push(j.body); continue; }
        j.attempts++;
        j.hiddenUntil = t + visibility;
        return { id: j.id, body: j.body, attempts: j.attempts };
      }
      return null;
    },
    ack(id) {
      const i = jobs.findIndex((j) => j.id === id);
      if (i < 0) return false;
      jobs.splice(i, 1);
      return true;
    },
    size() { return jobs.length; },
    deadLetters() { return [...dead]; },
  };
}

Three consequences follow. Jobs can run more than once, so workers must be idempotent (Day 6: use an idempotency key). Order is only best-effort, because a retried job lands after newer ones. And a poison message that always crashes its worker must not loop forever: after maxAttempts it moves to a dead-letter queue for a human to inspect.

"Exactly-once" delivery over a network is not really possible. What systems offer is at-least-once delivery plus idempotent handlers, which together *behave* like exactly-once.

The rest of this lesson

  • A job's journeyorder
  • Who sees the job?predict
  • Build a queuewrite code
  • Choosing timeouts and retriesexplain
  • Queue vocabularymatch
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browserright here

Continue with Google

See all 12 lessons of System design