> ## Documentation Index
> Fetch the complete documentation index at: https://docs.oxenty.api.br/llms.txt
> Use this file to discover all available pages before exploring further.

# Rate Limits

> Entenda os limites de requisições da Oxenty API

A Oxenty API implementa rate limiting para garantir estabilidade e justiça no uso dos recursos. Os limites variam de acordo com o plano contratado.

## Limites por Plano

<Tabs>
  <Tab title="Free">
    | Recurso            | Limite |
    | ------------------ | ------ |
    | Requisições/minuto | 40     |
    | Sessões ativas     | 1      |
    | Mensagens/dia      | 480    |
    | Webhooks           | 1      |
  </Tab>

  <Tab title="Inicial">
    | Recurso            | Limite     |
    | ------------------ | ---------- |
    | Requisições/minuto | 120        |
    | Sessões ativas     | 1          |
    | Mensagens/dia      | Ilimitadas |
    | Webhooks           | 1          |
  </Tab>

  <Tab title="Intermediário">
    | Recurso            | Limite     |
    | ------------------ | ---------- |
    | Requisições/minuto | 360        |
    | Sessões ativas     | 3          |
    | Mensagens/dia      | Ilimitadas |
    | Webhooks           | 3          |
  </Tab>

  <Tab title="Empresarial">
    | Recurso            | Limite     |
    | ------------------ | ---------- |
    | Requisições/minuto | Ilimitadas |
    | Sessões ativas     | 10         |
    | Mensagens/dia      | Ilimitadas |
    | Webhooks           | Ilimitadas |
  </Tab>
</Tabs>

***

## Headers de Rate Limit

Toda resposta da API inclui headers informativos sobre o estado atual dos limites:

```
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 950
X-RateLimit-Reset: 1704067200
```

| Header                  | Descrição                                  |
| ----------------------- | ------------------------------------------ |
| `X-RateLimit-Limit`     | Total de requisições permitidas no período |
| `X-RateLimit-Remaining` | Requisições restantes no período atual     |
| `X-RateLimit-Reset`     | Timestamp Unix de quando o limite reseta   |

***

## Resposta de Limite Excedido

Quando você excede o rate limit, a API retorna status `429 Too Many Requests`:

```json theme={"system"}
{
  "statusCode": 429,
  "error": "TOO_MANY_REQUESTS",
  "message": "Rate limit exceeded. Try again in 45 seconds.",
  "retryAfter": 45
}
```

O header `Retry-After` também é incluído indicando em quantos segundos você pode tentar novamente.

***

## Estratégias de Tratamento

### Exponential Backoff

Implemente retries com backoff exponencial para lidar com rate limits:

<CodeGroup>
  ```typescript TypeScript theme={"system"}
  async function requestWithRetry<T>(
    fn: () => Promise<T>,
    maxRetries = 3
  ): Promise<T> {
    let lastError: Error;
    
    for (let attempt = 0; attempt < maxRetries; attempt++) {
      try {
        return await fn();
      } catch (error: any) {
        if (error.status !== 429) throw error;
        
        lastError = error;
        const delay = Math.pow(2, attempt) * 1000; // 1s, 2s, 4s
        await new Promise(resolve => setTimeout(resolve, delay));
      }
    }
    
    throw lastError;
  }

  // Uso
  const sessions = await requestWithRetry(() => 
    client.sessions.list()
  );
  ```

  ```python Python theme={"system"}
  import time
  import requests

  def request_with_retry(url, headers, max_retries=3):
      for attempt in range(max_retries):
          response = requests.get(url, headers=headers)
          
          if response.status_code != 429:
              return response
          
          delay = (2 ** attempt)  # 1s, 2s, 4s
          time.sleep(delay)
      
      return response

  # Uso
  response = request_with_retry(
    'https://api.oxenty.api.br/api/sessions',
      headers={'X-API-Key': API_KEY}
  )
  ```
</CodeGroup>

### Queue de Requisições

Para alto volume, implemente uma queue que respeite os limites:

```typescript theme={"system"}
class RequestQueue {
  private queue: Array<() => Promise<void>> = [];
  private processing = false;
  private requestsPerMinute: number;
  private interval: number;

  constructor(requestsPerMinute: number) {
    this.requestsPerMinute = requestsPerMinute;
    this.interval = 60000 / requestsPerMinute;
  }

  async add<T>(fn: () => Promise<T>): Promise<T> {
    return new Promise((resolve, reject) => {
      this.queue.push(async () => {
        try {
          const result = await fn();
          resolve(result);
        } catch (error) {
          reject(error);
        }
      });
      this.process();
    });
  }

  private async process() {
    if (this.processing) return;
    this.processing = true;

    while (this.queue.length > 0) {
      const fn = this.queue.shift();
      if (fn) {
        await fn();
        await new Promise(r => setTimeout(r, this.interval));
      }
    }

    this.processing = false;
  }
}

// Uso
const queue = new RequestQueue(60); // 60 req/min

await queue.add(() => client.messages.send(sessionId, message1));
await queue.add(() => client.messages.send(sessionId, message2));
```

***

## Rate Limits por Endpoint

Alguns endpoints possuem limites específicos mais restritivos:

| Endpoint              | Limite    | Motivo                      |
| --------------------- | --------- | --------------------------- |
| `POST /sessions`      | 5/minuto  | Criação de sessão é custosa |
| `POST /messages/send` | Por plano | Evitar spam                 |
| `GET /contacts/check` | 10/minuto | Rate limit do WhatsApp      |
| `POST /groups`        | 3/minuto  | Rate limit do WhatsApp      |

<Warning>
  O WhatsApp possui seus próprios rate limits internos. Mesmo que a API permita, envios muito frequentes podem resultar em ban temporário do número.
</Warning>

***

## Boas Práticas

<Steps>
  <Step title="Monitore os Headers">
    Sempre verifique `X-RateLimit-Remaining` antes de fazer múltiplas requisições.
  </Step>

  <Step title="Implemente Caching">
    Cache respostas de endpoints que mudam pouco (ex: lista de sessões).
  </Step>

  <Step title="Use Webhooks">
    Ao invés de polling, configure webhooks para receber eventos em tempo real.
  </Step>

  <Step title="Batch quando possível">
    Alguns endpoints suportam operações em lote. Prefira enviar múltiplos itens em uma requisição.
  </Step>
</Steps>

***

## Upgrade de Plano

Se você está frequentemente atingindo os limites, considere fazer upgrade do seu plano:

<CardGroup cols={2}>
  <Card title="Ver Planos" icon="credit-card" href="https://oxenty.api.br/#pricing">
    Compare os planos disponíveis
  </Card>

  <Card title="WhatsApp" icon="phone" href="https://wa.me/558781148453">
    Vendas e planos Enterprise: +55 87 8114-8453
  </Card>
</CardGroup>
