# Dead-letter queues

> Use pushq dead-letter queues to keep tasks that ran out of retries: setup, what is copied, the X-Pushq-Deadletter headers, and how to replay them.

Source: https://pushqueue.dev/docs/concepts/dead-letter-queues/

A pushq dead-letter queue (DLQ) catches tasks that ran out of [retries](https://pushqueue.dev/docs/concepts/retries/), so failed work isn't lost. When a task in a queue with `dead_letter_queue` set fails for good, pushq creates a copy of it in the dead-letter queue. The original stays `failed` in its own queue.

A DLQ is an ordinary queue. It has its own state, rate limits, retry settings and target, and its tasks are dispatched like any others. That is what makes replay possible, and it is also the main thing to plan for: a running DLQ delivers its copies right away.

The examples assume a client named `pq` (see [Install & configure an SDK](https://pushqueue.dev/docs/getting-started/sdks/)).

## Set up a dead-letter queue

1. Create the DLQ and pause it, so dead letters are kept instead of being delivered again immediately.
2. Point the source queue at it with `dead_letter_queue`.


**TypeScript**

```ts
await pq.upsertQueue("emails-dead", { target: { baseUrl: "https://api.example.com" } });
await pq.pauseQueue("emails-dead");

await pq.patchQueue("emails", { deadLetterQueue: "emails-dead" });
```

**Python**

```python
from pushq import Target

pq.upsert_queue("emails-dead", target=Target(base_url="https://api.example.com"))
pq.pause_queue("emails-dead")

pq.patch_queue("emails", dead_letter_queue="emails-dead")
```

**Go**

```go
_, err := pq.UpsertQueue(ctx, "emails-dead", pushq.QueueConfig{
	Target: &pushq.Target{BaseURL: "https://api.example.com"},
})
_, err = pq.PauseQueue(ctx, "emails-dead")

_, err = pq.PatchQueue(ctx, "emails", pushq.QueueConfig{DeadLetterQueue: "emails-dead"}, "")
```

**Java**

```java
pq.upsertQueue("emails-dead", QueueConfig.builder()
    .target(Target.builder().baseUrl("https://api.example.com").build())
    .build());
pq.pauseQueue("emails-dead");

pq.patchQueue("emails", QueuePatch.builder().deadLetterQueue("emails-dead").build());
```

**.NET**

```csharp
await pq.UpsertQueueAsync("emails-dead", new QueueConfig
{
    Target = new Target { BaseUrl = "https://api.example.com" },
});
await pq.PauseQueueAsync("emails-dead");

await pq.PatchQueueAsync("emails", new QueuePatch { DeadLetterQueue = "emails-dead" });
```

**curl**

```bash
curl -X PUT https://api.pushqueue.dev/v1/queues/emails-dead \
  -H "Authorization: Bearer $PUSHQ_API_KEY" \
  -d '{"target": {"base_url": "https://api.example.com"}}'

curl -X POST https://api.pushqueue.dev/v1/queues/emails-dead:pause \
  -H "Authorization: Bearer $PUSHQ_API_KEY"

curl -X PATCH https://api.pushqueue.dev/v1/queues/emails \
  -H "Authorization: Bearer $PUSHQ_API_KEY" \
  -d '{"dead_letter_queue": "emails-dead"}'
```

You can also set `dead_letter_queue` in the PUT that creates the source queue. Remember that a PUT without `dead_letter_queue` removes it; to remove it with PATCH, send `"dead_letter_queue": ""`.

| Parameter | Type | Default | Description |
|---|---|---|---|
| `dead_letter_queue` | string | none | Name of the queue that receives copies of permanently failed tasks. Must be a valid queue name and can't be the queue itself. Several queues can share one DLQ. |

### The dead-letter queue must exist

pushq checks only that `dead_letter_queue` is a valid name; it doesn't check that the queue exists when you set it. The copy is made when a task fails, and if the DLQ doesn't exist at that moment, or is `disabled`, the copy is dropped (the server logs the error) and the task is only marked `failed` in its own queue. Create the DLQ first and don't disable it. A `paused` DLQ accepts copies normally.

## What is copied to the dead-letter queue

When a task fails for the last time, the DLQ gets a new task with:

| Copied from the original | Not copied |
|---|---|
| `url` or `path` | `task_id`: the copy gets a new server-generated ID |
| `method` (the task's own) | Per-task `retry` override: the DLQ's retry settings apply |
| Task `headers`, plus the headers below | Attempt history and counters |
| Body | The source queue's `target` (`base_url`, `method`, `headers`, `signing_secret`): the DLQ's own target applies |
| `dispatch_deadline_seconds` | |

The copy is scheduled for immediate delivery. On a running DLQ it is sent right away; on a paused DLQ it waits.

Because the source queue's `target` doesn't come along, set up the DLQ to match it when you want replays to reach the same endpoint: the same `base_url` (path-based tasks are resolved against the **DLQ's** `base_url`, and fail with a `config` error if it has none), and the same `target.headers` and `signing_secret` if your endpoint expects them.

### X-Pushq-Deadletter headers

Three headers are added to the copy's headers, so they are visible in the task (with `view=full`) and sent with every delivery of the copy:

| Header | Example | Meaning |
|---|---|---|
| `X-Pushq-Deadletter-Source-Queue` | `emails` | The queue the task failed in. |
| `X-Pushq-Deadletter-Task-Id` | `welcome-user-42` | The original task's ID. |
| `X-Pushq-Deadletter-Final-Status` | `500` or `timeout` | The last attempt's HTTP status, or its error kind (`timeout`, `connect`, `dns`, `tls`, `config`, `lease_lost`) when there was no response. |

The copy's own `X-Pushq-Task-Id` and `webhook-id` use the new ID and the DLQ's name. If your endpoint deduplicates on those, use `X-Pushq-Deadletter-Task-Id` to recognize a replay of a task it already saw.

## Inspect failed tasks in a dead-letter queue

List the DLQ with the full view to see bodies and headers:


**TypeScript**

```ts
const page = await pq.listTasks("emails-dead", { view: "full", pageSize: 50 });
for (const t of page.items) {
  console.log(t.id, t.headers?.["X-Pushq-Deadletter-Task-Id"], t.headers?.["X-Pushq-Deadletter-Final-Status"]);
}
```

**Python**

```python
page = pq.list_tasks("emails-dead", view="full", page_size=50)
for t in page.items:
    print(t.id, t.headers.get("X-Pushq-Deadletter-Task-Id"), t.headers.get("X-Pushq-Deadletter-Final-Status"))
```

**Go**

```go
tasks, _, err := pq.ListTasks(ctx, "emails-dead", pushq.ListTasksParams{View: "full", PageSize: 50})
for _, t := range tasks {
	fmt.Println(t.ID, t.Headers["X-Pushq-Deadletter-Task-Id"], t.Headers["X-Pushq-Deadletter-Final-Status"])
}
```

**Java**

```java
TaskPage page = pq.listTasks("emails-dead", ListTasksParams.builder().view("full").pageSize(50).build());
for (Task t : page.getTasks()) {
    System.out.println(t.getId() + " " + t.getHeaders().get("X-Pushq-Deadletter-Task-Id")
        + " " + t.getHeaders().get("X-Pushq-Deadletter-Final-Status"));
}
```

**.NET**

```csharp
var page = await pq.ListTasksAsync("emails-dead", new ListTasksOptions { View = TaskView.Full, PageSize = 50 });
foreach (var t in page.Items)
    Console.WriteLine($"{t.Id} {t.Headers?["X-Pushq-Deadletter-Task-Id"]} {t.Headers?["X-Pushq-Deadletter-Final-Status"]}");
```

**curl**

```bash
curl "https://api.pushqueue.dev/v1/queues/emails-dead/tasks?view=full&page_size=50" \
  -H "Authorization: Bearer $PUSHQ_API_KEY"
```

Watch the DLQ's `pending` and `scheduled_future` counts in [queue stats](https://pushqueue.dev/docs/concepts/queues/#queue-stats-and-monitoring) to alert when tasks start dead-lettering.

## Replay tasks from a dead-letter queue

Once you've fixed the cause, there are three ways to deal with what's in a paused DLQ (the [replay dead letters pattern](https://pushqueue.dev/docs/patterns/replay-dead-letters/) walks through a full replay):

- **Replay one task:** `:run` delivers a single task right away, even though the DLQ is paused. Use it to check that the fix works.
- **Replay everything:** resume the DLQ. Its tasks are delivered at the DLQ's rate limits and retried with the DLQ's retry settings. Pause it again afterwards if you want it to keep collecting.
- **Discard everything:** purge the DLQ, or delete individual tasks.


**TypeScript**

```ts
await pq.runTask("emails-dead", "0193a1b2-7c4d-7e8f-9a0b-1c2d3e4f5a6b"); // one task
await pq.resumeQueue("emails-dead");                                     // all of them
```

**Python**

```python
pq.run_task("emails-dead", "0193a1b2-7c4d-7e8f-9a0b-1c2d3e4f5a6b")  # one task
pq.resume_queue("emails-dead")                                     # all of them
```

**Go**

```go
_, err := pq.RunTask(ctx, "emails-dead", "0193a1b2-7c4d-7e8f-9a0b-1c2d3e4f5a6b") // one task
_, err = pq.ResumeQueue(ctx, "emails-dead")                                      // all of them
```

**Java**

```java
pq.runTask("emails-dead", "0193a1b2-7c4d-7e8f-9a0b-1c2d3e4f5a6b"); // one task
pq.resumeQueue("emails-dead");                                     // all of them
```

**.NET**

```csharp
await pq.RunTaskAsync("emails-dead", "0193a1b2-7c4d-7e8f-9a0b-1c2d3e4f5a6b"); // one task
await pq.ResumeQueueAsync("emails-dead");                                     // all of them
```

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

To replay into the original queue instead (for example, to get its rate limits), read the tasks with `view=full` and create new tasks in the source queue with the same `path` or `url`, method, headers and body.

If a replayed task fails again in the DLQ, it follows the DLQ's retry settings. When those run out it becomes `failed` in the DLQ, or moves on to the DLQ's own `dead_letter_queue` if it has one.

## Dead-letter queue use cases

- **Parking lot (paused DLQ):** keep failed work safe during an outage, then replay it after the fix. This is the setup shown above.
- **Failure handler (running DLQ with a different target):** give the DLQ a `base_url` that points at a handler which alerts, refunds or marks the record as failed. Path-based tasks then reach that handler with the original body and the dead-letter headers. Tasks created with an absolute `url` still go to that URL, so this pattern needs path-based tasks.
- **Shared DLQ:** point many queues (such as every queue under `tenants/`) at one DLQ and use `X-Pushq-Deadletter-Source-Queue` to tell them apart.

## Read more

- [Replay dead letters](https://pushqueue.dev/docs/patterns/replay-dead-letters/): a step-by-step replay after an outage.
- [Retry backoff and max attempts](https://pushqueue.dev/docs/concepts/retries/): when a task counts as permanently failed.
- [Queues and queue configuration](https://pushqueue.dev/docs/concepts/queues/): pause, resume and purge a dead-letter queue.
- [Stop retrying a task](https://pushqueue.dev/docs/patterns/stop-retrying/): send a task to the dead-letter queue sooner.
