# Rate Limiting

The Veritas B2B API implements rate limiting to ensure fair usage and system
stability.

## Rate Limit Headers

All API responses include rate limit information in headers:

| Header                  | Description                                 |
| ----------------------- | ------------------------------------------- |
| `X-RateLimit-Limit`     | Maximum requests allowed in the window      |
| `X-RateLimit-Remaining` | Requests remaining in current window        |
| `X-RateLimit-Reset`     | Timestamp when the window resets (ISO 8601) |

**Example Response Headers:**

```
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 847
X-RateLimit-Reset: 2024-01-15T15:00:00Z
```

## Rate Limits by Tier

| Tier       | Requests/Hour | Requests/Day | Concurrent |
| ---------- | ------------- | ------------ | ---------- |
| Free       | 100           | 1,000        | 5          |
| Basic      | 1,000         | 10,000       | 10         |
| Pro        | 10,000        | 100,000      | 25         |
| Enterprise | Custom        | Custom       | Custom     |

**Sandbox (Test Keys):**

| Limit         | Value   |
| ------------- | ------- |
| Requests/Hour | 10,000  |
| Requests/Day  | 100,000 |

## Rate Limit Response

When you exceed the rate limit, you'll receive a `429 Too Many Requests`
response:

```json
{
  "error": "Rate limit exceeded. Retry after 60 seconds.",
  "code": "RATE_LIMIT_EXCEEDED",
  "retryAfter": 60
}
```

**Headers:**

```
HTTP/1.1 429 Too Many Requests
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 2024-01-15T15:00:00Z
Retry-After: 60
```

## Handling Rate Limits

### JavaScript SDK

The SDK automatically handles rate limits with retry logic:

```javascript
const client = new VeritasClient({
  apiKey: 'sk_live_...',
  retry: true, // Enable automatic retries (default: true)
  maxRetries: 3, // Maximum retry attempts (default: 3)
});

// SDK will automatically retry rate-limited requests
const articles = await client.feed.list();
```

For custom handling:

```javascript
import { RateLimitError } from '@veritas/b2b-sdk';

try {
  const articles = await client.feed.list();
} catch (error) {
  if (error instanceof RateLimitError) {
    console.log(`Rate limited. Reset at: ${error.resetAt}`);
    console.log(`Retry after: ${error.retryAfter} seconds`);

    // Wait and retry
    await sleep(error.retryAfter * 1000);
    const articles = await client.feed.list();
  }
}
```

### Python SDK

```python
from veritas_sdk import VeritasClient, RateLimitError
import asyncio

client = VeritasClient(
    api_key="sk_live_...",
    retry=True,       # Enable automatic retries (default: True)
    max_retries=3,    # Maximum retry attempts (default: 3)
)

try:
    articles = await client.feed.list()
except RateLimitError as e:
    print(f"Rate limited. Reset at: {e.reset_at}")
    print(f"Retry after: {e.retry_after} seconds")

    # Wait and retry
    await asyncio.sleep(e.retry_after)
    articles = await client.feed.list()
```

### Manual Implementation

```javascript
async function fetchWithRateLimit(fn) {
  try {
    return await fn();
  } catch (error) {
    if (error.status === 429) {
      const retryAfter = parseInt(error.headers?.['retry-after'] || '60', 10);
      console.log(`Rate limited. Waiting ${retryAfter}s...`);
      await sleep(retryAfter * 1000);
      return await fn();
    }
    throw error;
  }
}
```

## Best Practices

### 1. Monitor Your Usage

Check rate limit headers on every response:

```javascript
const response = await fetch('/api/v1/b2b/feed', {
  headers: { 'X-API-Key': apiKey },
});

const remaining = response.headers.get('X-RateLimit-Remaining');
const reset = response.headers.get('X-RateLimit-Reset');

if (remaining < 100) {
  console.warn(`Low rate limit: ${remaining} remaining, resets at ${reset}`);
}
```

### 2. Implement Request Queuing

For high-volume applications, queue requests to stay within limits:

```javascript
class RateLimitedClient {
  constructor(requestsPerSecond) {
    this.queue = [];
    this.interval = 1000 / requestsPerSecond;
    this.processing = false;
  }

  async request(fn) {
    return new Promise((resolve, reject) => {
      this.queue.push({ fn, resolve, reject });
      this.processQueue();
    });
  }

  async processQueue() {
    if (this.processing || this.queue.length === 0) return;
    this.processing = true;

    while (this.queue.length > 0) {
      const { fn, resolve, reject } = this.queue.shift();
      try {
        const result = await fn();
        resolve(result);
      } catch (error) {
        reject(error);
      }
      await sleep(this.interval);
    }

    this.processing = false;
  }
}
```

### 3. Cache Responses

Reduce API calls by caching responses:

```javascript
const cache = new Map();
const CACHE_TTL = 60 * 1000; // 1 minute

async function getCachedArticle(id) {
  const cached = cache.get(id);
  if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
    return cached.data;
  }

  const response = await client.feed.get(id);
  cache.set(id, { data: response, timestamp: Date.now() });
  return response;
}
```

### 4. Use Pagination Efficiently

Fetch only what you need:

```javascript
// Bad: Fetching all articles at once
const all = await client.feed.all();

// Good: Use pagination with limits
for await (const article of client.feed.iterate({ limit: 50 })) {
  process(article);
  if (shouldStop()) break;
}
```

### 5. Batch Related Requests

Minimize total requests by batching:

```javascript
// Instead of multiple individual requests
const article = await client.feed.get(id);
const media = await client.media.forArticle(id);

// Consider fetching article with full content (includes some media info)
const { article } = await client.feed.get(id);
```

### 6. Use Webhooks for Real-time Data

Instead of polling, use webhooks for notifications:

```javascript
// Bad: Polling every minute
setInterval(async () => {
  const articles = await client.feed.list({ from: lastCheck });
  // Process new articles
}, 60000);

// Good: Set up webhook for instant notifications
await client.alerts.create({
  name: 'New Articles',
  alertType: 'topic',
  filters: { topics: ['politics'] },
  webhookUrl: 'https://your-server.com/webhook',
  frequency: 'instant',
});
```

## Rate Limit Exemptions

Enterprise customers may request rate limit exemptions for specific use cases:

- Data migration
- Bulk historical analysis
- Real-time streaming integrations

Contact your account manager or sales@veritas.news for custom arrangements.

## Monitoring & Alerts

We recommend setting up monitoring for your rate limit usage:

1. **Track remaining requests** - Log `X-RateLimit-Remaining` values
2. **Alert on low limits** - Notify when remaining < 10% of limit
3. **Track 429 responses** - Monitor rate limit hit frequency
4. **Review usage patterns** - Optimize high-frequency endpoints

## Upgrading Your Limit

If you consistently hit rate limits:

1. Review your implementation for inefficiencies
2. Implement caching and request optimization
3. Contact sales@veritas.news to discuss tier upgrades
4. Enterprise plans offer custom limits and dedicated support
