# Limites de velocidade (por número, por conta, por chave)

`POST /v1/messages`

Três limites, e cada um conta separado. **Por número** (`connection`), só `POST /v1/messages`: o ritmo que a Meta dá a esse número — **Coexistência 20 por segundo, Cloud API 80 por segundo**, com uma rajada de um segundo. Um número a todo vapor **não segura os outros** da sua conta. **Por conta** (`account`), só `POST /v1/messages`, por minuto conforme o plano: teste 600, Starter 1.200, Studio 2.400, Agencia 4.800, Escala 9.600; plano sob medida sem teto; nunca menos de 600 por chave ativa. **Por chave** (`key`): todo o resto de `/v1`, **600 pedidos por minuto**. Um envio não gasta os 600 da chave.

## Exemplos

### cURL

```bash
curl -i -X POST https://api.waiaconnect.com/v1/messages \
  -H "Authorization: Bearer wc_live_YOUR_API_KEY" \
  -H "Idempotency-Key: 7c0e…-same-on-every-retry" \
  -H "Content-Type: application/json" \
  -d '{"connectionId":"conn_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX","to":"5493511234567","type":"text","text":{"body":"Hi"}}'
# 202 → X-RateLimit-Scope: connection  X-RateLimit-Limit: 20  X-RateLimit-Remaining: 19
# 429 → Retry-After: 1
# { "error": { "code": "RATE_LIMITED", "limit": "connection", "connectionId": "conn_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
#              "retryAfterSeconds": 1, "details": { "limitPerSecond": 20, "burst": 20 } } }
```

### Node.js

```javascript
// One limiter PER NUMBER (Coexistence 20/s, Cloud API 80/s); retry 429 with the SAME key.
const pausedUntil = new Map(); // connectionId → ms (pause only the number that hit its limit)
async function send(msg, idempotencyKey) {
  for (;;) {
    const wait = (pausedUntil.get(msg.connectionId) || 0) - Date.now();
    if (wait > 0) await new Promise(r => setTimeout(r, wait));
    const res = await fetch("https://api.waiaconnect.com/v1/messages", {
      method: "POST",
      headers: { "Authorization": "Bearer wc_live_YOUR_API_KEY", "Idempotency-Key": idempotencyKey, "Content-Type": "application/json" },
      body: JSON.stringify(msg)
    });
    if (res.status !== 429) return res.json();
    const { error } = await res.json();
    if (error.code !== "RATE_LIMITED") return { error }; // quota: do not retry
    const until = Date.now() + Number(res.headers.get("retry-after") || error.retryAfterSeconds) * 1000;
    if (error.limit === "connection") pausedUntil.set(msg.connectionId, until);
    else await new Promise(r => setTimeout(r, until - Date.now())); // account or key: everything waits
  }
}
```

### PHP

```php
<?php
// Retry a 429 with the SAME Idempotency-Key, after Retry-After.
function send(array $msg, string $idemKey): array {
  for ($i = 0; $i < 5; $i++) {
    $ch = curl_init("https://api.waiaconnect.com/v1/messages");
    curl_setopt_array($ch, [
      CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_HEADER => true,
      CURLOPT_HTTPHEADER => ["Authorization: Bearer wc_live_YOUR_API_KEY", "Idempotency-Key: $idemKey", "Content-Type: application/json"],
      CURLOPT_POSTFIELDS => json_encode($msg),
    ]);
    $raw = curl_exec($ch);
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $body = json_decode(substr($raw, curl_getinfo($ch, CURLINFO_HEADER_SIZE)), true);
    if ($status !== 429 || ($body["error"]["code"] ?? "") !== "RATE_LIMITED") return $body;
    sleep(max(1, (int)$body["error"]["retryAfterSeconds"])); // = Retry-After
  }
  return $body;
}
```

### Python

```python
import time, requests
# Retry a 429 with the SAME Idempotency-Key, after Retry-After.
def send(msg, idem_key):
    for _ in range(5):
        res = requests.post("https://api.waiaconnect.com/v1/messages", json=msg, headers={
            "Authorization": "Bearer wc_live_YOUR_API_KEY", "Idempotency-Key": idem_key})
        if res.status_code != 429 or res.json()["error"]["code"] != "RATE_LIMITED":
            return res.json()
        err = res.json()["error"]  # err["limit"]: connection | account | key
        time.sleep(int(res.headers.get("Retry-After", err["retryAfterSeconds"])))
    return res.json()
```

## Notas

- **O 429:** o `code` é o de sempre, `RATE_LIMITED`. Soma `error.limit` (`connection`, `account` ou `key`: qual te segurou), `error.connectionId` (só se foi o do número) e `error.retryAfterSeconds`, igual ao header `Retry-After`. Para `account` e `key`, a cifra está em `details.limitPerMinute`; para `connection`, em `details.limitPerSecond` e `details.burst`.
- **Toda resposta de `/v1`** traz `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset` (segundos até encher de novo) e `X-RateLimit-Scope`, do limite que mais aperta naquele momento.
- **Como montar sua fila:** um limitador por número (até 20/s na Coexistência, 80/s na Cloud API), todos abaixo da cifra por minuto da sua conta. Diante de um 429, espere `Retry-After` e tente de novo com a **mesma** `Idempotency-Key`: um 429 não cria nada, a nova tentativa é segura. Com `limit: "connection"` pause só esse número; com `account` ou `key`, tudo.
- **Aceito não é entregue:** depois de um 202, a fila passa cada mensagem à Meta no ritmo dela e não perde nenhuma. `GET /v1/usage/by-connection` conta mensagens, não pedidos: um 429 não aparece ali.
- Precisa de outra cifra de conta para um caso especial? Escreva para nós: ajusta-se conta por conta.
