Skip to content

feat(queue): replay dead letters back onto their queue from the admin API - #1776

Open
fenos wants to merge 4 commits into
masterfrom
fenos/feat/admin-dlq-replay
Open

fenos wants to merge 4 commits into
masterfrom
fenos/feat/admin-dlq-replay

Conversation

@fenos

@fenos fenos commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

What

An admin endpoint to replay a queue's dead letters back onto it, paced so its workers are not swamped. The move itself is part of the generic queue adapter contract, so it works the same on pg-boss and SQS.

Endpoints

  • GET /queue/dead-letters: every queue with a dead-letter queue of its own, with how many dead letters it holds (fullest first) and how busy the queue it would be replayed onto is right now (outstanding, what maxBacklog is measured against). Counts are the engine's sampled gauges, approximate on SQS.
  • POST /queue/dead-letters/replay:
field default
queue required the queue to replay onto; its own dead-letter queue is the source
limit required the most dead letters this replay moves (1 to 100,000)
batchSize 100 the most one round moves (up to 1,000)
delaySeconds 5 the pause between rounds
maxBacklog 1,000 a round moves nothing while the queue has this many messages waiting, running or due for a retry
maxMinutes 60 the replay stops at this limit, whatever is left

How it avoids storming workers

The replay runs in the background as a chain of ReplayDeadLetters jobs, one round per job (the same shape as the v10 to SQS move). Each round moves at most min(batchSize, what is left of limit, room under maxBacklog), so the queue never gets more than maxBacklog piled onto it, whatever the pace or however many replays run at once. A round with no room moves nothing and the next one waits at least 15s. The chain ends at the limit, on an empty dead-letter queue, or at maxMinutes.

Replayed messages arrive as fresh messages (attempt 1, same payload, headers and key), so they get their whole retry budget again. One that fails again works through that budget and lands back in the dead-letter queue.

How

Adapter contract (src/internal/queue/manager)

  • ProducerAdapter.redrive?(deadLetter, target, { limit, queues, signal }) returns { moved, remaining }. Optional, like stats.
  • Every manager shape gets queue.redrive(queue, { limit }). It resolves the queue's declared retry.deadLetter and rejects a dead-letter queue shared by several queues (not every engine records which queue a message came from). The sync queue and adapters without the capability reject with NotSupportedError('redrive').

Adapters

  • pg-boss: pg-boss's own redrive(). One transaction per call, so nothing is lost or duplicated. It keeps the singleton key and trace context. A job the target's policy refuses (an exclusive queue that already holds that key) is failed in place in the dead-letter queue, with the reason as its output. previewRedrive() with limit 1 answers remaining.
  • SQS: receive ten at a time (1s long poll, 60s hold), copy through the adapter's own send (batching, size checks, service-fault retries), delete only the dead letters whose copy was confirmed. At-least-once: a crash between copy and delete re-copies. A FIFO target drops that copy within five minutes, because the copy's deduplication id is derived from the dead letter's id. Works for dead letters the adapter copied and ones SQS's redrive policy moved.
  • memory: the reference implementation.

Storage (src/storage/events/dead-letters/replay-dead-letters.ts)

  • The ReplayDeadLetters event and handler on a new replay-dead-letters queue (system retry posture, with its own dead-letter queue).
  • replayRound / nextReplayRoundDelay / outstandingOf hold the pacing logic. Outstanding is backlog plus in-flight plus retries due now. Retries parked for later are left out, so a queue with a long-backoff retry pile is not throttled forever.

Object delete cleanup retries (object-admin-delete, object-admin-delete-batch)

  • These fail mostly when S3 throttles (SlowDown). Under the default policy their first six retries landed within about a minute, back onto the throttled prefix, and every message of a failed DeleteObjects batch came back at the same moment.
  • RetryPolicy gains an opt-in jitter: each delay is spread at random between half and all of the capped curve. The manager's delay is what both engines apply (it overwrites pg-boss's own start_after on a handler failure), so this works on pg-boss and SQS alike. Other queues are unchanged.
  • The two queues use a new cleanupRetry: 30s doubling to 6h, jittered, on the same 21 attempts as the default, so an SQS queue's maxReceiveCount set in verify provisioning needs no change. The first six retries now take 15 to 30 minutes; a message is dead-lettered after about 2 days on average (1.4 to 2.9). pg-boss rewrites the queue's policy at startup; jobs already queued keep the schedule they were inserted with.
  • This only spaces out retries. It does not cap how fast first attempts go out, which is what competes with API writes for S3's per-prefix budget.

Limits

  • limit is a ceiling in the normal path, but two failure paths can go past it:

    • A round that fails after moving some messages is retried with the same budget: up to one extra batch per failed attempt.
    • A worker that dies after sending the next round, before its own job is acked, runs the round again and starts a second chain with the same remaining budget.

    Both chains still honour maxBacklog. A strict cap needs the replay's progress stored durably (which would also give a stop endpoint and a status view); left for a follow-up.

  • There is no stop endpoint: maxMinutes bounds a replay.

  • No per-tenant filter: SQS cannot filter a queue without receiving from it.

Deploy note

Two new queues: replay-dead-letters and replay-dead-letters-dead-letter. pg-boss provisions them at startup. On SQS with verify provisioning they must be created in the infrastructure repo before this ships, or startup fails on the missing queues.

Tests

  • Adapter conformance (adapters/conformance.ts), three new tests run on every adapter: a dead letter comes back fresh with payload, headers and key intact; limit bounds a call and remaining reports what is left; a dead letter a consumer holds is skipped until it is handed back. Passing on memory, pg-boss (real Postgres) and SQS standard and FIFO (ElasticMQ).
  • sqs-adapter.test.ts: on a partial send, only the dead letters whose copy was confirmed are deleted; copies carry a per-dead-letter idempotency key.
  • manager/redrive.test.ts: end to end on the memory adapter (fail, dead-letter, redrive, handled again at attempt 1), producer-only manager, argument forwarding, request validation, shared or missing dead-letter queue, NotSupportedError on adapters without the capability and on the sync queue.
  • replay-dead-letters.test.ts: round sizing under batch, limit and backlog room; throttling; no backpressure without stats; delays and every stop condition; the handler chaining the next round.
  • admin/queue.test.ts: scheduling with explicit and default pacing, validation, the listing, and the queue-disabled case.
  • manager/policy.test.ts: jittered delays stay between half and all of the capped curve, including at the cap; a non-boolean jitter is refused at start. storage/events/workers.test.ts: both delete queues keep the default attempt budget and never wait under 15s or over the SQS visibility limit.

tsc and Biome are clean. The full unit suite passes (4,540 tests), and so does src/test/queue against throwaway Postgres and ElasticMQ containers.

… API

Adds dead-letter redrive to the queue adapter contract and an admin
endpoint that replays a queue's dead letters onto it, paced so its
workers are not swamped.

- Adapter contract: optional `redrive(deadLetter, target, { limit })`,
  surfaced as `queue.redrive(queue, { limit })` on every manager shape.
  pg-boss uses its native redrive (one transaction per call), SQS copies
  then deletes (at-least-once, FIFO dedup by dead-letter id), memory is
  the reference. Held to the conformance suite.
- Storage: a ReplayDeadLetters job chain that moves at most batchSize per
  round, stops at the limit, an empty dead-letter queue or maxMinutes,
  and moves nothing while the queue has maxBacklog messages waiting or
  running.
- Admin: GET /queue/dead-letters, POST /queue/dead-letters/replay.
@fenos
fenos requested a review from a team as a code owner November 30, 2026 09:22
Copilot AI balanced review requested due to automatic review settings November 30, 2026 09:22

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Findings marked 🟡 are optional suggestions and need no follow-up push.

Comment thread src/http/routes/admin/queue.ts Resolved
@coveralls

coveralls commented Nov 30, 2026 •

Copy link
Copy Markdown

Coverage Report for CI Build 46415379681

Warning

Build has drifted: This PR's base is out of sync with its target branch, so coverage data may include unrelated changes.
Quick fix: rebase this PR. Learn more →

Coverage increased (+0.1%) to 88.798%

Details

  • Coverage increased (+0.1%) from the base build.
  • Patch coverage: 1 uncovered change across 1 file (255 of 256 lines covered, 99.61%).
  • 96 coverage regressions across 7 files.

Uncovered Changes

File Changed Covered %
src/storage/events/dead-letters/replay-dead-letters.ts 49 48 97.96%
Total (17 files) 256 255 99.61%

Coverage Regressions

96 previously-covered lines in 7 files lost coverage.

File Lines Losing Coverage Coverage
src/storage/protocols/s3/s3-handler.ts 48 86.17%
src/http/routes/admin/tenants.ts 26 85.85%
src/storage/uploader.ts 8 94.95%
src/internal/errors/codes.ts 8 91.21%
src/http/routes/s3/commands/put-object.ts 4 86.67%
src/internal/auth/jwks/manager.ts 1 95.74%
src/http/routes/s3/commands/complete-multipart-upload.ts 1 83.33%

Coverage Stats

Coverage Status
Relevant Lines: 19562
Covered Lines: 17896
Line Coverage: 91.48%
Relevant Branches: 12289
Covered Branches: 10387
Branch Coverage: 84.52%
Branches in Coverage %: Yes
Coverage Strength: 1276.79 hits per line

💛 - Coveralls

…ckpressure

- SQS: a message now carries its idempotency key in the
  `queue.idempotency-key` attribute, which dead-letter copies keep. A
  redrive copy joins the original's FIFO group and deduplicates per dead
  letter, so it is held behind a live message of the same identity and a
  replay soon after the original send is not dropped as its duplicate.
- Replay: parked retries no longer count toward maxBacklog on SQS, where
  in-flight cannot tell them from running deliveries; the backlog read is
  capped at maxBacklog (now at most 100,000); a round past its deadline
  moves nothing.
- Integration coverage: manager redrive on pg-boss and SQS, the replay
  chain end to end on pg-boss, FIFO identity through a dead letter.
@blacksmith-sh

This comment has been minimized.

The five dead letters are sent in one insert, so they are equally old and
pg-boss redrives them in no particular order. OrioleDB returned a
different three than Postgres. Assert the count per replay and that every
dead letter comes back exactly once.
object-admin-delete and object-admin-delete-batch fail mostly when S3
throttles (SlowDown). Under the default policy their first six retries
landed within about a minute, right back onto the throttled prefix, and
every message of a failed DeleteObjects batch came back at the same
moment.

- RetryPolicy gains an opt-in `jitter`: each delay is spread at random
  between half and all of the capped curve. The manager's delay is what
  both engines apply (pg-boss's own jittered start_after is overwritten
  on a handler failure), so this spreads retries on pg-boss and SQS.
- The two delete queues use a new cleanupRetry: 30s doubling to 6h,
  jittered, on the same 21 attempts as the default so an SQS queue's
  maxReceiveCount set in verify provisioning stays valid. The first six
  retries now take 15 to 30 minutes; a message is dead-lettered after
  about 2 days on average (1.4 to 2.9).

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants