Node.js Fanout Delivery: Retry Queues, Cron Timing, and Dead Letters

Short answer: use a queue for the first delivery attempt and bounded retries, then use a small cron sweep to find records that never reached a terminal state. Put exhausted messages in a dead-letter queue. The important choice is the idempotency key, not whether a timer is cheaper.

My concrete case is a gaming SaaS that fans out a shipment update to many subscribers. A collector's package changes from in_transit to delivered; hundreds of players may be listening for that event. One subscriber can be slow, offline, or return a 429. Retrying the whole fanout as one job makes the blast radius bigger, so each subscriber gets its own delivery record.

How should a Node.js SaaS choose queue retries, cron sweeps, and a dead-letter queue?

Start with a durable row keyed by (shipment_id, subscriber_id, event_version). The worker claims one row, sends the notification, and marks it complete only after the provider acknowledges it. A retryable failure increments attempts and stores next_attempt_at; a permanent 4xx is terminal. No magic. A timeout is neither success nor proof of failure, which is why the receiver must tolerate the same idempotency key more than once.

A queue gives prompt work and backoff without polling every subscriber. Cron still has a narrow job: periodically select rows whose next_attempt_at is due and whose lease expired, then enqueue them. That sweep repairs a lost acknowledgement or a worker process that died between the send and the database update. It should not be the main delivery clock.

The dead-letter queue is an audit boundary, not a trash can. Ship it. Keep the original event, subscriber, attempt count, last status, and a reason that an operator can act on. Replaying a dead letter must create the same idempotency key, otherwise a support click can send a duplicate shipment notice.

The smallest working implementation

The following worker uses generic queue interfaces so the policy can run on a hosted queue, a self-managed broker, or a database-backed adapter. The adapter should acknowledge a message only after deliver returns.

type Delivery = { shipmentId: string; subscriberId: string; eventVersion: number; attempts: number; nextAttemptAt: number; }; type Result = { status: number }; const MAX_ATTEMPTS = 6; const BACKOFF_MS = [30_000, 120_000, 600_000, 1_800_000, 3_600_000]; function idempotencyKey(d: Delivery): string { return `shipment:${d.shipmentId}:subscriber:${d.subscriberId}:v:${d.eventVersion}`; } function retryAt(attempt: number, now = Date.now()): number { const slot = Math.min(attempt - 1, BACKOFF_MS.length - 1); return now + BACKOFF_MS[slot]; } async function handle(d: Delivery): Promise<"done" | "retry" | "dead"> { if (d.attempts >= MAX_ATTEMPTS) return "dead"; let result: Result; try { result = await deliver(d, idempotencyKey(d)); } catch { await reschedule({ ...d, attempts: d.attempts + 1, nextAttemptAt: retryAt(d.attempts + 1) }); return d.attempts + 1 >= MAX_ATTEMPTS ? "dead" : "retry"; } if (result.status >= 200 && result.status < 300) { await markComplete(d, idempotencyKey(d)); return "done"; } if (result.status === 429 || result.status >= 500) { await reschedule({ ...d, attempts: d.attempts + 1, nextAttemptAt: retryAt(d.attempts + 1) }); return d.attempts + 1 >= MAX_ATTEMPTS ? "dead" : "retry"; } await markPermanentFailure(d, result.status); return "dead"; } // These functions are supplied by the queue and storage adapters. declare function deliver(d: Delivery, key: string): Promise<Result>; declare function reschedule(d: Delivery): Promise<void>; declare function markComplete(d: Delivery, key: string): Promise<void>; declare function markPermanentFailure(d: Delivery, status: number): Promise<void>; 

The subtle part is the order around deliver and markComplete. A process crash after the remote side accepts the request can cause another attempt. That is expected. The receiving endpoint must deduplicate the key, or the sender needs a provider-level idempotency feature. Exactly-once delivery is not a realistic promise across two independent systems.

What changes when volume grows?

At low volume, one worker pool and one retry policy are enough. At higher volume, partition by subscriber or tenant so one noisy integration cannot consume every slot. Add a visibility lease, jitter to the backoff, and a per-destination concurrency limit. Record queue age, retry counts, dead-letter rate, and the age of the oldest pending delivery. These measurements tell me when a feature is consuming more revenue-per-hour than it returns.

I also test the ugly transitions: timeout after acceptance, duplicate queue delivery, a clock moving backward, and a cron sweep racing a worker lease. A fake timer test is useful, but one integration test against the real broker confirms acknowledgement semantics. RabbitMQ documents that an acknowledgement is separate from delivery, which is the same boundary this design relies on.

Trade-offs and the boundary of this pattern

The catch is operational surface area. A queue, a scheduler, a delivery table, and a dead-letter policy are four things to observe. Cron-only retries can be simpler for a nightly digest, where a few minutes of delay is acceptable and duplicate sends are easy to reconcile. Use that when the job is low fanout and the receiver has no idempotency support.

A queue-first design is unsuitable when work must run at an exact wall-clock time, such as a regulated draw. Use a scheduler with an explicit run ledger there, then enqueue the actual work. The ledger records the intended fire time, the actual enqueue time, and the resulting delivery ids. That extra record matters during an incident: an operator can tell the difference between a scheduler that never fired and a queue that fired but stalled. It also makes replay deliberate. A replay command should require the event version and destination, show the expected number of sends, and write an audit entry before it starts. Without those checks, a well-meaning repair can turn one missed update into a second notification for every player. It is also a poor fit for a single tiny script that has no durable database; adding brokers would cost more attention than the feature earns.

I ship weekly, so I keep the policy in one module and outsource the undifferentiated plumbing to an adapter. Your mileage may vary: the right retry delay depends on provider limits, player expectations, and how long a shipment update remains useful.

References