Skip to main content

Chapter 26 — Queues & Background Processing: Jobs, Workers, Retries, DLQ, Outbox

Part V · Distributed Systems, Messaging & Scale | Prerequisites: Ch 25 | Builds: Pulsely claim submission & provider/patient notifications moved to background workers via a queue + outbox

Earlier you made Pulsely's handlers safe to run twice: an at-least-once world is survivable once your effects converge instead of accumulate. That was the receiver's half of the bargain. This chapter is the sender's half — and the architecture that lives between them. We are going to take work out of the request path: the slow, flaky, fan-out work that has no business making a biller stare at a spinner while a clearinghouse has a bad afternoon. We push it into a durable queue, hand it to worker processes that consume it idempotently, retry it with backoff, and dead-letter it when it's hopeless. And we close the one seam that naïvely "just adding a queue" rips open: the dual-write gap between "I recorded the claim" and "I told the world," which we seal with the transactional outbox.

This is the chapter where Pulsely stops being one synchronous program and becomes a system with a request tier and a background tier that communicate through a buffer. Get the handoff right — atomic from the database to the queue, idempotent on the way out of it — and everything downstream becomes operable. Get it wrong and you get the worst bug class in this book: claims that exist but were never transmitted to the payer, with no error anywhere to tell you so — pure revenue leakage you discover at month-end reconciliation.


1. The problem: why slow work can't live in the request​

Let me put you on the pager.

POST /claims is at 4.2 seconds p99 and climbing. You open the handler and the cause is obvious in hindsight — it does everything, inline, in order:

// The handler that ate claim submission. Every line is a network call to someone who can be slow.
async function submitClaim(req, res) {
const claim = await db.insertClaim(req.body); // our DB
await clearinghouse.submit837(claim); // external clearinghouse (X12 837)
await db.markEncounterBilled(claim.encounterId); // our DB
await notify.provider(claimStatus(claim)); // notification service
await reportingIndexer.index(claim.id); // analytics / reporting index
res.json({ claimId: claim.id });
}

Five hops, three of them across a network you don't control, all on the critical path of a human waiting for a confirmation. When the clearinghouse has a slow day, claim submission gets slow — even though whether the 837 transmits has nothing to do with whether the claim was recorded. And slow submission has a signature failure mode of its own: billers double-click Submit, which (without idempotency keys) would be two claims — duplicate billing, a compliance problem, not just a UX one. The request tier's latency is now hostage to the slowest dependency in a chain of things the biller doesn't care about seeing complete right now.

The instinct is right: move the transmission out, do it "later." So someone writes this:

const claim = await db.insertClaim(req.body); // line A: record the fact
await queue.publish('claim.submitted', { id: claim.id }); // line B: announce it

And here is the trap that defines this chapter. Those are two separate writes to two separate systems with no shared transaction. Consider the process crashing — OOM kill, deploy, a node eviction — in the gap between line A and line B:

  • A commits, B never runs. The claim exists in Postgres. No event was published. No 837 transmitted, no encounter marked billed, no reporting entry. Silent, permanent inconsistency. No exception was thrown anywhere; the claim just quietly never gets submitted. You discover it weeks later when the revenue for that encounter never lands and month-end reconciliation comes up short.
  • Flip the order of the lines and you get the mirror evil: B succeeds, A's transaction rolls back. Now a worker cheerfully transmits an 837 to the payer for a claim that does not exist in your own database — a phantom claim you can't even reconcile against.

This is the dual-write problem, and it is not solved by adding a queue — it is introduced by adding a queue naïvely. Two systems of record, no atomic bridge between them.

Two more pains complete the case for doing this carefully:

Retrying inline poisons unrelated traffic. If the clearinghouse call fails and you retry it three times with backoff inside the request, you're holding an HTTP connection, an open database transaction, and a connection-pool slot (a fixed, shared set of reusable DB connections the whole server borrows from) for the whole duration. One flaky partner now drains the pool and degrades endpoints that never touch billing. Slowness becomes contagious.

Fan-out couples failure domains that should be independent. One submitted claim should trigger five side effects: transmit the 837, mark the encounter billed, create a claim-tracking record, notify the provider/biller, emit an analytics event. Do them inline and a failed analytics call can roll back — or hang — a recorded claim. That is insane on its face: the encounter's revenue is now in flight; the analytics ping is the least important thing in the building, and it's blocking everything.

🧭 Mental model. The request handler's job is to decide and durably record intent — the smallest set of writes that lets the system keep a promise later. The background tier's job is to carry out the consequences. Submission doesn't need to finish transmitting to the payer; it needs to guarantee transmission will happen. Separate "the claim is recorded" (must be synchronous, the biller is waiting) from "the payer has been told about the claim" (can be a few seconds later, nobody's staring at it).

So the real problem statement isn't "this is slow." It's: how do I move consequential work off the request path without ever losing the link between a committed fact and its consequences? The queue is half the answer. The outbox is the other half. Most teams ship the first and skip the second, and that omission is the orphaned-claim bug above.


2. The mental model: a buffer, a job, and a bridge​

Three pictures carry this whole chapter.

The queue as a buffer in time, rate, and failure​

A queue is a durable, append-mostly buffer sitting between producers (who put work in) and consumers (who take it out). Its entire value is decoupling:

  • In time — the producer is fast, the consumer can be slow; the buffer holds the difference. Claim submission returns in 80 ms; the 837 transmits 600 ms later. Nobody waited.
  • In rate — a month-end burst of 10,000 claims at close lands in the queue instantly and drains at whatever rate the workers (and the clearinghouse's submission limits) can sustain. The queue absorbs the burst as backlog, not as errors or timeouts.
  • In failure — the consumer being down is no longer the producer being down. Clearinghouse offline for ten minutes? Claims keep getting recorded; the transmit jobs pile up and flush when it recovers. The failure is contained to the transmission tier.
producers QUEUE (durable buffer) consumers
┌──────────┐ enqueue ┌───────────────────────────┐ dequeue ┌──────────┐
│ POST │ ──────────▶ │ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ ▢ │ ─────────▶ │ worker 1 │
│ /claims │ │ (jobs wait their turn) │ │ worker 2 │
└──────────┘ └───────────────────────────┘ │ worker N │
fast ───────────────────────────────────────────▶ slow / flaky / fan-out

A job is data, not a function call​

A job (or message) is a serialized description of work to do, or a fact that happened — { "type": "claim.submitted", "claimId": "clm_7f3a", "schemaVersion": 1 }. It is emphatically not a function pointer or a closure. It has to survive things an in-memory call never faces: the process restarting, a redeploy to new code, version skew where the producer is on v2 and the consumer is still on v1 mid-rollout. That constraint shapes everything about job design later (§5): small, self-describing, versioned payloads carrying IDs you re-read, not snapshots you trust.

The outbox is the atomic bridge​

The dual-write gap from §1 exists because "commit the fact" and "publish the event" are two transactions. The outbox collapses them into one. You write the event as a row in your own database, inside the same transaction as the business change. Either both commit or neither does — that's just atomicity doing its job. Then a separate relay reads those outbox rows and publishes them to the queue, retrying safely because publishing is now decoupled from the business write.

┌─────────────── ONE DB TRANSACTION ───────────────┐
│ INSERT INTO claims (...) │ ← the fact
│ INSERT INTO outbox (event_type, payload, ...) │ ← the intent to announce it
└───────────────────── commit ──────────────────────┘
│
(relay, separately)
▼
SELECT … FROM outbox WHERE not published ──publish──▶ QUEUE ──▶ workers
│
mark row published

🧭 Mental model. "At-least-once delivery + idempotent consumer = effectively-once processing." You almost never get true exactly-once at the broker. You manufacture effectively-once at the handler, using exactly the idempotency you already built. The queue's job is durability and decoupling; correctness under duplicates is your job, at the consumer.

One more framing to hold, because it prevents most design mistakes: durability, delivery, and ordering are three independent axes. Durability asks does the message survive a crash? Delivery asks how many times might I see it? Ordering asks in what sequence? You choose each one per job type, consciously. An analytics event can be lossy and unordered; a claim-state-transition must be durable and per-claim-ordered. Treating these as one knob ("reliable queue") is how you over-pay for analytics and under-protect money.


3. Theory & invariants​

A mental model tells you the shapes. Invariants tell you what must stay true or the system is wrong. These are load-bearing.

🔑 The delivery invariant: design for at-least-once. There are three delivery semantics, and only one is the honest default. At-most-once (fire-and-forget; ack before processing) may lose messages — acceptable only for pure telemetry. At-least-once (durable; ack only after success) may duplicate messages — and this is the one you design for, every time, because it's the only one a real broker gives you cheaply. Exactly-once at the transport layer is rare, expensive, and usually a lie the moment your effect touches a system outside the broker (the same myth you've already met). Build for at-least-once and absorb the duplicates; never build assuming you won't get them.

🔑 The idempotency invariant. Processing the same job N times must produce the same observable state as processing it once. You enforce this two ways: an idempotency key + dedup store (a processed_jobs table with a unique constraint, checked-and-inserted in the same transaction as the effect), or a naturally idempotent operation (set-to-a-value, upsert, conditional update) where re-running is inherently a no-op. If your handler does balance = balance + 10, you have neither, and at-least-once will eventually pay a claim twice. In healthcare this invariant is not a nicety — a duplicate claim submission is duplicate billing, a device that re-POSTs a reading storm doesn't get counted five times, and an inbound remit callback that retries doesn't post the payment twice.

🔑 The acknowledgement contract. A message leaves the queue only after the consumer acks it. This single rule decides your loss-vs-duplicate tradeoff. Ack-on-receive (ack first, then process) risks loss: crash after ack, before the work is done, and the job is gone with no trace. Ack-after-success (process fully, then ack) risks duplicates: crash after the work but before the ack, and the broker redelivers. The correct default is ack-after-success — you've already made the handler idempotent (above), so a duplicate is boring, whereas a silent loss is a data-loss incident.

🔑 The visibility-timeout (lease) invariant. When a worker picks up a message, the broker makes it invisible to other workers for a visibility timeout (SQS) / hands out a lease (the general term). If the worker acks within that window, the message is deleted. If it doesn't — because it crashed, or is just slow — the broker assumes failure and redelivers to someone else. The deadly corollary: the timeout must exceed worst-case processing time. Set it too short and a slow-but-alive worker has its job redelivered to a second worker while the first is still running it — concurrent duplicate processing of the same job. The lease is a bet on "dead vs slow," and you lose the bet by underestimating slow.

🔑 The forward-progress invariant: bounded retries + DLQ. A poison message is a job that deterministically fails every attempt — a malformed 837 payload, a referenced encounter that no longer exists, a bug in the handler. Retry it forever and it pins a worker at 100% CPU, climbs the retry counter to infinity, and blocks progress while looking healthy. The invariant that guarantees forward progress: cap attempts (say, 5), and after the cap, move the message to a dead-letter queue (DLQ) — a separate queue for jobs that exhausted their retries. The DLQ is the bounded "we gave up, a human should look" bin. A queue without one cannot make progress past its first poison message.

🔑 The outbox invariant. The event row and the business state change share one transaction boundary — so either both commit or neither does, eliminating the dual-write window entirely. The relay's subsequent publish is retryable and idempotent (publish, then mark the row sent; a crash before "mark sent" just republishes), which means duplicate publishes are expected and absorbed downstream by the idempotency invariant above. The outbox doesn't give you exactly-once publishing — it gives you at-least-once publishing with no lost events, which combined with idempotent consumers is exactly what you want.

🔑 The ordering invariant: order is not free. FIFO across the whole queue requires either a single consumer or per-key serialization (all messages for one entity routed to one consumer, processed in sequence). Parallel consumers inherently reorder — that's the price of parallelism. The senior realization: most systems need per-entity ordering, not global ordering. You don't need every Pulsely event in one global sequence; you need one claim's claim.submitted to land before that claim's claim.voided, and one encounter's encounter.signed before that encounter's encounter.billed. Buy ordering only at the entity granularity you actually require, and pay for it with reduced parallelism only there.

📎 Borrowed on credit: log-based streaming. Everything in this chapter is the queue model — point-to-point, destructive read (a message is consumed once and gone), the broker tracking who's done. There is a fundamentally different primitive: the log (Kafka), where reads are non-destructive, many independent consumers each hold their own cursor, and you can replay history. The distinction is sharp and it matters: a queue is a mailbox (read it, it's gone); a log is a ledger (read it, it's still there for the next reader). We name it here so you don't reach for Kafka when a queue is correct — Chapter 27 builds the log, event-driven architecture, CQRS, and sagas in full. This chapter: queues. That one: logs.

Pin the vocabulary, because the rest of the chapter assumes it: producer / consumer, broker, exchange / routing key (Rabbit) vs topic / queue, ack / nack (negative ack = "I failed, requeue or dead-letter"), redelivery, backoff, jitter, DLQ, lease / visibility timeout, prefetch / in-flight limit, consumer group.


4. Under the hood: brokers, workers, and the relay​

Let's open the boxes. Two broker philosophies, the Node worker anatomy, the outbox relay, and the backoff math.

Two broker models: smart broker vs smart consumer​

RabbitMQ — smart broker, dumb consumer. Producers publish to an exchange, not a queue. The exchange routes by routing key and bindings to one or more queues. The broker holds the routing intelligence; the consumer just drains a queue.

// RabbitMQ: producer publishes to an exchange with a routing key; the broker fans out.
await channel.assertExchange('pulsely.claims', 'topic', { durable: true });
channel.publish('pulsely.claims', 'claim.submitted',
Buffer.from(JSON.stringify({ claimId })),
{ persistent: true }); // persistent = survive broker restart (durability axis)

// Consumer: explicit ack AFTER success; prefetch caps unacked-in-flight.
await channel.prefetch(20); // at most 20 unacked messages at once
channel.consume('claim.transmit', async (msg) => {
try {
await transmitClaim(JSON.parse(msg.content.toString()));
channel.ack(msg); // ack-after-success
} catch (err) {
channel.nack(msg, false, false); // requeue=false → route to DLX
}
});

Rabbit gives you, beyond a plain ack, a handful of broker-level features. Each is one undefined term until you see it, so here they are one per line:

  • Per-message TTL — a time-to-live after which an unconsumed message expires on its own.
  • Dead-letter exchange (DLX) — a side queue Rabbit republishes a message into when you reject it or it expires; the broker-config version of the DLQ from §3. You wire it up with the x-dead-letter-exchange queue argument.
  • nack (negative-ack = "tell the broker I failed, don't just stay silent") — a nacked message can be requeued or routed to the DLX.
  • Delayed messages — via the delayed-message plugin, or the classic TTL-then-DLX trick.
  • Prefetch (the Rabbit setting name is basic.qos) — the cap on how many un-acked messages one consumer holds at once.

SQS — dumb broker, smart consumer. No routing, no exchanges. You poll. Two flavors: standard (best-effort ordering, at-least-once) and FIFO (strict order per MessageGroupId, plus a built-in dedup window for "exactly-once-ish"). The mechanics live in attributes:

// SQS standard: poll, process, delete. "Delete" IS the ack here.
const { Messages } = await sqs.receiveMessage({
QueueUrl, MaxNumberOfMessages: 10, WaitTimeSeconds: 20, // long polling: cut empty receives
VisibilityTimeout: 60, // lease window
});
for (const m of Messages ?? []) {
await transmitClaim(JSON.parse(m.Body)); // do the work first
await sqs.deleteMessage({ QueueUrl, ReceiptHandle: m.ReceiptHandle }); // then ack
}

SQS gives you VisibilityTimeout (the lease), maxReceiveCount + a redrive policy that auto-moves a message to a DLQ after N receives, DelaySeconds for delayed delivery, and long polling to avoid burning money on empty receives. Notice the inversion: with SQS you own the receive loop and the DLQ logic is broker config; with Rabbit the broker owns routing and DLX.

The Node/TS lab: BullMQ on Redis​

For the Pulsely lab we use BullMQ (a Redis-backed job queue) because you almost certainly already run Redis, and it's Node-native. Redis gives you a reliable-queue structure plus a delayed-set, which is exactly enough.

import { Queue, Worker } from 'bullmq';
const connection = { host: 'redis', port: 6379 };

// Producer side (the relay will call this).
const claimQueue = new Queue('claim.submitted', { connection });
await claimQueue.add('transmit', { claimId }, {
attempts: 5, // max attempts → then DLQ (failed set)
backoff: { type: 'exponential', delay: 1000 },// 1s, 2s, 4s, 8s, 16s (+ jitter, below)
removeOnComplete: 1000, // keep last 1000 for inspection
removeOnFail: false, // KEEP failures = your DLQ
});

// Worker side: long-lived process, concurrency-bounded.
new Worker('claim.submitted', async (job) => {
await transmitClaim(job.data.claimId); // throwing → retry; exhausting → "failed" (DLQ)
}, { connection, concurrency: 20 });

BullMQ's "failed" set is your DLQ; its repeatable/cron jobs cover scheduling; QueueEvents streams lifecycle events for metrics. The same shape talks to SQS via the AWS SDK consumer loop, or to Rabbit via amqplib — the concepts (attempts, backoff, lease, DLQ, concurrency) are identical; only the API differs.

The outbox relay — two mechanisms​

The outbox table is written inside the claim transaction. A separate relay moves rows to the queue. Two ways to build the relay:

(a) Polling publisher — what we use for Pulsely. A loop selects unpublished rows, publishes, marks them sent. The critical SQL is FOR UPDATE SKIP LOCKED so multiple relay instances don't fight over the same rows.

In plain terms: FOR UPDATE tells Postgres "lock these rows, I'm about to work on them," and SKIP LOCKED says "if another relay already locked a row, don't wait for it — just skip past to the next free one." So two relays running at once each scoop up a different batch instead of colliding. If you've used optimistic updates in the UI — two browser tabs racing to claim the same item, and the loser silently moves on to the next — this is the same claim-it-or-skip-it idea, enforced by the database.

-- Claim a batch no other relay instance is touching.
SELECT id, event_type, payload
FROM outbox
WHERE published_at IS NULL
ORDER BY id
LIMIT 100
FOR UPDATE SKIP LOCKED; -- concurrent relays each grab DIFFERENT rows, no blocking
// Relay loop: claim → publish → mark sent. Crash before "mark sent" → republish (idempotent downstream).
async function relayOnce() {
await db.tx(async (t) => {
const rows = await t.query(CLAIM_SQL);
for (const row of rows) {
await claimQueue.add(row.event_type, row.payload, { attempts: 5, /* … */ });
await t.query('UPDATE outbox SET published_at = now() WHERE id = $1', [row.id]);
}
});
}

Simple, zero new infrastructure, slightly laggy (publish latency = poll interval).

(b) Log-tailing / CDC. CDC (change-data-capture) means: instead of your app polling the outbox table, a tool watches the database's own internal change log — Postgres's WAL (write-ahead log), the append-only file where every committed change is recorded before it's applied — and emits an event the instant a new outbox row is written. Debezium is the common tool that does this: near-zero lag, no app polling, at the cost of running Debezium plus a connector. We teach (a) for Pulsely and name (b) as the scale path when polling lag or DB load becomes the bottleneck.

Worker anatomy and concurrency​

A worker is a long-lived process — not a Lambda spun up per message — that connects to the broker, sets its prefetch/concurrency, and loops: pull a job, run the handler, ack or nack. Workers are a separate deployable from the API, deliberately: they scale independently (you might need 2 API pods and 20 transmit workers, or vice versa), they isolate blast radius (a worker OOM doesn't take down claim entry), and they have a different resource profile.

Concurrency in Node works the way you've already seen: a single worker process handles many I/O-bound jobs concurrently on the event loop — twenty in-flight await clearinghouse.submit837(...) calls overlap fine, because each is mostly waiting. Prefetch / concurrency caps the in-flight count. But a CPU-bound job (rendering a PDF statement, parsing a large HL7 batch) blocks the event loop and starves the others — those need multiple processes or worker_threads. And beware: too-high prefetch + slow jobs gives you uneven load (one greedy worker hoards messages) and long redelivery tails when it dies holding fifty leases.

🏭 The JVM lens, because it teaches the principle. (Skippable — the payoff, not the Java vocabulary.) Spring expresses the exact same outbox idea as a commit-phase hook: @TransactionalEventListener(phase = AFTER_COMMIT) fires your "publish" code only after the transaction commits — tying the side effect to the commit boundary, never to the in-flight transaction. And @RabbitListener with a RetryTemplate + RepublishMessageRecoverer is declarative retry→DLQ. Different syntax, identical law: tie side effects to the commit boundary, and bound your retries into a dead-letter sink. If you internalize that law, you can re-derive the machinery in any framework.

Backoff math: capped exponential with jitter​

When a downstream is down, naïve fixed-interval retries from a thousand workers hit it in lockstep — a thundering herd that re-kills it the instant it recovers. The fix is exponential backoff with a cap, plus jitter:

// delay = min(cap, base * 2^attempt), then FULL jitter to break synchronization.
function backoffMs(attempt: number, base = 1000, cap = 30_000): number {
const exp = Math.min(cap, base * 2 ** attempt);
return Math.random() * exp; // full jitter: random(0, exp)
}
// attempt 0→~0-1s, 1→0-2s, 2→0-4s … capped at 30s, spread randomly.

The jitter is not cosmetic. Without it, retries synchronize and the herd reconverges on every recovery. Full jitter (random(0, delay)) spreads the retries across the whole window, so a recovering downstream sees a smooth ramp instead of a wall. This is load-protection, not tidiness — we'll see it again in §8.

Heads-up: the earlier BullMQ config and this backoffMs helper don't match, on purpose. BullMQ's built-in type: 'exponential' gives fixed steps — 1s, 2s, 4s, no jitter. Once you have many workers retrying at once, swap in this full-jitter version as a custom backoff strategy so they don't all fire in lockstep.

🛑 What we deliberately did not explain. This chapter owns queues — point-to-point work handoff where the broker deletes a message once a worker finishes it. It does not cover the log abstraction (Kafka: retained, replayable, partition-ordered streams), event-driven architecture, sagas, or CQRS — those are Ch 27. The full claims conversation — 837 out, 277CA acknowledgement back, 835 remit with payment-or-denial, then an appeal — is a multi-step saga with compensations, and that lives there too; here we own only submitting the claim reliably. The distinction (a queue forgets; a log remembers) is the whole reason that chapter exists. The resilience patterns a worker leans on when a downstream misbehaves — circuit breakers, bulkheads, load shedding — belong to Ch 33. Here we owned the job, the retry, the DLQ, and the outbox; the stream and the safety net come next.


5. In production: the Pulsely increment​

Here is the actual refactor. We move claim submission (837 transmission to the clearinghouse, encounter billed-state transition, claim-tracking record) and all outbound notifications (provider notice, patient statement) off the synchronous POST /claims path, behind an outbox.

The synchronous handler shrinks to "record intent"​

// POST /claims — now does the SMALLEST set of writes to make a keepable promise.
async function submitClaim(req, res) {
const claim = await db.tx(async (t) => {
const c = await t.insertClaim(req.body); // the fact
await t.insertOutbox({ // the intent to announce — SAME TX
aggregateType: 'claim', aggregateId: c.id,
eventType: 'claim.submitted',
payload: { claimId: c.id, schemaVersion: 1 },
});
return c; // both commit, or neither
});
res.status(202).json({ claimId: claim.id, status: 'processing' }); // 202 Accepted, not 200
}

Two things changed. The handler now does two inserts in one transaction and returns — 837 transmission, notification, reporting are all gone from the critical path. And it returns 202 Accepted with status: 'processing', not 200 — an honest status code for "I've durably accepted this; the consequences are in flight." The client polls or subscribes for completion (realtime is the push path; a status field is the poll path).

The outbox table​

CREATE TABLE outbox (
id BIGSERIAL PRIMARY KEY, -- monotonic → ordering hint for the relay
aggregate_type TEXT NOT NULL,
aggregate_id TEXT NOT NULL,
event_type TEXT NOT NULL,
payload JSONB NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
published_at TIMESTAMPTZ, -- NULL = not yet relayed
attempts INT NOT NULL DEFAULT 0
);
-- Partial index: the relay only ever scans the unpublished tail. Cheap even when the table is huge.
CREATE INDEX outbox_unpublished ON outbox (id) WHERE published_at IS NULL;

The relay (§4) drains this with FOR UPDATE SKIP LOCKED. Note the partial index — the relay's hot query is "unpublished rows," and you don't want it scanning millions of already-sent rows.

Idempotent workers​

Each event fans out to its own worker, and each worker is idempotent — because the relay publishes at-least-once and the queue redelivers. The dedup uses the same processed_jobs pattern you've already built:

new Worker('claim.submitted', async (job) => {
const { claimId } = job.data;
await db.tx(async (t) => {
// Dedup + side effect in ONE transaction.
const inserted = await t.query(
`INSERT INTO processed_jobs (idempotency_key) VALUES ($1)
ON CONFLICT DO NOTHING RETURNING 1`,
[`transmit:${claimId}`] // or the claim control number — a natural dedup key
);
if (inserted.rowCount === 0) return; // already processed → no-op, ack normally

// Re-read CURRENT state — never trust a snapshot from enqueue time (job design rule below).
const claim = await t.getClaim(claimId);
await t.markEncounterBilled(claim.encounterId); // conditional: WHERE status = 'signed'
await t.createClaimTracking(claim.id);
await clearinghouse.submit837(claim); // idempotent on the claim control number
});
}, { connection, concurrency: 10 });

The notification worker is a second, independent consumer of the same event — so a slow clearinghouse can't delay the provider notice, and a transmission bug can't block statements. Their failure domains are now separate. (The same shape handles the inbound side too: the 271 eligibility reply, the 835 remit, and the lab-result callback each arrive as their own event and each gets an idempotent worker — a retried remit callback must never post a payment twice.)

Job design rules that survive an on-call​

  • Small payloads — IDs, not blobs. Pass { claimId, schemaVersion }, not the whole denormalized claim. The row may have changed between enqueue and processing (a correction, a void); the worker must re-read the source of truth at processing time, or it transmits a claim the biller already voided. This is the most common subtle bug in background work.
  • Self-describing and versioned. Every job carries a type and schemaVersion. During a rolling deploy the producer is on v2 while a consumer is still on v1; the version field is how the consumer knows whether it understands the payload — the same version-evolution discipline you've already met, applied to messages.
  • Retry only retryable errors. Classify exceptions. Transient — network timeout to the clearinghouse, 503, lock contention — retry. Permanent — a validation failure, an unknown payer id, a malformed 837 — dead-letter immediately, don't waste five attempts and twenty seconds proving a bad payload is still bad.
catch (err) {
if (isTransient(err)) throw err; // let the queue retry with backoff
await deadLetter(job, err); // permanent → DLQ now, alert
}

Retry / DLQ configuration​

Max attempts 5, exponential backoff with a cap and full jitter, a distinct DLQ per queue, and — the line that matters most — the DLQ is monitored and alertable. A DLQ nobody watches is a silent data-loss bin; you find the 4,000 unsubmitted claims weeks later, after the filing deadline has passed and the money is gone. Alert on DLQ depth > 0 and on oldest-message age.

Visibility-timeout tuning​

Set the lease to p99 processing time + margin. For genuinely long jobs (a bulk statement export), don't pick a huge static timeout — that delays redelivery of actually-crashed jobs by minutes. Instead heartbeat / extend the lease periodically while the job runs, so a live-but-slow worker keeps its claim and a dead one releases it fast.

Observability for a background tier​

Dashboards must show, per queue: depth, oldest-message age (the real lag signal — depth can be flat while age climbs, meaning you're stuck on a head-of-line job), in-flight count, a processing-time histogram, retry rate, and DLQ size. Structured logs keyed by jobId / idempotencyKey. And propagate the trace context from the originating request into the job, so a background failure links back to the POST /claims that spawned it — otherwise a worker error is an orphan with no story.

Operational runbooks (write these before you need them)​

  • Graceful shutdown. On SIGTERM during a deploy: stop pulling new jobs, finish in-flight ones, then exit. A worker that exits mid-job orphans work (or relies on lease redelivery, which delays it). This is the same graceful-shutdown discipline, and it's non-negotiable for workers.
  • Drain before deploy, pause consumers without losing messages, and replay the DLQ after a bug fix — re-publish the dead-lettered jobs with a fresh idempotency context so the fix gets a clean run while the idempotency keys still protect against double effects.

Scheduled, delayed, and cron jobs​

Two distinct needs. Delayed jobs — "send an appointment reminder in 24h" — are a single message with a delay (DelaySeconds, Rabbit TTL+DLX, BullMQ delayed set). Cron jobs — "rebuild the provider worklist every 5 minutes" — fire on a schedule. The trap with cron in a multi-replica deployment: every replica fires the same schedule, so your nightly claim-batch job runs N times. Guard it two ways — a distributed lock (Redis SET NX EX) so only one instance wins the tick, and a guard against overlapping runs (the 5-minute job that takes 7 minutes must not start a second copy on top of the first).


6. Common pitfalls​

Each as signature → fix: the symptom you'll observe, then the principle that resolves it.

Dual write. Signature: claims exist with no transmission and no provider notice after a crash; your metrics show publish_count < commit_count. Fix: the transactional outbox. Write the event row in the same transaction as the business change; never await db.commit() and await queue.publish() as two independent steps and hope both land.

Non-idempotent handler. Signature: the same claim submitted twice (duplicate billing), two provider notifications, an encounter marked billed twice after a redelivery. Fix: idempotency key + dedup table inside the effect's transaction, or conditional/upsert writes (UPDATE … WHERE status = 'signed', INSERT … ON CONFLICT DO NOTHING). Never a bare read-modify-write in application code.

Visibility timeout shorter than processing time. Signature: the same job runs on two workers simultaneously; duplicated side effects that only appear under load (when jobs run slow). Fix: set the lease above p99 processing time, or heartbeat-extend it for long jobs. The lease is your "dead vs slow" bet — don't let slow look like dead.

Unbounded retries / no DLQ. Signature: one poison message pins a worker at 100% CPU; queue depth climbs while every health check is green. Fix: max attempts + a monitored DLQ + transient-vs-permanent error classification. Forward progress requires a "give up" path.

Huge payloads / stale data in the job. Signature: a worker acts on data that changed since enqueue — transmits a claim the biller voided after enqueue. Fix: pass IDs, re-read current state at processing time. The job is a pointer to a fact, not a snapshot of it.

Ack-before-work. Signature: jobs vanish on worker crash; silent loss with no DLQ entry (because the message was already deleted). Fix: ack only after successful processing. Duplicates are cheap (you're idempotent); silent loss is a data-loss incident.

Assuming FIFO with parallel consumers. Signature: claim.voided is processed before claim.submitted; the state machine throws "cannot void a non-existent claim." Fix: route per-entity events to a single ordered partition/group key, or make handlers commutative / order-tolerant. Parallelism reorders — that's not a bug, it's the deal.

Cron double-fire across instances. Signature: the nightly claim-batch job runs N times on an N-replica deploy; N times the submissions, N duplicate claims. Fix: a distributed lock or single-leader election gating the scheduled trigger, plus an overlap guard.

Unmonitored DLQ. Signature: weeks later you discover 4,000 unsubmitted claims sitting in a queue nobody dashboards. Fix: alert on DLQ depth > 0 and oldest-message age. A DLQ is only a safety net if someone is watching it.


7. Tradeoffs​

Senior engineering is naming the spectrum and saying why you stand where you stand.

Sync ↔ async, per operation. Push to background when work is slow, failure-prone, fan-out, or not needed for the response (the 837 transmission, the reporting index, the analytics). Keep it synchronous when the caller must see the result, or when strong read-after-write is required (the biller must immediately see "claim recorded"). Reverse it when: a job that's always fast and must be reflected immediately — a sub-50ms write the UI reads back instantly — is just complexity for nothing; put it back inline. The cost of async is always eventual consistency plus operational surface; only pay it when the work earns it.

Outbox (polling relay) ↔ CDC / log-tailing. Polling is zero new infrastructure but adds publish latency (poll interval) and a steady DB read load. CDC (Debezium) is near-real-time but adds operational weight — a connector, often Kafka-Connect, to run and monitor. Reverse to CDC when outbox lag or the polling query's DB load becomes the actual bottleneck. Start with polling; you'll know when you've outgrown it because the lag metric will tell you.

Outbox ↔ "just publish and accept rare loss." Acceptable for low-value analytics events (a dropped page-view doesn't owe anyone money). Never for money or clinical fulfillment — a lost claim is lost revenue, a lost lab order is a patient who never gets tested. The ADR below is scoped only to consequential events — don't outbox your telemetry, don't fire-and-forget your claim submissions.

RabbitMQ ↔ SQS ↔ Redis/BullMQ. Rabbit for rich routing and on-prem control; SQS for zero-ops managed scale on AWS; BullMQ/Redis when you already run Redis and want a simple Node-native job system. Reverse off Redis when you need true broker-grade durability and routing — Redis durability is a configuration you must get right (appendonly, fsync policy), and a misconfigured Redis can lose jobs a real broker wouldn't.

Standard ↔ FIFO queue. FIFO buys ordering + dedup, at lower throughput and per-group serialization. Choose standard + idempotent handlers unless ordering is a hard business requirement — and even then, scope the ordering to the entity (per MessageGroupId), not globally, so you only pay the serialization tax where you need it.

Few large workers ↔ many small workers. Large workers give better cache and connection reuse and coarse scaling; many small workers give fine-grained autoscaling and better fault isolation. Reverse toward more, smaller workers as job heterogeneity grows — you don't want your 200ms notification jobs stuck behind a worker pool tuned for multi-minute exports.

Effectively-once via idempotency ↔ chasing exactly-once transport. Building dedup at the handler is cheaper and more portable than depending on a broker's "exactly-once" semantics that usually don't hold across your full pipeline anyway. Manufacture correctness at the consumer; don't buy it from the wire.

🚫 A framing this book rejects. "We added a queue, so the work is reliable now." A queue without an outbox has a dual-write hole; a queue without idempotent consumers double-processes on every redelivery; a queue without a monitored DLQ silently swallows poison messages. The queue is infrastructure — it provides durability and decoupling. Reliability is something you build around it with the outbox, idempotency, bounded retries, and DLQ monitoring. "Just add RabbitMQ" is the start of the work, not the end of it.


8. Security & scale notes​

Job payloads are untrusted input at the consumer. Validate and deserialize defensively — a worker is a trust boundary just as much as an HTTP handler is. A malicious or merely buggy producer can craft a payload that crashes every worker that touches it — a self-inflicted poison-message DoS. Bounded retries + DLQ contain it (the bad message lands in the DLQ after 5 attempts instead of cycling forever), but only if you didn't disable the cap.

Keep secrets and PHI out of payloads. Messages land in DLQs, logs, and broker dashboards — all places with broader read access than your database. Pass references (claimId), and fetch the sensitive data at processing time with proper authorization. A patient's chart data or an MRN sitting in a DLQ is a reportable HIPAA breach waiting in a place you forgot to secure — treat it with the same gravity as a leaked chart.

SSRF and abuse via jobs. A "call this partner URL" or "fetch this document" job lets an attacker make your worker call internal URLs (http://169.254.169.254/... for cloud metadata, internal admin endpoints). Validate destinations against an allowlist and egress-restrict the worker network. The worker has more network reach than the public internet does — treat that reach as the liability it is.

Queue-as-amplifier and fairness. One bad enqueue loop floods the queue (a queue bomb); rate-limit producers and cap per-tenant enqueue rates so one clinic's runaway RPM-device integration — a monitor firehosing readings — can't starve every other clinic's claim submissions (the noisy-neighbor problem). Fairness in a shared queue is a design decision, not a default.

Now scale, where queues change the shape of overload:

Queues turn overload into latency, not errors. This is their superpower and their trap. A burst that would have errored synchronously instead lands in the buffer and drains slowly — so the system stays up, but the backlog (and thus end-to-end latency) grows. The consequence for monitoring: watch oldest-message age, not just depth. Depth can look stable while age climbs, which means you're falling behind on the head of the queue even as throughput looks fine. And set a max queue length / TTL so a runaway backlog doesn't consume unbounded broker memory and take the broker itself down.

Backpressure: more workers can make it worse. When the downstream (the clearinghouse, the notification provider) is the bottleneck, throwing more workers at the queue just hits the struggling downstream harder. Cap concurrency to the downstream's capacity — clearinghouses publish submission rate limits for exactly this reason — autoscale workers on backlog age but with that concurrency ceiling enforced.

📎 Borrowed on credit: circuit breakers and bulkheads. When a downstream is failing, the right move is to stop hammering it — a circuit breaker that trips open after repeated failures and lets it recover, and bulkheads that isolate one downstream's failure from the rest of the worker pool. These reliability patterns are real and load-bearing here, but they're Chapter 33's to build. We name them as the proper tool; this chapter's jitter is the lightweight cousin.

Redelivery storms after an outage. When a downstream recovers, every retry that was backing off fires — and if they fire in sync, they re-overload it instantly. This is exactly why full jitter (§4) is load-protection, not neatness: it spreads the recovering herd across the backoff window so the downstream sees a ramp, not a wall. The thundering herd is a scale property, and jitter is its cheapest defense.


9. Interview lens & exercises​

Interview questions​

Background-processing questions separate people who've operated a queue from people who've only added one.

"You write a row and publish an event — how do you make those atomic?"

  • Junior answer: "wrap both in a try/catch," or "use a distributed transaction across the DB and the broker." (The first doesn't close the crash gap; the second is a two-phase-commit blocking nightmare almost no one actually runs.)
  • Senior answer: names the dual-write failure window explicitly (crash between commit and publish → orphaned claim), proposes the transactional outbox (event row in the same DB tx), discusses relay polling vs CDC, and notes that publishing is now at-least-once, so consumers must be idempotent. The whole chain, not just "use the outbox."

"Your queue is at-least-once. How do you avoid submitting the same claim twice?"

  • Junior: "check if it already exists before processing." (A check-then-act TOCTOU race — two redeliveries both check, both find nothing, both submit.)
  • Senior: idempotency key + dedup store inside the same transaction as the effect (insert-on-conflict, let the DB serialize), or an idempotent claim control number the clearinghouse itself dedups on; and is precise about where the dedup boundary lives — same atomic boundary as the effect, or it's theater.

"A job keeps failing. Walk me through what happens."

  • Junior: "it retries until it works."
  • Senior: retry with exponential backoff + jitter, classify transient vs permanent (don't burn 5 attempts on a validation error), bounded attempts → DLQ, alert on the DLQ, replay after the fix with a fresh idempotency context. Names the poison-message-forever failure the bound prevents.

"How do you guarantee the order of events with multiple workers?"

  • Junior: "use a FIFO queue" — with no awareness of the serialization cost.
  • Senior: you generally don't guarantee global order; you partition by entity key for per-entity FIFO (all of one claim's events on one group key), or you make handlers order-tolerant / commutative. Names the throughput cost of FIFO and scopes ordering to the entity, not the topic.

"When would you NOT move work to a queue?"

  • Junior: "always queue everything."
  • Senior: when the caller needs the result synchronously, when the work is trivially fast, or when the added complexity and eventual-consistency aren't worth it. Knowing when not to add the queue is the senior signal — async is a cost, not a free win.

Exercises & the Pulsely increment​

Do these in code, not on a whiteboard. The bugs only teach when you watch them happen.

  1. Build the outbox increment. Add the outbox table. Rewrite POST /claims to insert the claim and the outbox event(s) in one transaction. Build a polling relay using FOR UPDATE SKIP LOCKED that publishes to the queue and marks rows sent. Implement claim.submitted workers for 837 transmission and provider notification, each with an idempotency key, exponential backoff + jitter, max 5 attempts, and a DLQ. This is the chapter, made real.

  2. Write the ADR: "Outbox over dual-write." Context (submission latency + lost claims). Options: (a) inline everything, (b) dual-write db.commit() then queue.publish(), (c) outbox with polling relay, (d) CDC/Debezium. Decision: (c), because it closes the dual-write window with zero new infrastructure and the relay's lag is acceptable for claim/notification timescales. Consequences: relay lag (publish latency = poll interval), and consumers must be idempotent because publish is now at-least-once. Reversal trigger: move to CDC when outbox lag exceeds X seconds or the relay query's DB load becomes material.

  3. Reproduce the dual-write bug on purpose. Implement the naïve commit()-then-publish() version. Kill the process between the two lines (a process.exit(1) after commit, before publish, will do). Observe the orphaned claim — exists in Postgres, no event, never transmitted, revenue lost. Then switch to the outbox version, kill the relay mid-flight, restart it, and prove it recovers (republishes the unsent row). Same crash, opposite outcome.

  4. Force a poison message. Enqueue a malformed 837 payload that throws every time. Verify it lands in the DLQ after 5 attempts without blocking healthy jobs flowing past it. Then write a DLQ-replay script that re-enqueues fixed messages idempotently — and confirm the idempotency keys prevent any double effect on replay.

  5. Tune a visibility timeout. Artificially slow a handler past the visibility timeout (a sleep longer than the lease). Watch the broker redeliver to a second worker while the first is still running — concurrent duplicate processing, i.e. the same claim transmitted twice. Then fix it two ways: raise the timeout above p99, and (separately) add a lease heartbeat for long jobs. Watch the duplicates disappear.


Key takeaways​

  • The request path's job is to decide and durably record intent; the background path carries out the consequences. Move slow, flaky, or fan-out work off the request — but never lose the link between a committed fact and its consequences.
  • A queue decouples producer and consumer in time, rate, and failure. A job is serialized data (IDs + version), not a function pointer — it must survive restarts and version skew.
  • Design for at-least-once delivery, ack after success, and make every consumer idempotent: at-least-once + idempotent consumer = effectively-once processing. In healthcare that idempotency is life-or-death — a duplicate claim, a re-POSTing device, a retried remit callback must all converge, not accumulate.
  • The transactional outbox closes the dual-write hole: write the event row in the same DB transaction as the business change, then relay it to the queue (polling now, CDC at scale). Publish becomes at-least-once, which your idempotent consumers already absorb.
  • Bounded retries + a monitored DLQ guarantee forward progress past poison messages. The visibility timeout must exceed p99 processing time, or slow looks like dead and you double-process.
  • Exponential backoff with full jitter is load-protection — it prevents the thundering-herd retry storm when a downstream recovers.
  • Queues turn overload into latency, not errors: monitor oldest-message age, cap concurrency to the downstream's capacity, and watch the DLQ. This is the queue (destructive, point-to-point); the log (replayable, multi-reader) is the next chapter.

← Previous: Ch 25 — Idempotency & Delivery Semantics · Up: Part V overview · Master TOC · Next: Ch 27 — Log-Based Streaming & EDA →