BT San Technology

8 June 2026

Background jobs and queues: moving heavy work off the web app screen

27 min read · Websites and web apps

Illustration: a laptop showing a list of background jobs with running and done states, with a server rack and network cables behind
AI-generated illustration

You click Send invoice and the page spins for thirty seconds because the system is building a PDF, then sending an email, then syncing to the accounting system. The user clicks again because it seems stuck, and the customer gets two emails. In another case, the accounting service is down for ten minutes, and the jobs that tried to call it vanish silently without anyone knowing. Both problems are fixed by moving the heavy work off the screen and into the background. But a job queue written the simple way creates a new set of problems.

This article builds a small job queue that handles those problems. It uses TypeScript that Node 24 runs directly and the node:sqlite module that ships with Node, so there is nothing to install. It has code, real output and tests. A manager can read the explanations and tables and see what to ask the development team. An engineer can run it as is.

The real problem: background jobs that get lost, duplicated or loop forever

Doing work later does not make it safe by itself. It only moves where the problem happens, from the screen the user sees to a job in a queue nobody watches. Consider three hypothetical scenarios. They are not projects from any BT San customer.

  • An export company sends monthly invoices to 400 customers: the process that builds the PDFs is restarted in the middle of a build. The job is no longer in the queue but never finished. One customer never receives an invoice, and nobody knows until the day payment is chased.
  • A clinic sends appointment confirmation emails through an outside mail service: the service answers 503 for a short while. If the system retries every second from every job at once, it piles onto a service that is already struggling. If it never retries, all the emails from that period are lost.
  • An online store syncs orders to the accounting system: one order has a malformed format and fails no matter how many times it is retried. If the queue retries without limit, it loops and eats resources forever. If it is dropped silently, that day's sales do not match the books.

In summary, the queue must answer four questions. Where does a job go if the worker that took it dies midway? How do we avoid sending twice when we retry? How far apart should retries be? And where is a job that can never succeed kept so a person can look at it?

How job queues generally work: what the documentation says

All the ideas in this article already exist in ready-made queue services. This table summarizes what the documentation says, so our example rests on the same ideas.

TopicWhat the documentation saysEffect on our code
lease / visibility timeoutAmazon SQS: when a consumer receives a message, the message stays in the queue but is invisible to others for the visibility timeout (default 30 seconds). If it is not deleted before the time runs out, whether the app fails or crashes, the message returns for another consumer to receive.A claimed job needs an expiry time. After it passes, someone else can claim the job.
Duplicates are possibleAmazon SQS says it uses an at-least-once delivery model, so it does not guarantee that a message will not be delivered again, even within the visibility timeout.The job handler must be safe to run twice.
Setting the time correctlyAmazon SQS recommends setting it from the time the job really takes. If it is too high, a crashed job comes back slowly. A heartbeat can extend it, but there is a 12-hour ceiling.A lease that is too short makes jobs overlap. One that is too long makes recovery slow.
dead-letterAmazon SQS: set maxReceiveCount to the number of times a consumer may receive a message before it moves to the dead-letter queue, which separates messages that could not be processed so they can be analyzed. It recommends keeping the DLQ's retention longer than the main queue's.Count how many times a job was claimed. When the limit is reached, move it to a separate table.
Retry and jitterAWS Builders' Library: backoff increases the wait exponentially each time, usually with a cap, and adds jitter to spread out the retries so that everyone does not return at once and overload the service again.Wait = base x 2 to the power of the attempt, cut off by the cap, then randomize part of it.
idempotencyAWS Builders' Library: an operation with side effects can be retried safely only if it is idempotent, meaning the side effect happens once no matter how many times it is retried.Use a key to prevent inserting the same job twice, and make the job handler guard against duplicates itself.
Defaults of ready-made queuesCloudflare Queues: a failed delivery is retried three times (max_retries defaults to 3) and then deleted, unless a dead letter queue is set, in which case it is written there instead. Each message can be delayed up to 24 hours.Each service has different defaults. Read the ones for the service you use.
Summary of the Amazon SQS, AWS Builders' Library and Cloudflare Queues documentation as accessed on 2026-11-21. For real details, read the documentation of the service you use.

Overview of the example

The example is in the examples/background-job-queue-retry-business-web/ folder. It uses node:sqlite, built into Node 24, and keeps the queue in memory. The Node documentation says this module no longer needs a flag but is still experimental (the latest documentation page we opened lists it as a release candidate), so we run it with --no-warnings to silence the warning. The example uses RETURNING in an UPDATE, which the SQLite documentation says is available from version 3.35.0. The test machine has SQLite 3.53.4.

FileRole
backoff.tsA seeded random generator, a simulated clock, and the backoff formula with jitter
queue.tsThe jobs and dead-letter tables, plus enqueue, claim, complete and fail
handlers.tsSimulated job handlers: invoice email, PDF build, accounting sync, and a crash simulator
data/jobs.jsonSample jobs, including a duplicate key, an empty key, a bad email, a job where the worker crashes, and a transient failure
demo.tsTwo workers stepping through simulated time, printing every event
queue.test.tsTests run with node --test

Step 1: the jobs table and duplicate prevention

The main table stores the status (queued, running or done), the number of times the job was claimed, the time the job is ready to run, and the time its lease expires. The idem_key column is UNIQUE, so the database itself prevents duplicates. There is no checking in code that could leave a gap for two requests to slip in between. Times in the example are milliseconds from a simulated clock.

queue.ts · lines 21–43
export function openQueue(clock: Clock, rng: () => number): Queue {
  const db = new DatabaseSync(":memory:");
  db.exec(`
    CREATE TABLE jobs (
      id INTEGER PRIMARY KEY,
      idem_key TEXT NOT NULL UNIQUE,
      kind TEXT NOT NULL,
      payload TEXT NOT NULL,
      status TEXT NOT NULL DEFAULT 'queued' CHECK (status IN ('queued','running','done')),
      attempts INTEGER NOT NULL DEFAULT 0,
      max_attempts INTEGER NOT NULL,
      run_at INTEGER NOT NULL,
      lease_until INTEGER,
      lease_owner TEXT,
      last_error TEXT
    );
    CREATE TABLE dead_jobs (
      id INTEGER PRIMARY KEY, idem_key TEXT NOT NULL, kind TEXT NOT NULL, payload TEXT NOT NULL,
      attempts INTEGER NOT NULL, last_error TEXT, died_at INTEGER NOT NULL
    );
  `);
  return { db, clock, rng };
}
queue.ts: the jobs table, the dead_jobs table, and UNIQUE on idem_key

enqueue uses ON CONFLICT DO NOTHING and then checks whether a row was inserted. If the key is a duplicate, it returns the id of the existing job. Clicking Send invoice twice therefore produces one job. The key should be tied to a business intent, such as the invoice number plus the job type, and not a random number generated fresh every time. Otherwise duplicates can still happen as before.

queue.ts · lines 45–55
/** ใส่งานเข้าคิว key ซ้ำ = ไม่ใส่ซ้ำ และได้ id ของงานเดิมกลับไป */
export function enqueue(q: Queue, key: string, kind: string, payload: unknown, maxAttempts = 4, delayMs = 0) {
  if (!key.trim()) throw new Error("idempotency key ว่าง");
  const r = q.db.prepare(
    `INSERT INTO jobs (idem_key, kind, payload, max_attempts, run_at) VALUES (?, ?, ?, ?, ?)
     ON CONFLICT(idem_key) DO NOTHING`,
  ).run(key, kind, JSON.stringify(payload), maxAttempts, q.clock.now() + delayMs);
  const row = q.db.prepare("SELECT id FROM jobs WHERE idem_key = ?").get(key) as { id: number } | undefined;
  // งานที่ทำเสร็จแล้วยังอยู่ในตาราง (status done) จึงกันซ้ำได้ต่อเนื่อง; งานที่ตายแล้วย้ายไป dead_jobs
  return { id: row ? Number(row.id) : null, duplicate: Number(r.changes) === 0 };
}
queue.ts: enqueue prevents duplicates by key and rejects an empty key

Step 2: claim a job with an atomic lease

Homemade queues often break at one point: they SELECT a free job and then UPDATE it to say it is taken. Between those two statements, another worker can claim the same job. Here it is combined into a single UPDATE that picks the job with a subquery and returns the row with RETURNING, which the SQLite documentation says gives the values after the update. The database therefore decides who gets the job.

The selection condition has two cases: a job that is waiting and due, and a job whose status is running but whose lease has expired. The second is the mechanism that recovers jobs from crashed workers, with no separate watchdog needed. The claim count goes up every time, including the times a worker crashed, so a job that keeps crashing workers does not loop forever.

queue.ts · lines 82–97
/** หยิบงานหนึ่งชิ้นแบบอะตอมมิก: งานที่ถึงเวลา หรืองานที่ lease หมดอายุ (worker เดิมน่าจะล่ม) */
export function claim(q: Queue, worker: string, leaseMs: number): Job | null {
  sweepDead(q);
  const now = q.clock.now();
  const row = q.db.prepare(
    `UPDATE jobs SET
        last_error = CASE WHEN status = 'running' THEN 'lease หมดอายุ (เจ้าของเดิม ' || lease_owner || ')' ELSE last_error END,
        status = 'running', lease_owner = ?, lease_until = ?, attempts = attempts + 1
      WHERE id = (
        SELECT id FROM jobs
         WHERE (status = 'queued' AND run_at <= ?) OR (status = 'running' AND lease_until <= ?)
         ORDER BY run_at, id LIMIT 1)
      RETURNING *`,
  ).get(worker, now + leaseMs, now, now) as Job | undefined;
  return row ? { ...row, id: Number(row.id) } : null;
}
queue.ts claim: one UPDATE that selects, locks and returns the job

On the finishing side, complete checks that the caller still owns the lease. If a worker is so slow that its lease expires and someone else takes over, it gets false and does not overwrite the result. This is the last guard against a ghost worker that wakes up later. But side effects it already caused, such as an email already sent, cannot be undone, so Step 4 is still needed.

Step 3: retry with backoff and jitter, then send to dead-letter

When the job handler throws an error, fail checks how many times the job has been claimed. If it has not reached the maximum, it sets the status back to queued with a run_at in the future according to the backoff. If the limit is reached, it moves the row to dead_jobs in a single transaction. If the move fails halfway, the job is neither lost nor in both places.

queue.ts · lines 99–120
/** จบงาน: สำเร็จเฉพาะผู้ที่ยังถือ lease อยู่ ผู้ที่ lease ถูกแย่งไปแล้วจะได้ false */
export function complete(q: Queue, id: number, worker: string): boolean {
  const r = q.db.prepare(
    "UPDATE jobs SET status = 'done', lease_until = NULL WHERE id = ? AND status = 'running' AND lease_owner = ?",
  ).run(id, worker);
  return Number(r.changes) === 1;
}

/** รายงานล้มเหลว: ยังเหลือโอกาส = ตั้งเวลาลองใหม่ด้วย backoff, ครบแล้ว = dead-letter */
export function fail(q: Queue, id: number, worker: string, error: string): "retry" | "dead" | "lost" {
  const job = q.db.prepare("SELECT * FROM jobs WHERE id = ? AND status = 'running' AND lease_owner = ?").get(id, worker) as Job | undefined;
  if (!job) return "lost";
  if (job.attempts >= job.max_attempts) {
    toDead(q, id, error);
    return "dead";
  }
  const delay = backoffMs(job.attempts, q.rng);
  q.db.prepare(
    "UPDATE jobs SET status = 'queued', run_at = ?, last_error = ?, lease_until = NULL, lease_owner = NULL WHERE id = ?",
  ).run(q.clock.now() + delay, error, id);
  return "retry";
}
queue.ts: complete checks the lease owner, and fail chooses between retry and dead-letter

The backoff formula uses a ceiling that doubles each time up to a limit, then waits at least half of the ceiling plus a random part of up to the other half. This was chosen because fully random waits can come out near zero, so a minimum is kept. The random generator uses a fixed seed so the demo runs the same way every time. A real system uses a normal random generator.

backoff.ts · lines 22–30
/**
 * Exponential backoff + jitter แบบ "equal jitter":
 * เพดาน = min(cap, base * 2^(attempt-1)) แล้วรอครึ่งหนึ่งของเพดานเป็นอย่างน้อย บวกสุ่มอีกไม่เกินครึ่ง
 * attempt คือครั้งที่เพิ่งล้มเหลว (เริ่มที่ 1)
 */
export function backoffMs(attempt: number, rng: () => number, baseMs = 2000, capMs = 60000): number {
  const ceiling = Math.min(capMs, baseMs * 2 ** (attempt - 1));
  return Math.floor(ceiling / 2 + rng() * (ceiling / 2));
}
backoff.ts: exponential ceiling, a maximum cap, and jitter

The example retries every error the same way. A real system should separate permanent errors, such as a malformed email address, from transient errors, such as a 503, and send the first kind to dead-letter immediately without wasting attempts.

Step 4: the job handler must be repeatable, and recover when a worker crashes

A queue like this, and most ready-made queue services, is at-least-once. One job can run twice when a worker crashes after causing a side effect but before reporting success. So the job handler must be safe to run again. In the example, the PDF job writes a file named from the invoice number, so running it again overwrites the same file. A real email job must record that this invoice was sent, or use the mail provider's idempotency key if there is one.

handlers.ts
// ตัวจัดการงานจำลอง ไม่ส่งอีเมลหรือเรียก API จริง ใช้ payload สั่งให้เกิดเหตุการณ์ที่ต้องการ

/** โยนสิ่งนี้เมื่ออยากจำลองว่า process ตายกลางงาน (ไม่มีโอกาสรายงานผลกลับคิว) */
export class WorkerCrash extends Error {}

export type Effects = Map<string, number>;

const bump = (fx: Effects, k: string) => fx.set(k, (fx.get(k) ?? 0) + 1);

export function runJob(kind: string, payload: Record<string, unknown>, attempt: number, fx: Effects) {
  if (kind === "send_invoice_email") {
    const to = String(payload.to ?? "");
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(to)) throw new Error(`ที่อยู่อีเมลไม่ถูกต้อง: "${to}"`);
    bump(fx, `email:${payload.invoice}`);
    return;
  }
  if (kind === "make_pdf") {
    // เขียนไฟล์ชื่อจากเลขที่ใบแจ้งหนี้ รันซ้ำแล้วทับไฟล์เดิม จึงปลอดภัยต่อการทำซ้ำ
    if (payload.crashOnAttempt === attempt) throw new WorkerCrash("process ถูกฆ่ากลางงาน");
    fx.set(`pdf:${payload.invoice}`, 1);
    return;
  }
  if (kind === "sync_accounting") {
    if (attempt <= Number(payload.failFirst ?? 0)) throw new Error("503 ระบบบัญชีตอบไม่ได้ชั่วคราว");
    bump(fx, `sync:${payload.invoice}`);
    return;
  }
  throw new Error(`ไม่รู้จักประเภทงาน ${kind}`);
}
handlers.ts: simulated job handlers with a worker crash simulator (WorkerCrash)

A real run: a normal job, a mid-job crash, a transient failure and a poison job

The demo loads the jobs from data/jobs.json and has workers A and B poll for jobs every one second of simulated time. The lease is 30 seconds and a job may be tried at most 4 times. One sample job makes B crash while building a PDF. Another fails twice before succeeding. Another sends email to a malformed address forever.

demo.ts · lines 25–48
for (let tick = 0; tick < 200; tick++) {
  for (const w of [...alive]) {
    const job = claim(q, w, LEASE_MS);
    if (!job) continue;
    const note = job.last_error?.startsWith("lease") ? ` (${job.last_error})` : "";
    log(`${w} หยิบ #${job.id} ${job.idem_key} ครั้งที่ ${job.attempts}/${job.max_attempts}${note}`);
    try {
      runJob(job.kind, JSON.parse(job.payload), job.attempts, fx);
      log(`${w} ${complete(q, job.id, w) ? "สำเร็จ" : "lease ถูกแย่งไปแล้ว ผลไม่ถูกนับ"} #${job.id}`);
    } catch (e) {
      if (e instanceof WorkerCrash) {
        alive.delete(w);
        log(`${w} ล่มกลางงาน #${job.id} ไม่ได้รายงานอะไรกลับ`);
        continue;
      }
      const r = fail(q, job.id, w, (e as Error).message);
      const next = q.db.prepare("SELECT run_at FROM jobs WHERE id = ?").get(job.id) as { run_at: number } | undefined;
      log(`${w} ล้มเหลว #${job.id}: ${(e as Error).message} -> ${r}${r === "retry" ? ` ลองใหม่ที่ t=${Number(next!.run_at) / 1000}s` : ""}`);
    }
  }
  const open = q.db.prepare("SELECT COUNT(*) AS n FROM jobs WHERE status != 'done'").get() as { n: number };
  if (Number(open.n) === 0) break;
  clock.advance(1000);
}
demo.ts: the worker loop: claim, run, report the result, and handle a crash
output.txt
t=  0s  เข้าคิว #1 INV-1001:email
t=  0s  ข้าม INV-1001:email (key ซ้ำ ใช้งานเดิม id=1)
t=  0s  เข้าคิว #2 INV-1002:pdf
t=  0s  เข้าคิว #3 INV-1003:sync
t=  0s  เข้าคิว #4 INV-1004:email
t=  0s  ปฏิเสธ: idempotency key ว่าง
t=  0s  A หยิบ #1 INV-1001:email ครั้งที่ 1/4
t=  0s  A สำเร็จ #1
t=  0s  B หยิบ #2 INV-1002:pdf ครั้งที่ 1/4
t=  0s  B ล่มกลางงาน #2 ไม่ได้รายงานอะไรกลับ
t=  1s  A หยิบ #3 INV-1003:sync ครั้งที่ 1/4
t=  1s  A ล้มเหลว #3: 503 ระบบบัญชีตอบไม่ได้ชั่วคราว -> retry ลองใหม่ที่ t=2.601s
t=  2s  A หยิบ #4 INV-1004:email ครั้งที่ 1/4
t=  2s  A ล้มเหลว #4: ที่อยู่อีเมลไม่ถูกต้อง: "not-an-email" -> retry ลองใหม่ที่ t=3.448s
t=  3s  A หยิบ #3 INV-1003:sync ครั้งที่ 2/4
t=  3s  A ล้มเหลว #3: 503 ระบบบัญชีตอบไม่ได้ชั่วคราว -> retry ลองใหม่ที่ t=6.704s
t=  4s  A หยิบ #4 INV-1004:email ครั้งที่ 2/4
t=  4s  A ล้มเหลว #4: ที่อยู่อีเมลไม่ถูกต้อง: "not-an-email" -> retry ลองใหม่ที่ t=7.339s
t=  7s  A หยิบ #3 INV-1003:sync ครั้งที่ 3/4
t=  7s  A สำเร็จ #3
t=  8s  A หยิบ #4 INV-1004:email ครั้งที่ 3/4
t=  8s  A ล้มเหลว #4: ที่อยู่อีเมลไม่ถูกต้อง: "not-an-email" -> retry ลองใหม่ที่ t=12.699s
t= 13s  A หยิบ #4 INV-1004:email ครั้งที่ 4/4
t= 13s  A ล้มเหลว #4: ที่อยู่อีเมลไม่ถูกต้อง: "not-an-email" -> dead
t= 30s  A หยิบ #2 INV-1002:pdf ครั้งที่ 2/4 (lease หมดอายุ (เจ้าของเดิม B))
t= 30s  A สำเร็จ #2

สรุปสถานะ
┌─────────┬────┬──────────────────┬────────┬──────────┐
│ (index) │ id │ idem_key         │ status │ attempts │
├─────────┼────┼──────────────────┼────────┼──────────┤
│ 0       │ 1  │ 'INV-1001:email' │ 'done' │ 1        │
│ 1       │ 2  │ 'INV-1002:pdf'   │ 'done' │ 2        │
│ 2       │ 3  │ 'INV-1003:sync'  │ 'done' │ 3        │
└─────────┴────┴──────────────────┴────────┴──────────┘
dead-letter:
┌─────────┬────┬──────────────────┬──────────┬──────────────────────────────────┐
│ (index) │ id │ idem_key         │ attempts │ last_error                       │
├─────────┼────┼──────────────────┼──────────┼──────────────────────────────────┤
│ 0       │ 4  │ 'INV-1004:email' │ 4        │ 'ที่อยู่อีเมลไม่ถูกต้อง: "not-an-email"' │
└─────────┴────┴──────────────────┴──────────┴──────────────────────────────────┘
ผลข้างเคียงที่เกิดจริง: { 'email:INV-1001': 1, 'sync:INV-1003': 1, 'pdf:INV-1002': 1 }
Output from a real run on 2026-11-21 with node --no-warnings demo.ts (Node 24.21). Times in the output are simulated time from seed 42 and do not depend on the machine.

How to read the output

  1. At t=0s, invoice INV-1001 is added twice. The second is skipped and points to the original job number 1, and the empty key is rejected at the entrance. As a result the email is sent only once, according to the count at the end of the output.
  2. Job #2 (PDF build): B claims it and crashes midway. Nothing is reported back to the queue, and the job stays in running status in the meantime. Worker A continues with other work.
  3. At t=30s the lease of job #2 expires. A claims that job for the 2nd time, with a record that the previous owner was B, and completes it. The PDF side effect is one file.
  4. Job #3 (accounting sync) got a 503 twice. The waits before retrying were 1.6 seconds and then 3.7 seconds (reaching t=2.601s and t=6.704s), which grow and include a random part. The third attempt succeeded.
  5. Job #4 (bad email) failed all 4 times, with waits that grew longer, and then went into dead_jobs with the last error a person can open and read. It does not loop again, and this job caused no side effects at all.

Note that the job from the crashed B had to wait the full 30 seconds for the lease to expire. During that time the user waiting for that invoice waited too. This is the price of a long lease. Set it from the time the job really takes, so no one waits longer than necessary.

The test suite

queue.test.ts has seven tests. They use a simulated clock, so there is no waiting in real time and no assertions about speed. The tests cover: a duplicate key and an empty key; two workers cannot claim the same job; after a lease expires someone else takes over and the original owner cannot finish the job; after a failure the job must wait out the backoff before it can be claimed again; reaching the attempt limit sends it to dead-letter; a job whose worker crashes until the limit is reached goes to dead-letter; and the range of the backoff. Run it with node --no-warnings --test queue.test.ts

queue.test.ts · lines 28–38
test("lease หมดอายุแล้ว worker อื่นรับช่วง และ worker เดิมจบงานไม่ได้", () => {
  const { q, clock } = make();
  enqueue(q, "k1", "make_pdf", {});
  const j = claim(q, "A", 1000)!;
  clock.advance(1000);
  const again = claim(q, "B", 1000)!;
  assert.equal(again.id, j.id);
  assert.equal(again.attempts, 2);
  assert.equal(complete(q, j.id, "A"), false);
  assert.equal(complete(q, j.id, "B"), true);
});
queue.test.ts: a test that simulates a worker crash by advancing the clock

Putting it to real use: the database, multiple workers and monitoring

  • Database: the example is in memory. A real system uses a database with backups, such as PostgreSQL, which can claim jobs the same way with SELECT ... FOR UPDATE SKIP LOCKED in the same transaction as the status update.
  • Real multiple workers: the example takes turns inside one process. The protection against double claims relies on the database's single UPDATE statement. Test it with several real processes and set permissions for each worker.
  • Heartbeat: for jobs whose duration varies a lot, have the worker renew the lease periodically instead of setting a long lease for everything (SQS has the same approach, with its own ceiling).
  • History: keep a record of each claim, who claimed it and what the result was, to trace problems. The example keeps only the latest error.
  • Monitoring: set alerts for when dead-letter gets a new job, when the age of the oldest job in the queue passes a threshold, and when the failure rate spikes. People need a screen to view and to resend jobs from dead-letter.
  • Personal data: a payload that contains a customer's email or name sits in the queue and in dead-letter. Set a retention period and access rights for it as you would for the main data.

When to use a managed queue service instead

A queue you write yourself on the same database as the web app suits small to medium systems with at most a few thousand to tens of thousands of jobs a day, where the team wants the same transaction (saving the invoice and enqueueing the job together). But consider a managed queue service in these situations.

  • There are so many jobs that contention on reading and writing the queue table starts to affect the main database.
  • You need dead-letter redrive, alerts and metrics out of the box (the Amazon SQS documentation describes a redrive policy and notifications through CloudWatch).
  • You need long advance delays or strict ordering, where each service has different limits. For example, SQS says not to use dead-letter with FIFO if you do not want the ordering to break.
  • Nobody maintains the database and the workers around the clock, and you accept a service fee in exchange for less work.

Moving to a ready-made service does not remove the responsibility for idempotency. The job handler must still be safe to repeat, because the documentation of those services also says messages can be delivered again.

Hypothetical examples: applying this to three businesses

Sending invoices and reminder emails

Key = invoice number + job type (email, pdf). Separate the PDF build job from the email job so they can be retried independently. The email job records the result the mail provider returns, and there is a screen where sales can see which invoices are in dead-letter.

Generating large reports and PDFs

The user clicks to request a report, and the system answers immediately with a job number and status. The screen checks the status periodically (compare the choice of how to receive status in the article on polling, SSE and WebSocket). When it is done, there is a download link. A long job should have a heartbeat to extend the lease, and should write a temporary file and rename it when finished, so no half-written file is left.

Syncing orders to the accounting system or ERP

The destination system being down is normal. Backoff and jitter prevent hammering it. Use the destination's idempotency key if it has one, or keep a table mapping order numbers to destination document numbers. When there are jobs in dead-letter, you need a daily reconciliation report that compares orders with the documents that actually reached the accounting system.

Common mistakes and a checklist

  • Doing SELECT and then UPDATE as two statements with no transaction or single-statement condition, so two workers claim the same job.
  • No lease expiry, so a job from a crashed worker stays in running forever.
  • A lease shorter than the real job time, so one job runs in two workers at once even though nobody crashed.
  • Retrying immediately with no backoff or no jitter, so every job comes back at once and piles onto the destination system.
  • Unlimited retries, so a job that can never succeed keeps eating resources.
  • Silently dropping a job when the attempt limit is reached, with no dead-letter, no alert, and nobody knowing a job was lost.
  • Believing the queue guarantees exactly-once and not making the job handler repeatable.
  • Using a key that is newly randomized every time the user clicks, so duplicates cannot be prevented.
  1. Choose a key tied to a business intent (document number + job type) and put UNIQUE in the database.
  2. Claim jobs with one atomic statement, with a lease reasonably longer than the real job time.
  3. Always check the lease owner when a job finishes.
  4. Make the job handler safe to rerun, whether through an overwritable file or the destination's key.
  5. Retry with backoff + jitter and limit the number of attempts.
  6. Separate permanent errors from transient ones.
  7. Have a place for dead jobs, a screen to view them, a resend button, and alerts.
  8. Test by killing a worker in the middle of a real job, and reconcile against the destination system regularly.

Caution about this example: it is a learning example. All data is hypothetical, and it sends no real email and calls no real API. The database is in memory, the workers take turns inside one process, there is no heartbeat, there is no separation of permanent errors, and there is no screen for viewing the queue. node:sqlite is an experimental module in Node 24. The lease and backoff numbers in the article are demonstration values and must be adjusted to your real jobs.

References

  1. Amazon SQS: visibility timeout (accessed 2026-11-21)
  2. Amazon SQS: dead-letter queues (accessed 2026-11-21)
  3. AWS Builders' Library: Timeouts, retries and backoff with jitter (accessed 2026-11-21)
  4. Cloudflare Queues: batching and retries (accessed 2026-11-21)
  5. Node.js: node:sqlite (accessed 2026-11-21)
  6. SQLite: RETURNING (accessed 2026-11-21)
  7. Node.js: node:test (accessed 2026-11-21)

Add us on LINE

Scan with the LINE app on your phone

QR code to add LINE @Bankoos

LINE ID: @Bankoos

Open LINE on this computer