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

# Rate Limits

> Understanding and managing API rate limits

To ensure the stability and availability of our API for all users, Meibel implements rate limiting. This page explains our rate limiting system and how to handle rate limit errors.

## Understanding Rate Limits

Rate limits are applied on a per-API-key basis and vary depending on your subscription plan. Rate limits are calculated based on rolling time windows, typically per minute and per day.

## Rate Limit Headers

Every API response includes headers that provide information about your current rate limit status:

| Header                  | Description                                                                |
| ----------------------- | -------------------------------------------------------------------------- |
| `X-RateLimit-Limit`     | The maximum number of requests allowed in the current time window          |
| `X-RateLimit-Remaining` | The number of requests remaining in the current time window                |
| `X-RateLimit-Reset`     | The time at which the current rate limit window resets (UTC epoch seconds) |

Example headers:

```
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1620000000
```

## Rate Limit Errors

When you exceed your rate limit, the API returns a `429 Too Many Requests` error:

```json theme={null}
{
  "message": "Rate limit exceeded. Please retry after 45 seconds."
}
```

The response will include a `Retry-After` header indicating how many seconds to wait.

## Handling Rate Limits

<CodeGroup>
  ```python Python theme={null}
  from meibel import MeibelClient
  from meibel.exceptions import RateLimitError
  import time
  import os

  client = MeibelClient(api_key=os.getenv("MEIBEL_API_KEY"))

  def request_with_retry(fn, *args, max_retries=5, **kwargs):
      for attempt in range(max_retries):
          try:
              return fn(*args, **kwargs)
          except RateLimitError as e:
              if attempt == max_retries - 1:
                  raise
              wait = e.retry_after or (2 ** attempt)
              print(f"Rate limited. Retrying in {wait}s...")
              time.sleep(wait)
  ```

  ```typescript TypeScript theme={null}
  import { MeibelClient, RateLimitError } from 'meibel';

  const client = new MeibelClient({ apiKey: process.env.MEIBEL_API_KEY });

  async function requestWithRetry<T>(fn: () => Promise<T>, maxRetries = 5): Promise<T> {
    for (let attempt = 0; attempt < maxRetries; attempt++) {
      try {
        return await fn();
      } catch (e) {
        if (!(e instanceof RateLimitError) || attempt === maxRetries - 1) throw e;
        const wait = e.retryAfter ?? 2 ** attempt;
        console.log(`Rate limited. Retrying in ${wait}s...`);
        await new Promise(r => setTimeout(r, wait * 1000));
      }
    }
    throw new Error('Max retries exceeded');
  }
  ```
</CodeGroup>

## Best Practices

<Steps>
  <Step title="Implement backoff and retry logic">
    When you receive a 429 response, use the `Retry-After` header to determine when to retry. Use exponential backoff as a fallback.
  </Step>

  <Step title="Monitor your usage">
    Check rate limit headers in API responses to stay within your limits.
  </Step>

  <Step title="Batch requests when possible">
    Combine operations to reduce the number of requests.
  </Step>

  <Step title="Cache responses">
    Cache API responses that don't change frequently to reduce request volume.
  </Step>
</Steps>

## Increasing Your Rate Limits

If you need higher rate limits:

1. **Contact sales**: Enterprise customers can request custom rate limits by contacting [sales@meibel.ai](mailto:sales@meibel.ai)
2. **Optimize your usage**: Review our best practices to ensure efficient API usage

<Warning>
  Repeatedly exceeding your rate limits may result in temporary restrictions on your API key. Always implement proper rate limit handling in production applications.
</Warning>
