# Replay dead-lettered tasks

> Park failed tasks in a paused pushq dead-letter queue, inspect why they failed, then replay them after a fix by resuming the DLQ or re-creating them, and purge.

Source: https://pushqueue.dev/docs/patterns/replay-dead-letters/

This pattern turns a [dead-letter queue](https://pushqueue.dev/docs/concepts/dead-letter-queues/) (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

Create the DLQ first, with the same target as the source queue, and pause it. Then point the source queue at it.


**TypeScript**

```ts
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",
});
```

**Python**

```python
import os
from 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")
```

**Go**

```go
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",
})
```

**Java**

```java
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());
```

**.NET**

```csharp
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",
});
```

**curl**

```bash
# 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](https://pushqueue.dev/docs/getting-started/sdks/)). 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

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's** `target.base_url`. Without one, every delivery fails with a `config` error.
- The DLQ's `target.headers` and `signing_secret` are used, not the source's. If your endpoint checks a static header or a [webhook signature](https://pushqueue.dev/docs/concepts/delivery/#webhook-signing), give the DLQ the same ones.
- The DLQ's `retry` settings apply to the copy.

That's why the setup reuses one `target` for both queues. See [what is copied to the dead-letter queue](https://pushqueue.dev/docs/concepts/dead-letter-queues/#what-is-copied-to-the-dead-letter-queue) for the full list.

:::danger[A missing or disabled DLQ silently drops the copy]
pushq doesn't check that the dead-letter queue exists when you set `dead_letter_queue`. If it doesn't exist, or is `disabled`, when a task fails, the copy is dropped (only the server log shows it) and the task is just `failed` in its source queue. Create the DLQ before pointing a queue at it, and pause it rather than disabling it.
:::

:::caution[A running DLQ delivers immediately]
A dead-lettered copy is scheduled for right now. On a running DLQ it is delivered (and retried) at once, before you've looked at it. Keep the DLQ paused if you want to decide first. A paused queue still accepts the copies.
:::

## 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.


**TypeScript**

```ts
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);
}
```

**Python**

```python
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)
```

**Go**

```go
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)
	}
}
```

**Java**

```java
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());
    }
}
```

**.NET**

```csharp
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**

```bash
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](https://pushqueue.dev/docs/concepts/queues/). On a paused DLQ, every task is pending until you act.

## 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

`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

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.


**TypeScript**

```ts
await pq.runTask("emails-dead", "0193a1b2-7c4d-7e8f-9a0b-1c2d3e4f5a6b"); // try one
await pq.resumeQueue("emails-dead");                                     // then all of them
// ...when queueStats("emails-dead").pending is 0:
await pq.pauseQueue("emails-dead");
```

**Python**

```python
pq.run_task("emails-dead", "0193a1b2-7c4d-7e8f-9a0b-1c2d3e4f5a6b")  # try one
pq.resume_queue("emails-dead")                                     # then all of them
# ...when queue_stats("emails-dead").pending is 0:
pq.pause_queue("emails-dead")
```

**Go**

```go
_, 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")
```

**Java**

```java
pq.runTask("emails-dead", "0193a1b2-7c4d-7e8f-9a0b-1c2d3e4f5a6b"); // try one
pq.resumeQueue("emails-dead");                                     // then all of them
// ...when queueStats("emails-dead").getPending() is 0:
pq.pauseQueue("emails-dead");
```

**.NET**

```csharp
await pq.RunTaskAsync("emails-dead", "0193a1b2-7c4d-7e8f-9a0b-1c2d3e4f5a6b"); // try one
await pq.ResumeQueueAsync("emails-dead");                                     // then all of them
// ...when (await pq.GetQueueStatsAsync("emails-dead")).Pending is 0:
await pq.PauseQueueAsync("emails-dead");
```

**curl**

```bash
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": 0
curl -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

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`.


**TypeScript**

```ts

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);
}
```

**Python**

```python
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)
```

**Go**

```go
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
	}
}
```

**Java**

```java
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());
}
```

**.NET**

```csharp
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);
}
```

**curl**

```bash
# 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).

:::caution[The original task ID is still taken]
You can't re-create the task under its original ID: the failed original keeps that ID reserved in the source queue for its retention period (7 days on a default self-hosted server). Use a new ID such as `replay-<dlq id>`, and if your handler deduplicates on `X-Pushq-Task-Id` or `webhook-id`, have it use `X-Pushq-Deadletter-Task-Id` when present. See [idempotent handlers](https://pushqueue.dev/docs/patterns/idempotent-handlers/).
:::

## 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.


**TypeScript**

```ts
await pq.purgeQueue("emails-dead");
```

**Python**

```python
pq.purge_queue("emails-dead")
```

**Go**

```go
_, err := pq.PurgeQueue(ctx, "emails-dead")
```

**Java**

```java
pq.purgeQueue("emails-dead");
```

**.NET**

```csharp
await pq.PurgeQueueAsync("emails-dead");
```

**curl**

```bash
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

- **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 with `config` errors 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 `upsertQueue` with a partial config on the source queue.** Upsert replaces the whole config, and an omitted `dead_letter_queue` is removed. Always include it (see [per-tenant queues](https://pushqueue.dev/docs/patterns/per-tenant-queues/#upsert-replaces-the-whole-queue-config)).

## Read more

- [Dead-letter queues: setup, copied fields and headers](https://pushqueue.dev/docs/concepts/dead-letter-queues/)
- [Retries, backoff and max attempts](https://pushqueue.dev/docs/concepts/retries/)
- [Stop retrying permanent errors](https://pushqueue.dev/docs/patterns/stop-retrying/)
- [Idempotent task handlers](https://pushqueue.dev/docs/patterns/idempotent-handlers/)
- [Troubleshooting failed tasks](https://pushqueue.dev/docs/guides/troubleshooting/)
