# Stop retrying failed tasks

> Stop pushq retrying a task that can never succeed: return 2xx and record the failure, cap max_attempts, delete the task, or dead-letter it.

Source: https://pushqueue.dev/docs/patterns/stop-retrying/

pushq retries every failed delivery with backoff, and a failure is any response that isn't `2xx`, including `400`, `404` and `422`. When a task can never succeed (the record it points to was deleted, the payload is invalid, a downstream API rejects it for good), you have to stop the retries yourself: acknowledge it with a `2xx` and record the failure, cap its attempts, delete it, or let it land in a dead-letter queue.

## Acknowledge permanent failures with a 2xx

Your handler knows which errors are permanent. Return a `2xx` for those so pushq marks the task succeeded and stops, and keep your own record of what went wrong. Return a non-2xx (or let the request fail) only for errors a retry can fix.


**TypeScript**

```ts
app.post("/hooks/send-welcome", express.raw({ type: "*/*" }), async (req, res) => {
  // Authenticate the request first: see /docs/concepts/delivery/
  const taskId = req.get("X-Pushq-Task-Id");
  const { user_id } = JSON.parse(req.body.toString("utf8"));
  try {
    const user = await findUser(user_id);
    if (!user) {
      // Permanent: retrying won't make the user exist. Record it and acknowledge.
      await recordFailure(taskId, "user not found");
      return res.status(200).json({ skipped: "user not found" });
    }
    await sendWelcomeEmail(user);
    res.sendStatus(204);
  } catch (err) {
    // Temporary (timeout, 5xx from the email API): let pushq retry.
    console.error(err);
    res.sendStatus(500);
  }
});
```

**Python**

```python
@app.post("/hooks/send-welcome")
async def send_welcome(request: Request):
    # Authenticate the request first: see /docs/concepts/delivery/
    task_id = request.headers.get("x-pushq-task-id")
    payload = await request.json()
    user = await find_user(payload["user_id"])
    if user is None:
        # Permanent: retrying won't make the user exist. Record it and acknowledge.
        await record_failure(task_id, "user not found")
        return {"skipped": "user not found"}  # 200
    # A temporary error raised here becomes a 500, so pushq retries.
    await send_welcome_email(user)
    return Response(status_code=204)
```

**Go**

```go
func sendWelcome(w http.ResponseWriter, r *http.Request) {
	// Authenticate the request first: see /docs/concepts/delivery/
	taskID := r.Header.Get("X-Pushq-Task-Id")
	var p struct {
		UserID int64 `json:"user_id"`
	}
	if err := json.NewDecoder(r.Body).Decode(&p); err != nil {
		// Permanent: this payload will never parse.
		recordFailure(r.Context(), taskID, "invalid payload: "+err.Error())
		w.WriteHeader(http.StatusOK)
		return
	}
	user, err := findUser(r.Context(), p.UserID)
	if errors.Is(err, errUserNotFound) {
		// Permanent: retrying won't make the user exist.
		recordFailure(r.Context(), taskID, "user not found")
		w.WriteHeader(http.StatusOK)
		return
	}
	if err == nil {
		err = sendWelcomeEmail(r.Context(), user)
	}
	if err != nil {
		// Temporary: let pushq retry.
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	w.WriteHeader(http.StatusNoContent)
}
```

**Java**

```java
@PostMapping("/hooks/send-welcome")
public ResponseEntity<Map<String, String>> sendWelcome(
        @RequestBody Map<String, Object> payload,
        @RequestHeader("X-Pushq-Task-Id") String taskId) {
    // Authenticate the request first: see /docs/concepts/delivery/
    long userId = ((Number) payload.get("user_id")).longValue();
    Optional<User> user = users.findById(userId);
    if (user.isEmpty()) {
        // Permanent: retrying won't make the user exist. Record it and acknowledge.
        failures.record(taskId, "user not found");
        return ResponseEntity.ok(Map.of("skipped", "user not found"));
    }
    // A temporary error thrown here becomes a 500, so pushq retries.
    mailer.sendWelcome(user.get());
    return ResponseEntity.noContent().build();
}
```

**.NET**

```csharp
app.MapPost("/hooks/send-welcome", async (HttpRequest req, UserStore users, FailureLog failures, Mailer mailer) =>
{
    // Authenticate the request first: see /docs/concepts/delivery/
    var taskId = req.Headers["X-Pushq-Task-Id"].FirstOrDefault();
    var payload = await JsonDocument.ParseAsync(req.Body);
    var userId = payload.RootElement.GetProperty("user_id").GetInt64();

    var user = await users.FindAsync(userId);
    if (user is null)
    {
        // Permanent: retrying won't make the user exist. Record it and acknowledge.
        await failures.RecordAsync(taskId, "user not found");
        return Results.Ok(new { skipped = "user not found" });
    }
    // A temporary error thrown here becomes a 500, so pushq retries.
    await mailer.SendWelcomeAsync(user);
    return Results.NoContent();
});
```

`findUser`, `recordFailure` and `sendWelcomeEmail` stand for your own code. Use this when your handler can tell a permanent error from a temporary one, which is most of the time.

:::note
pushq keeps the response body only for non-2xx attempts (as the attempt's `error_snippet`). A `2xx` body is not stored, so the task just shows as succeeded. The failure record is yours to keep: a table, a log line, an alert, or a task on another queue.
:::

## What pushq treats as success and failure

| Outcome of an attempt | What pushq does |
|---|---|
| Any `2xx` status | Marks the task `succeeded`. No more attempts. |
| Any other status, including `400`, `401`, `404`, `410`, `422`, `500` | Schedules a retry with backoff. |
| `429` or `503` with a `Retry-After` header | Retries after the `Retry-After` delay (capped at the queue's `max_backoff_seconds`) and briefly holds back the whole queue. |
| Timeout, connection refused, DNS or TLS error | Schedules a retry with backoff. |

There is no status code that means "don't retry". Retries end only when the task succeeds, when its retry limits run out, or when you delete it. When the limits run out, the task becomes `failed` and, if the queue has a [dead-letter queue](https://pushqueue.dev/docs/concepts/dead-letter-queues/), a copy goes there. The details are on the [retries page](https://pushqueue.dev/docs/concepts/retries/).

## Cap retries with max_attempts and a dead-letter queue

When you can't tell permanent errors apart (for example, a third-party endpoint you don't control), limit how long pushq keeps trying. Set `retry.max_attempts` on the task (it counts the first attempt, so `5` means one try and four retries) and give the queue a dead-letter queue to collect what runs out. The dead-letter queue must already exist.


**TypeScript**

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

await pq.createTask("webhooks", {
  taskId: "order-created-1234",
  url: "https://partner.example.com/events",
  jsonBody: { event: "order.created", order_id: 1234 },
  retry: { maxAttempts: 5 },
});
```

**Python**

```python
from pushq import Retry

pq.patch_queue("webhooks", dead_letter_queue="webhooks-dead")

pq.create_task(
    "webhooks",
    task_id="order-created-1234",
    url="https://partner.example.com/events",
    json_body={"event": "order.created", "order_id": 1234},
    retry=Retry(max_attempts=5),
)
```

**Go**

```go
_, err := pq.PatchQueue(ctx, "webhooks", pushq.QueueConfig{DeadLetterQueue: "webhooks-dead"}, "")
if err != nil {
	return err
}

_, err = pq.CreateTask(ctx, "webhooks", pushq.TaskCreate{
	TaskID:   "order-created-1234",
	URL:      "https://partner.example.com/events",
	JSONBody: map[string]any{"event": "order.created", "order_id": 1234},
	Retry:    &pushq.Retry{MaxAttempts: pushq.Int(5)},
})
```

**Java**

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

pq.createTask("webhooks", TaskCreate.builder()
    .taskId("order-created-1234")
    .url("https://partner.example.com/events")
    .jsonBody(Map.of("event", "order.created", "order_id", 1234))
    .retry(RetryConfig.builder().maxAttempts(5).build())
    .build());
```

**.NET**

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

await pq.CreateTaskAsync("webhooks", new TaskCreate
{
    TaskId = "order-created-1234",
    Url = "https://partner.example.com/events",
    JsonBody = new { @event = "order.created", order_id = 1234 },
    Retry = new RetryConfig { MaxAttempts = 5 },
});
```

**curl**

```bash
curl -X PATCH https://api.pushqueue.dev/v1/queues/webhooks \
  -H "Authorization: Bearer $PUSHQ_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"dead_letter_queue":"webhooks-dead"}'

curl -X POST https://api.pushqueue.dev/v1/queues/webhooks/tasks \
  -H "Authorization: Bearer $PUSHQ_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"task_id":"order-created-1234","url":"https://partner.example.com/events","json_body":{"event":"order.created","order_id":1234},"retry":{"max_attempts":5}}'
```

Use this when a task is worth a few tries but not the queue default of 100 attempts. To change the limit for every task in the queue, set `retry.max_attempts` on the queue instead; see [queues](https://pushqueue.dev/docs/concepts/queues/). SDKs use their own casing for these fields (`maxAttempts` in TypeScript and Java, `max_attempts` in Python, `MaxAttempts` in Go and .NET).

:::caution[Both retry limits must be reached]
If `max_attempts` and `max_retry_duration_seconds` are both set (on the task, or one inherited from the queue), pushq keeps retrying until **both** are reached, the same as Cloud Tasks. A per-task `max_attempts: 3` on a queue with `max_retry_duration_seconds: 86400` still retries for a day. Set the duration to `0` (unlimited) to let `max_attempts` decide alone.
:::

## Delete a task to stop its retries

Deleting a task stops it immediately, whatever state it is in. Use it for a task that is already retrying and that you know is hopeless.


**TypeScript**

```ts
await pq.deleteTask("webhooks", "order-created-1234");
```

**Python**

```python
pq.delete_task("webhooks", "order-created-1234")
```

**Go**

```go
err := pq.DeleteTask(ctx, "webhooks", "order-created-1234")
```

**Java**

```java
pq.deleteTask("webhooks", "order-created-1234");
```

**.NET**

```csharp
await pq.DeleteTaskAsync("webhooks", "order-created-1234");
```

**curl**

```bash
curl -X DELETE https://api.pushqueue.dev/v1/queues/webhooks/tasks/order-created-1234 \
  -H "Authorization: Bearer $PUSHQ_API_KEY"
```

- A pending task is never dispatched again.
- A running task's in-flight request is not cancelled, but its result is discarded and it won't be retried.
- A deleted task is not copied to the dead-letter queue, and its ID stays reserved for the dedup window (1 hour on self-hosted defaults). See [task deduplication](https://pushqueue.dev/docs/patterns/deduplication/).

To stop every task in a queue at once, pause the queue (dispatch stops, tasks are kept) or purge it (tasks are deleted).

## Pitfalls

- **Returning 4xx for bad input retries it up to 100 times.** Validation errors are permanent; answer them with a `2xx` and record the problem.
- **Returning 2xx too eagerly loses work.** Only acknowledge errors you are sure a retry can't fix. Timeouts and `5xx` from your dependencies usually clear up.
- **A failure in the dead-letter queue retries too.** Dead-lettered copies get the dead-letter queue's own retry settings and a new task ID. Give that queue a sensible `max_attempts`, and see [replaying dead letters](https://pushqueue.dev/docs/patterns/replay-dead-letters/).
- **The dead-letter queue must exist.** If the queue named in `dead_letter_queue` doesn't exist when a task runs out of retries, the copy is not made (the server logs the error) and only the `failed` task remains.
- **Use `Retry-After` for "not yet", not "never".** A `429` or `503` with `Retry-After` delays the retry; it doesn't stop it.

## Read more

- [Retry backoff and when retries stop](https://pushqueue.dev/docs/concepts/retries/)
- [Dead-letter queues for failed tasks](https://pushqueue.dev/docs/concepts/dead-letter-queues/)
- [Replay tasks from a dead-letter queue](https://pushqueue.dev/docs/patterns/replay-dead-letters/)
- [Idempotent webhook handlers](https://pushqueue.dev/docs/patterns/idempotent-handlers/)
- [Troubleshooting failing tasks](https://pushqueue.dev/docs/guides/troubleshooting/)
