# Rate limits (per number, per account, per key)

`POST /v1/messages`

Three limits, each one counted separately. **Per number** (`connection`), `POST /v1/messages` only: the pace Meta gives that number — **Coexistence 20 per second, Cloud API 80 per second**, with a one-second burst. One number at full speed **does not slow down the others** of your account. **Per account** (`account`), `POST /v1/messages` only, per minute by plan: trial 600, Starter 1,200, Studio 2,400, Agencia 4,800, Escala 9,600; custom plan, no cap; never below 600 per active key. **Per key** (`key`): everything else in `/v1`, **600 requests per minute**. A send does not use the key's 600.

## Examples

### 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()
```

## Notes

- **The 429:** the `code` is the usual `RATE_LIMITED`. It adds `error.limit` (`connection`, `account` or `key`: which one stopped you), `error.connectionId` (only when it was the number's) and `error.retryAfterSeconds`, equal to the `Retry-After` header. For `account` and `key` the figure is in `details.limitPerMinute`; for `connection`, in `details.limitPerSecond` and `details.burst`.
- **Every `/v1` response** carries `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset` (seconds until it is full again) and `X-RateLimit-Scope`, for the limit that is tightest at that moment.
- **How to build your queue:** one limiter per number (up to 20/s on Coexistence, 80/s on the Cloud API), all of them under your account's per-minute figure. On a 429, wait `Retry-After` and retry with the **same** `Idempotency-Key`: a 429 creates nothing, so the retry is safe. With `limit: "connection"` pause only that number; with `account` or `key`, everything.
- **Accepted is not delivered:** after a 202 the queue hands each message to Meta at its own pace and loses none. `GET /v1/usage/by-connection` counts messages, not requests: a 429 does not show up there.
- Need a different account figure for a special case? Write to us: it is set account by account.
