# Receive and delete messages

Take up to ten messages off a queue, long-polling for them, and delete each one with its receipt handle once it is processed.

Replace _my-queue_ with the name of your queue. A receive is a real receive wherever you make it:
the messages are hidden from your other consumers until you delete them, release them, or their
visibility timeout ends. See [Message delivery](message-delivery.md).

## Prerequisites

- Permission for `queue:ReceiveMessage` and `queue:DeleteMessage` on the queue.
  `queue:ReceiveMessage` is a write: the read-only preset `QueueReadOnlyAccess` does not include it.
- In the console, also `queue:GetQueueAttributes` to open the queue's page (without it the page is
  not found). **Release** also needs `queue:ChangeMessageVisibility`. Without
  `queue:ReceiveMessage` the **Receive messages** section says "Your policies do not grant
  queue:ReceiveMessage on this queue; ask an administrator." and has no **Poll for messages**;
  without `queue:DeleteMessage` or `queue:ChangeMessageVisibility`, **Delete** or **Release** is
  unavailable.

## Receive and delete

**Console**
1. Open the queue, then choose **Send and receive**.
2. Under **Receive messages**, choose **Poll for messages**. The console takes up to 10 messages,
   waiting up to 5 seconds for one to arrive, and lists each with its id, when it was sent, and how
   many times it has been received.
3. On each message you have dealt with, choose **Delete**. To give a message back to the queue at
   once, choose **Release** instead.

**CLI**
```sh
dcloud queue messages receive my-queue --max-messages 10 --wait-seconds 20
dcloud queue messages delete my-queue receipt-handle
```

Replace _receipt-handle_ with a message's `receiptHandle` from the receive.

**API**
```http
POST /queue/api/queues/my-queue/receive
{ "maxMessages": 10, "waitSeconds": 20 }
```

The answer is `200` with `messages`, empty when none arrived in time. Each message has
`messageId`, `receiptHandle`, `body`, `md5OfBody`, `attributes`, `attributeTypes`, `sentAt`,
`receiveCount`, `firstReceivedAt`, `deadLetterSourceQueueId` (in a dead-letter queue, the id of
the queue the message came from), and on a FIFO queue `messageGroupId`,
`messageDeduplicationId` and `sequenceNumber`. `attributeTypes` names the attributes an SQS client
sent with a type other than `String`; a `Binary` attribute's value is base64.

Delete one message with its receipt handle:

```http
DELETE /queue/api/queues/my-queue/messages/{receiptHandle}
```

Or up to 10 in one request, each with an `id` of your choosing:

```http
POST /queue/api/queues/my-queue/messages/delete-batch
{ "entries": [ { "id": "a", "receiptHandle": "…" } ] }
```

The batch answers `200` with `successful` and `failed` per `id`; a failed entry does not fail the
others.

**Terraform:** not available. Receiving and deleting messages are actions, not configuration.

A receive that names no `maxMessages` takes 1 message; one that names no `waitSeconds` or
`visibilityTimeoutSeconds` uses the queue's receive wait and visibility timeout.

## A consumer in Node.js

`fetch` is enough. This loop long-polls, processes, and deletes in batches; `EWS_URL` is the
Deutsche Cloud Console's address, and the access key is yours (see [Security](security.md)):

```js
const BASE = `${process.env.EWS_URL}/queue/api/queues/my-queue`;
const AUTH = `EWS-ACCESS-KEY ${process.env.EWS_ACCESS_KEY_ID}:${process.env.EWS_SECRET_ACCESS_KEY}`;

async function call(method, path, body) {
  const res = await fetch(`${BASE}${path}`, {
    method,
    headers: { Authorization: AUTH, 'Content-Type': 'application/json' },
    body: body === undefined ? undefined : JSON.stringify(body),
  });
  const json = await res.json();
  if (!json.success) throw new Error(`${json.code ?? res.status}: ${json.error}`);
  return json.data;
}

for (;;) {
  const { messages } = await call('POST', '/receive', { maxMessages: 10, waitSeconds: 20 });
  const done = [];
  for (const m of messages) {
    try {
      await handle(JSON.parse(m.body));
      done.push({ id: m.messageId, receiptHandle: m.receiptHandle });
    } catch (err) {
      console.error(err); // not deleted: received again when its visibility timeout ends
    }
  }
  if (done.length > 0) await call('POST', '/messages/delete-batch', { entries: done });
}
```

## Result

Deleted messages are gone for good. Deleting a message that is already gone succeeds, so a retried
delete is safe.

## When a receive or delete is refused

- `400` with code `ReceiptHandleIsInvalid`: "The message was received again since this receipt was
  issued; only the latest receipt can delete it." Someone else now holds the message.
- `400` "That is not a receipt handle."
- `403` with code `OverLimit` when 20,000 messages of the queue are in flight: delete processed
  messages, or shorten the visibility timeout.
- `403` "This organization already holds 50 long polls open. Use fewer consumers, or receive
  several messages per call." for a receive that would wait.
- `429` with code `Throttling` and a `Retry-After` header when your organization makes more queue
  requests than the rate in [Quotas](quotas.md).

## Related

- [Change the visibility of a message](change-message-visibility.md)
- [Message delivery](message-delivery.md)
