Skip to content

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?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.