Replay dead-lettered tasks
This pattern turns a dead-letter queue (DLQ) into a parking lot: tasks that run out of retries are kept in a paused DLQ, where nothing is delivered, until you have fixed the cause and decide to replay them or throw them away. It covers setting up the DLQ, inspecting dead-lettered tasks, the three ways to replay, and cleaning up.
Set up a paused dead-letter queue
Section titled “Set up a paused dead-letter queue”Create the DLQ first, with the same target as the source queue, and pause it. Then point the source queue at it.
const target = { baseUrl: "https://api.example.com", signingSecret: process.env.PUSHQ_SIGNING_SECRET };
// 1. The DLQ: same target as the source, paused so nothing is delivered until you decide.await pq.upsertQueue("emails-dead", { target, retry: { maxAttempts: 3 } });await pq.pauseQueue("emails-dead");
// 2. The source queue: tasks that exhaust their retries are copied to the DLQ.await pq.upsertQueue("emails", { target, retry: { maxAttempts: 5 }, deadLetterQueue: "emails-dead",});import osfrom pushq import Retry, Target
target = Target(base_url="https://api.example.com", signing_secret=os.environ["PUSHQ_SIGNING_SECRET"])
# 1. The DLQ: same target as the source, paused so nothing is delivered until you decide.pq.upsert_queue("emails-dead", target=target, retry=Retry(max_attempts=3))pq.pause_queue("emails-dead")
# 2. The source queue: tasks that exhaust their retries are copied to the DLQ.pq.upsert_queue("emails", target=target, retry=Retry(max_attempts=5), dead_letter_queue="emails-dead")target := &pushq.Target{BaseURL: "https://api.example.com", SigningSecret: os.Getenv("PUSHQ_SIGNING_SECRET")}
// 1. The DLQ: same target as the source, paused so nothing is delivered until you decide.if _, err := pq.UpsertQueue(ctx, "emails-dead", pushq.QueueConfig{ Target: target, Retry: &pushq.Retry{MaxAttempts: pushq.Int(3)},}); err != nil { return err}if _, err := pq.PauseQueue(ctx, "emails-dead"); err != nil { return err}
// 2. The source queue: tasks that exhaust their retries are copied to the DLQ._, err := pq.UpsertQueue(ctx, "emails", pushq.QueueConfig{ Target: target, Retry: &pushq.Retry{MaxAttempts: pushq.Int(5)}, DeadLetterQueue: "emails-dead",})Target target = Target.builder() .baseUrl("https://api.example.com") .signingSecret(System.getenv("PUSHQ_SIGNING_SECRET")) .build();
// 1. The DLQ: same target as the source, paused so nothing is delivered until you decide.pq.upsertQueue("emails-dead", QueueConfig.builder() .target(target) .retry(RetryConfig.builder().maxAttempts(3).build()) .build());pq.pauseQueue("emails-dead");
// 2. The source queue: tasks that exhaust their retries are copied to the DLQ.pq.upsertQueue("emails", QueueConfig.builder() .target(target) .retry(RetryConfig.builder().maxAttempts(5).build()) .deadLetterQueue("emails-dead") .build());var target = new Target{ BaseUrl = "https://api.example.com", SigningSecret = Environment.GetEnvironmentVariable("PUSHQ_SIGNING_SECRET"),};
// 1. The DLQ: same target as the source, paused so nothing is delivered until you decide.await pq.UpsertQueueAsync("emails-dead", new QueueConfig { Target = target, Retry = new RetryConfig { MaxAttempts = 3 } });await pq.PauseQueueAsync("emails-dead");
// 2. The source queue: tasks that exhaust their retries are copied to the DLQ.await pq.UpsertQueueAsync("emails", new QueueConfig{ Target = target, Retry = new RetryConfig { MaxAttempts = 5 }, DeadLetterQueue = "emails-dead",});# 1. The DLQ, then pause it.curl -X PUT https://api.pushqueue.dev/v1/queues/emails-dead \ -H "Authorization: Bearer $PUSHQ_API_KEY" -H "Content-Type: application/json" \ -d '{"target":{"base_url":"https://api.example.com","signing_secret":"'"$PUSHQ_SIGNING_SECRET"'"}, "retry":{"max_attempts":3}}'curl -X POST https://api.pushqueue.dev/v1/queues/emails-dead:pause -H "Authorization: Bearer $PUSHQ_API_KEY"
# 2. The source queue.curl -X PUT https://api.pushqueue.dev/v1/queues/emails \ -H "Authorization: Bearer $PUSHQ_API_KEY" -H "Content-Type: application/json" \ -d '{"target":{"base_url":"https://api.example.com","signing_secret":"'"$PUSHQ_SIGNING_SECRET"'"}, "retry":{"max_attempts":5},"dead_letter_queue":"emails-dead"}'The examples assume a client named pq (see install and configure an SDK). The text uses JSON field names; the SDKs use their language’s casing (deadLetterQueue in TypeScript and Java, dead_letter_queue in Python, DeadLetterQueue in Go and .NET).
Use this when failed work must not be lost and must not be retried blindly: payments, order fulfilment, outbound webhooks to customers, anything where you want a human to look before it runs again.
Running this setup again is safe: upsert never changes a queue’s state, so the DLQ stays paused.
Why the dead-letter queue must match the source target
Section titled “Why the dead-letter queue must match the source target”When a task fails for the last time, pushq copies it into the DLQ as a new task: same url or path, method, headers and body, plus three X-Pushq-Deadletter-* headers. The copy does not take the source queue’s target or the task’s own retry override:
- A path-based task (
/hooks/send-welcome) is resolved against the DLQ’starget.base_url. Without one, every delivery fails with aconfigerror. - The DLQ’s
target.headersandsigning_secretare used, not the source’s. If your endpoint checks a static header or a webhook signature, give the DLQ the same ones. - The DLQ’s
retrysettings apply to the copy.
That’s why the setup reuses one target for both queues. See what is copied to the dead-letter queue for the full list.
Inspect dead-lettered tasks
Section titled “Inspect dead-lettered tasks”List the DLQ with the full view to see bodies and headers. The original task is still in the source queue in the failed state (for 7 days on a default self-hosted server), with its attempt history, which tells you why it failed.
const page = await pq.listTasks("emails-dead", { view: "full", pageSize: 100 });for (const t of page.items) { const source = t.headers?.["X-Pushq-Deadletter-Source-Queue"]!; const originalId = t.headers?.["X-Pushq-Deadletter-Task-Id"]!; console.log(t.id, source, originalId, t.headers?.["X-Pushq-Deadletter-Final-Status"]);
const attempts = await pq.listAttempts(source, originalId); for (const a of attempts) console.log(" ", a.number, a.responseStatus ?? a.errorKind, a.errorSnippet);}page = pq.list_tasks("emails-dead", view="full", page_size=100)for t in page.items: source = t.headers["X-Pushq-Deadletter-Source-Queue"] original_id = t.headers["X-Pushq-Deadletter-Task-Id"] print(t.id, source, original_id, t.headers.get("X-Pushq-Deadletter-Final-Status"))
for a in pq.list_attempts(source, original_id): print(" ", a.number, a.response_status or a.error_kind, a.error_snippet)tasks, _, err := pq.ListTasks(ctx, "emails-dead", pushq.ListTasksParams{View: "full", PageSize: 100})if err != nil { return err}for _, t := range tasks { source := t.Headers["X-Pushq-Deadletter-Source-Queue"] originalID := t.Headers["X-Pushq-Deadletter-Task-Id"] fmt.Println(t.ID, source, originalID, t.Headers["X-Pushq-Deadletter-Final-Status"])
attempts, err := pq.ListAttempts(ctx, source, originalID) if err != nil { continue // the original may already have been cleaned up } for _, a := range attempts { fmt.Println(" ", a.Number, a.ResponseStatus, a.ErrorKind, a.ErrorSnippet) }}TaskPage page = pq.listTasks("emails-dead", ListTasksParams.builder().view("full").pageSize(100).build());for (Task t : page.getTasks()) { String source = t.getHeaders().get("X-Pushq-Deadletter-Source-Queue"); String originalId = t.getHeaders().get("X-Pushq-Deadletter-Task-Id"); System.out.println(t.getId() + " " + source + " " + originalId + " " + t.getHeaders().get("X-Pushq-Deadletter-Final-Status"));
for (Attempt a : pq.listAttempts(source, originalId)) { System.out.println(" " + a.getNumber() + " " + a.getResponseStatus() + " " + a.getErrorKind() + " " + a.getErrorSnippet()); }}var page = await pq.ListTasksAsync("emails-dead", new ListTasksOptions { View = TaskView.Full, PageSize = 100 });foreach (var t in page.Items){ var source = t.Headers!["X-Pushq-Deadletter-Source-Queue"]; var originalId = t.Headers["X-Pushq-Deadletter-Task-Id"]; Console.WriteLine($"{t.Id} {source} {originalId} {t.Headers["X-Pushq-Deadletter-Final-Status"]}");
foreach (var a in await pq.ListAttemptsAsync(source, originalId)) Console.WriteLine($" {a.Number} {a.ResponseStatus?.ToString() ?? a.ErrorKind} {a.ErrorSnippet}");}curl "https://api.pushqueue.dev/v1/queues/emails-dead/tasks?view=full&page_size=100" \ -H "Authorization: Bearer $PUSHQ_API_KEY"
# Attempt history of the original task, from X-Pushq-Deadletter-Task-Id:curl "https://api.pushqueue.dev/v1/queues/emails/tasks/welcome-user-42/attempts" \ -H "Authorization: Bearer $PUSHQ_API_KEY"The three dead-letter headers:
| Header | Meaning |
|---|---|
X-Pushq-Deadletter-Source-Queue |
The queue the task failed in. |
X-Pushq-Deadletter-Task-Id |
The original task’s ID in that queue. |
X-Pushq-Deadletter-Final-Status |
The last attempt’s HTTP status (500), or its error kind when there was no response (timeout, connect, dns, tls, config, lease_lost). |
To alert when tasks start dead-lettering, watch the DLQ’s pending count in queue stats. On a paused DLQ, every task is pending until you act.
Replay dead-lettered tasks
Section titled “Replay dead-lettered tasks”Fix the cause first: deploy the handler fix, restore the downstream service, or correct the queue config. Then pick one of three ways to replay.
Replay one task with run
Section titled “Replay one task with run”POST /v1/queues/emails-dead/tasks/{id}:run delivers one DLQ task now, even though the DLQ is paused. Use it to check that the fix works before replaying the rest.
Replay all tasks by resuming the DLQ
Section titled “Replay all tasks by resuming the DLQ”Resume the DLQ. Its pending tasks are delivered to the DLQ’s target (the same endpoint, given the setup above) at the DLQ’s rate limits, with the DLQ’s retry settings. When the DLQ’s pending count reaches zero, pause it again so it goes back to collecting.
await pq.runTask("emails-dead", "0193a1b2-7c4d-7e8f-9a0b-1c2d3e4f5a6b"); // try oneawait pq.resumeQueue("emails-dead"); // then all of them// ...when queueStats("emails-dead").pending is 0:await pq.pauseQueue("emails-dead");pq.run_task("emails-dead", "0193a1b2-7c4d-7e8f-9a0b-1c2d3e4f5a6b") # try onepq.resume_queue("emails-dead") # then all of them# ...when queue_stats("emails-dead").pending is 0:pq.pause_queue("emails-dead")_, err := pq.RunTask(ctx, "emails-dead", "0193a1b2-7c4d-7e8f-9a0b-1c2d3e4f5a6b") // try one_, err = pq.ResumeQueue(ctx, "emails-dead") // then all of them// ...when QueueStats(ctx, "emails-dead", "").Pending is 0:_, err = pq.PauseQueue(ctx, "emails-dead")pq.runTask("emails-dead", "0193a1b2-7c4d-7e8f-9a0b-1c2d3e4f5a6b"); // try onepq.resumeQueue("emails-dead"); // then all of them// ...when queueStats("emails-dead").getPending() is 0:pq.pauseQueue("emails-dead");await pq.RunTaskAsync("emails-dead", "0193a1b2-7c4d-7e8f-9a0b-1c2d3e4f5a6b"); // try oneawait pq.ResumeQueueAsync("emails-dead"); // then all of them// ...when (await pq.GetQueueStatsAsync("emails-dead")).Pending is 0:await pq.PauseQueueAsync("emails-dead");curl -X POST https://api.pushqueue.dev/v1/queues/emails-dead/tasks/0193a1b2-7c4d-7e8f-9a0b-1c2d3e4f5a6b:run \ -H "Authorization: Bearer $PUSHQ_API_KEY"curl -X POST https://api.pushqueue.dev/v1/queues/emails-dead:resume -H "Authorization: Bearer $PUSHQ_API_KEY"# ...when GET /v1/queues/emails-dead/stats shows "pending": 0curl -X POST https://api.pushqueue.dev/v1/queues/emails-dead:pause -H "Authorization: Bearer $PUSHQ_API_KEY"While the DLQ is running, tasks that newly fail in the source queue are delivered from the DLQ right away too. Replayed copies that fail again follow the DLQ’s retry settings and end up failed in the DLQ (or in the DLQ’s own dead_letter_queue, if you set one).
Replay into the source queue
Section titled “Replay into the source queue”To replay with the source queue’s rate limits and retry settings, read each DLQ task and create a new task in the source queue with the same url or path, method, headers and body, then delete the DLQ copy. Deriving the new ID from the DLQ copy’s ID (replay-<id>) makes the script safe to run again after a crash: a task that was already re-created comes back as already_exists.
import { PushqError } from "pushq";
const page = await pq.listTasks("emails-dead", { view: "full", pageSize: 100 });for (const t of page.items) { const source = t.headers!["X-Pushq-Deadletter-Source-Queue"]; try { await pq.createTask(source, { taskId: `replay-${t.id}`, ...(t.url.startsWith("/") ? { path: t.url } : { url: t.url }), method: t.method, headers: t.headers, body: t.body, }); } catch (err) { if (!(err instanceof PushqError && err.code === "already_exists")) throw err; } await pq.deleteTask("emails-dead", t.id);}from pushq import PushqError
page = pq.list_tasks("emails-dead", view="full", page_size=100)for t in page.items: source = t.headers["X-Pushq-Deadletter-Source-Queue"] where = {"path": t.url} if t.url.startswith("/") else {"url": t.url} try: pq.create_task(source, task_id=f"replay-{t.id}", method=t.method, headers=t.headers, body=t.body, **where) except PushqError as e: if e.code != "already_exists": raise pq.delete_task("emails-dead", t.id)tasks, _, err := pq.ListTasks(ctx, "emails-dead", pushq.ListTasksParams{View: "full", PageSize: 100})if err != nil { return err}for _, t := range tasks { body, err := base64.StdEncoding.DecodeString(t.BodyBase64) if err != nil { return err } replay := pushq.TaskCreate{ TaskID: "replay-" + t.ID, Method: t.Method, Headers: t.Headers, Body: body, } if strings.HasPrefix(t.URL, "/") { replay.Path = t.URL } else { replay.URL = t.URL } source := t.Headers["X-Pushq-Deadletter-Source-Queue"] if _, err := pq.CreateTask(ctx, source, replay); err != nil && !pushq.IsCode(err, "already_exists") { return err } if err := pq.DeleteTask(ctx, "emails-dead", t.ID); err != nil { return err }}TaskPage page = pq.listTasks("emails-dead", ListTasksParams.builder().view("full").pageSize(100).build());for (Task t : page.getTasks()) { String source = t.getHeaders().get("X-Pushq-Deadletter-Source-Queue"); TaskCreate.Builder replay = TaskCreate.builder() .taskId("replay-" + t.getId()) .method(t.getMethod()) .headers(t.getHeaders()) .body(t.getBodyBase64() == null ? null : Base64.getDecoder().decode(t.getBodyBase64())); if (t.getUrl().startsWith("/")) replay.path(t.getUrl()); else replay.url(t.getUrl()); try { pq.createTask(source, replay.build()); } catch (PushqException e) { if (!"already_exists".equals(e.getCode())) throw e; } pq.deleteTask("emails-dead", t.getId());}var page = await pq.ListTasksAsync("emails-dead", new ListTasksOptions { View = TaskView.Full, PageSize = 100 });foreach (var t in page.Items){ var source = t.Headers!["X-Pushq-Deadletter-Source-Queue"]; var replay = new TaskCreate { TaskId = $"replay-{t.Id}", Method = t.Method, Headers = t.Headers, Body = t.Body }; if (t.Url.StartsWith("/")) replay.Path = t.Url; else replay.Url = t.Url; try { await pq.CreateTaskAsync(source, replay); } catch (PushqException e) when (e.Code == "already_exists") { // re-created by an earlier run } await pq.DeleteTaskAsync("emails-dead", t.Id);}# 1. Read the DLQ task (url, method, headers, body_base64):curl "https://api.pushqueue.dev/v1/queues/emails-dead/tasks/0193a1b2-7c4d-7e8f-9a0b-1c2d3e4f5a6b?view=full" \ -H "Authorization: Bearer $PUSHQ_API_KEY"
# 2. Re-create it in the source queue ("path" when url starts with "/", else "url"):curl -X POST https://api.pushqueue.dev/v1/queues/emails/tasks \ -H "Authorization: Bearer $PUSHQ_API_KEY" -H "Content-Type: application/json" \ -d '{"task_id":"replay-0193a1b2-7c4d-7e8f-9a0b-1c2d3e4f5a6b","path":"/hooks/send-welcome", "method":"POST","headers":{"Content-Type":"application/json"},"body_base64":"eyJ1c2VyX2lkIjo0Mn0="}'
# 3. Delete the DLQ copy:curl -X DELETE https://api.pushqueue.dev/v1/queues/emails-dead/tasks/0193a1b2-7c4d-7e8f-9a0b-1c2d3e4f5a6b \ -H "Authorization: Bearer $PUSHQ_API_KEY"This replays the first 100 tasks; loop over next_page_token for more, or run it again until the DLQ is empty. The X-Pushq-Deadletter-* headers come along with the other headers, so your handler can tell a replay apart (they are replaced, not duplicated, if the task dead-letters again).
Purge the dead-letter queue when done
Section titled “Purge the dead-letter queue when done”To throw away everything left in the DLQ (tasks you decided not to replay), purge it. Purge deletes every task created up to that moment and keeps the queue and its paused state, so it keeps collecting new failures.
await pq.purgeQueue("emails-dead");pq.purge_queue("emails-dead")_, err := pq.PurgeQueue(ctx, "emails-dead")pq.purgeQueue("emails-dead");await pq.PurgeQueueAsync("emails-dead");curl -X POST https://api.pushqueue.dev/v1/queues/emails-dead:purge -H "Authorization: Bearer $PUSHQ_API_KEY"To drop only some tasks, delete them one by one with DELETE /v1/queues/emails-dead/tasks/{id}.
Pitfalls
Section titled “Pitfalls”- DLQ created after the source queue starts failing. Copies made before the DLQ existed are lost. Create the DLQ first.
- DLQ without the source’s
base_url, headers or signing secret. Replays by resume fail withconfigerrors or are rejected by your endpoint. - Resuming and forgetting. A running DLQ delivers new failures immediately. Pause it again after the replay.
- Replaying before fixing. The tasks fail again and use up the DLQ’s retries. Try one with run first.
- Using
upsertQueuewith a partial config on the source queue. Upsert replaces the whole config, and an omitteddead_letter_queueis removed. Always include it (see per-tenant queues).