# Rate Limits & API Quotas

The Cineamo API implements rate limiting to ensure service stability and fair usage.

## Rate Limit Overview

Rate limits restrict the number of API requests you can make within a time window.

### Default Limits

- **Authenticated requests**: 1000 requests per hour
- **Burst limit**: 50 requests per minute
- **Concurrent requests**: 10 simultaneous requests

## Rate Limit Headers

Every API response includes rate limit information in the headers:

```http
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 987
X-RateLimit-Reset: 1640995200
```

### Header Descriptions

- `X-RateLimit-Limit` - Maximum requests allowed in the time window
- `X-RateLimit-Remaining` - Number of requests remaining
- `X-RateLimit-Reset` - Unix timestamp when the limit resets

## Handling Rate Limits

### Check Remaining Requests

Monitor the `X-RateLimit-Remaining` header to track your usage:

```javascript
const response = await fetch('https://api.cineamo.com/api/v1/movies', {
  headers: {
    'Authorization': `Bearer ${accessToken}`
  }
});

const remaining = response.headers.get('X-RateLimit-Remaining');
console.log(`Requests remaining: ${remaining}`);
```

### Handle 429 Responses

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

```json
{
  "error": {
    "code": "RATE_LIMIT_EXCEEDED",
    "message": "Rate limit exceeded. Please retry after 300 seconds.",
    "retry_after": 300
  }
}
```

The `Retry-After` header indicates when you can retry:

```http
HTTP/1.1 429 Too Many Requests
Retry-After: 300
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1640995200
```

## Implementing Backoff

### Exponential Backoff Strategy

```javascript
async function makeRequestWithBackoff(url, maxRetries = 3) {
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      const response = await fetch(url, {
        headers: {
          'Authorization': `Bearer ${accessToken}`
        }
      });

      if (response.status === 429) {
        const retryAfter = response.headers.get('Retry-After');
        const delay = retryAfter ? parseInt(retryAfter) * 1000 : Math.pow(2, attempt) * 1000;

        console.log(`Rate limited. Retrying after ${delay}ms`);
        await new Promise(resolve => setTimeout(resolve, delay));
        continue;
      }

      return await response.json();
    } catch (error) {
      if (attempt === maxRetries - 1) throw error;
    }
  }
}
```

## Best Practices

### Optimize Request Patterns

- **Batch requests** when possible
- **Cache responses** to reduce duplicate requests
- **Use webhooks** instead of polling
- **Request only needed data** using filters and field selection

### Monitor Usage

```javascript
// Track rate limit status
function checkRateLimitStatus(response) {
  const limit = response.headers.get('X-RateLimit-Limit');
  const remaining = response.headers.get('X-RateLimit-Remaining');
  const reset = response.headers.get('X-RateLimit-Reset');

  const resetDate = new Date(parseInt(reset) * 1000);
  const percentage = (remaining / limit) * 100;

  console.log(`Rate limit: ${remaining}/${limit} (${percentage.toFixed(1)}%)`);
  console.log(`Resets at: ${resetDate.toISOString()}`);

  // Alert if usage is high
  if (percentage < 10) {
    console.warn('⚠️ Rate limit nearly exceeded!');
  }
}
```

### Distribute Load

- **Spread requests** over time
- **Avoid burst patterns** that quickly consume limits
- **Implement request queuing** for high-volume applications
- **Use multiple API keys** for different services (with approval)

## Increasing Rate Limits

If your application requires higher rate limits:

1. Contact your Cineamo account manager
2. Provide use case and expected request volume
3. Discuss enterprise tier options

## Rate Limit by Endpoint

Some endpoints have different rate limits:

| Endpoint | Rate Limit | Notes |
|----------|------------|-------|
| `/api/v1/movies` | Standard | 1000/hour |
| `/api/v1/orders` | Standard | 1000/hour |
| `/api/v1/analytics` | Reduced | 100/hour |
| `/api/v1/exports` | Limited | 10/hour |

Check individual endpoint documentation for specific limits.
