# Set a dead-letter queue

Name the queue that takes a message after a set number of receives without a delete, change the number, or remove the dead-letter queue.

Replace _my-queue_ with the name of your queue and _my-queue-dlq_ with the queue that should take its
failed messages. How messages move is described in [Dead-letter queues](dead-letter-queues.md).

## Prerequisites

- Permission for `queue:SetQueueAttributes` on _my-queue_. For the console, also
  `queue:GetQueueAttributes` on it, to open its page.
- _my-queue-dlq_ exists in the same organization and region, is not _my-queue_ itself, and is of the
  same type: FIFO for a FIFO queue, standard for a standard queue.

## Set or change the dead-letter queue

**Console**
1. Open _my-queue_, then choose **Settings**.
2. Under **Dead-letter queue**, for **Queue**, choose my-queue-dlq. To remove the dead-letter
   queue, choose **None**.
3. For **Receives before moving**, enter a number from 1 to 1000.
4. Choose **Save**.

**Save** also saves the settings under **Delivery**.

**CLI**
```sh
dcloud queue queues set-attributes my-queue --dead-letter-queue '{"name":"my-queue-dlq","maxReceiveCount":5}'
```

**API**
```http
PATCH /queue/api/queues/my-queue
{ "deadLetterQueue": { "name": "my-queue-dlq", "maxReceiveCount": 5 } }
```

To remove the dead-letter queue:

```http
PATCH /queue/api/queues/my-queue
{ "deadLetterQueue": null }
```

**Terraform**
```hcl
resource "dcloud_queue" "main" {
  name = "my-queue"
  dead_letter_queue = jsonencode({
    name            = "my-queue-dlq"
    maxReceiveCount = 5
  })
}
```

Removing `dead_letter_queue` from the configuration does not remove the dead-letter queue from the
queue; use the console or the API for that.

## Result

From now on a message of _my-queue_ moves to _my-queue-dlq_ once it has been received the given
number of times without being deleted. After you remove the dead-letter queue, failed messages are
delivered again until they expire.

## When the change is refused

- `400` "A queue cannot be its own dead-letter queue."
- `404` "There is no queue named “my-queue-dlq” to use as the dead-letter queue."
- `400` "The dead-letter queue of a FIFO queue must also be a FIFO queue." or "The dead-letter queue
  of a standard queue must also be a standard queue."

## Related

- [Redrive a dead-letter queue](redrive-a-dead-letter-queue.md)
- [Change a queue's settings](change-queue-settings.md)
