Lesson 12 of 14 · 18m
Work That Doesn't Belong in the Request
Email, exports, and webhooks go to a durable queue with at-least-once delivery — which makes idempotent consumers mandatory, not nice.
A request handler has one job: answer fast. Anything slow, retriable, or external — sending email, rendering a PDF, delivering a webhook, resizing an image — does not belong inside it. setTimeout(sendWelcomeEmail) inside a signup route is the junior queue: it dies when the process restarts, it never retries, and it loses work silently. That is the mental model to attack first — "async in the request path" is not a background job, it is a leak.
The queue is a durability boundary
Enqueue a job → a worker pops it → runs it → acks. The store — Redis for BullMQ, SQS with its visibility-timeout mechanics, pg-boss/graphile-worker for Postgres-backed shops — survives deploys and crashes, so the job survives too. The web process stays thin, and workers scale on their own axis: ten workers chewing a backlog while the API holds a 40 ms p99. Webhook delivery is the canonical fan-out — one event, a job per subscriber, each retried independently instead of one request thread racing ten flaky endpoints. SQS's visibility timeout is the honest version of "at least once": an un-acked job reappears in the queue, so a worker that dies mid-job doesn't take the work with it. The transactional outbox is the version juniors discover late: write the job row in the same transaction as the state change, then let a relay publish it — enqueue after COMMIT and a crash loses the job, enqueue before and a rollback leaks it.
Delivery is at-least-once — design for it
Queues do not promise exactly-once. They promise the job arrives at least once, which means your consumer will occasionally run twice. The only correct posture is idempotency: dedupe on a job key, enforce UNIQUE constraints where the job ends in a row, and carry idempotency keys to downstream APIs — Stripe's Idempotency-Key header exists precisely so a retried charge replays the original result instead of duplicating it. "It ran twice" should be a no-op, not a duplicate email or a double charge.
The lifecycle
await queue.add("welcome-email", { userId }, {
attempts: 5,
backoff: { type: "exponential", delay: 1000 },
});Every queue has the same states: pending → active → completed | failed → retry with backoff → dead-letter after N. The dead-letter queue is not a graveyard; it is the list of jobs a human must look at. Poison messages — the job that deterministically crashes the consumer — land there after retries, which is exactly why the alert belongs on DLQ depth: a DLQ nobody reads is a silent feature outage.
Scheduled work lives here too
Nightly exports, session cleanup, webhook retries: repeatable queue jobs or a single-owner cron — never setInterval inside each web replica, which runs the job N times, once per replica, precisely when you least want it. A lease row in the database — the "job lease" pattern — is how one instance claims ownership on a multi-replica deploy. Same codebase, two processes: the web serves requests, the worker consumes jobs, and both get the same SIGTERM contract from the deploy lesson — a worker's graceful shutdown means finishing or re-queueing the active job, not dying with it.
The inverse discipline matters too: enqueueing is itself a cost. A producer that enqueues faster than workers drain grows the backlog without bound — queue depth is the backpressure signal for the async world, and it belongs in your metrics next to latency. Some work never belongs in a queue at all: validation, cheap reads, anything the response itself needs — the request path is the right home for anything the caller is literally waiting on.
// Runnable: the idempotent consumer
const done = new Set();
const consume = j => done.has(j.id) ? "duplicate — noop" : (done.add(j.id), "processed");
console.log(consume({ id: "j1" }), consume({ id: "j1" }));The practice
Request path: fast work only. Everything else: a durable queue, bounded retries with backoff, idempotent consumers, a DLQ with an alert on it, exactly one scheduler — and queue depth as a first-class metric, because a growing backlog is latency nobody is reporting yet.
Was this lesson helpful?
Keep reading
Related articles from the SudoSecurity blog.
Node Runs TypeScript Now. Here's Exactly What It Strips, What It Refuses, and What It Costs
Node 24 and 26 run .ts files with no build step and no flags, by replacing types with whitespace. I ran eleven test cases, the TypeScript 7 compiler and tsx against both versions: enums, parameter properties and type imports without the type keyword all break, type errors run anyway, and...
Node.js vs Deno vs Bun: Picking the Right JavaScript Runtime in 2026
Three JavaScript runtimes. Three different philosophies on what the developer experience should feel like. Here's how they compare on performance, ecosystem, tooling, and the only decision that actually matters for production.
What is Bun? The JavaScript Runtime That Made npm Install Fast
Bun is a JavaScript runtime, package manager, bundler, and test runner in a single binary written in Zig. It's also the fastest thing to happen to JavaScript tooling in years — and it runs your existing Node.js code.
What is Deno? Ryan Dahl's Second Attempt at a JavaScript Runtime
In 2018, Ryan Dahl stood at JSConf EU and apologized for Node.js. Then he built Deno to fix the things he got wrong. Here's what changed, what the security model actually looks like, and whether switching is worth it.