# API Rate Limiting

## Overview

Our API implements rate limiting to ensure fair usage and optimal performance for all partners. Rate limits help protect the service from abuse while providing reliable access to our verification services.

***

### Understanding Rate Limits

#### What is Rate Limiting?

Rate limiting controls how many API requests you can make within a specific time window. When you exceed these limits, you'll receive a temporary block until the time window resets.

#### Why We Use Rate Limits

* **Fair Usage**: Ensures all partners get reliable access to the API
* **System Stability**: Protects our infrastructure from overload
* **Performance**: Maintains fast response times for everyone
* **Security**: Prevents abuse and malicious activities

***

### Rate Limit Structure

#### Global Limits

All API keys are subject to a baseline rate limit:

* **100 requests per minute**

#### API Key Specific Limits

Your specific rate limits may vary based on:

* Your subscription plan
* API key configuration
* Endpoint type being accessed

***

### Monitoring Your Usage

#### Rate Limit Headers

Every API response includes headers showing your current rate limit status:

```http
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1625097600
```

**Header Explanations:**

* `X-RateLimit-Limit`: Maximum requests allowed in the current window
* `X-RateLimit-Remaining`: Number of requests you have left
* `X-RateLimit-Reset`: Unix timestamp when your limit resets

#### Checking Your Current Usage

Monitor these headers in your API responses to track usage:

```javascript
const response = await fetch('https://api.cr3dentials.xyz/partner/types', {
  headers: { 'x-api-key': 'YOUR_API_KEY' }
});

console.log('Limit:', response.headers.get('X-RateLimit-Limit'));
console.log('Remaining:', response.headers.get('X-RateLimit-Remaining'));
console.log('Reset:', response.headers.get('X-RateLimit-Reset'));
```

***

### When You Hit Rate Limits

#### Rate Limit Response

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

```json
{
  "statusCode": 429,
  "message": "Too Many Requests",
  "error": "Rate limit exceeded. Try again in 60 seconds."
}
```

#### Handling Rate Limits in Your Code

**Basic Error Handling:**

```javascript
async function makeApiRequest() {
  try {
    const response = await fetch(apiUrl, options);
    
    if (response.status === 429) {
      const retryAfter = response.headers.get('Retry-After');
      console.log(`Rate limited. Retry after ${retryAfter} seconds`);
      // Wait before retrying
      return;
    }
    
    return response.json();
  } catch (error) {
    console.error('API request failed:', error);
  }
}
```

**Automatic Retry with Backoff:**

```javascript
async function apiRequestWithRetry(url, options, maxRetries = 3) {
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      const response = await fetch(url, options);
      
      if (response.status === 429) {
        const retryAfter = parseInt(response.headers.get('Retry-After') || '60');
        await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));
        continue;
      }
      
      return response.json();
    } catch (error) {
      if (attempt === maxRetries - 1) throw error;
      await new Promise(resolve => setTimeout(resolve, 1000 * Math.pow(2, attempt)));
    }
  }
}
```

***

### Best Practices

#### 1. Monitor Your Usage

✅ **Do:**

* Check rate limit headers in responses
* Track your API usage patterns
* Set up alerts when approaching limits

❌ **Don't:**

* Ignore rate limit headers
* Make unnecessary API calls
* Implement aggressive retry loops

#### 2. Optimize Your API Calls

**Efficient Request Patterns:**

```javascript
// Good: Batch operations when possible
const sessions = await Promise.all([
  createSession(user1Data),
  createSession(user2Data),
  createSession(user3Data)
]);

// Better: Check limits before making requests
const remaining = parseInt(response.headers.get('X-RateLimit-Remaining'));
if (remaining < 10) {
  console.log('Approaching rate limit, slowing down requests');
}
```

**Caching Strategies:**

```javascript
// Cache verification types to avoid repeated calls
let cachedTypes = null;
let cacheExpiry = null;

async function getVerificationTypes() {
  if (cachedTypes && cacheExpiry > Date.now()) {
    return cachedTypes;
  }
  
  cachedTypes = await api.getVerificationTypes();
  cacheExpiry = Date.now() + (60 * 60 * 1000); // Cache for 1 hour
  
  return cachedTypes;
}
```

#### 3. Use Webhooks Instead of Polling

**Instead of polling for status:**

```javascript
// Avoid: Polling every few seconds
setInterval(async () => {
  const status = await checkVerificationStatus(sessionId);
  // This quickly consumes your rate limit
}, 5000);
```

**Use webhooks for real-time updates:**

```javascript
// Better: Set up webhook to receive status updates
app.post('/webhook', (req, res) => {
  const { sessionId, status } = req.body.data;
  updateVerificationStatus(sessionId, status);
  res.status(200).json({ received: true });
});
```

#### 4. Implement Request Queuing

For high-volume applications:

```javascript
class ApiRequestQueue {
  constructor(requestsPerMinute = 90) { // Leave buffer below limit
    this.queue = [];
    this.processing = false;
    this.interval = 60000 / requestsPerMinute; // Time between requests
  }
  
  async add(apiCall) {
    return new Promise((resolve, reject) => {
      this.queue.push({ apiCall, resolve, reject });
      this.process();
    });
  }
  
  async process() {
    if (this.processing || this.queue.length === 0) return;
    
    this.processing = true;
    
    while (this.queue.length > 0) {
      const { apiCall, resolve, reject } = this.queue.shift();
      
      try {
        const result = await apiCall();
        resolve(result);
      } catch (error) {
        reject(error);
      }
      
      // Wait before next request
      await new Promise(resolve => setTimeout(resolve, this.interval));
    }
    
    this.processing = false;
  }
}
```

***

### Rate Limit Categories

Different endpoints may have different rate limits:

| Endpoint Type          | Typical Limit | Description                          |
| ---------------------- | ------------- | ------------------------------------ |
| **Session Creation**   | 20/minute     | Creating new verification sessions   |
| **Status Checks**      | 100/minute    | Checking verification status         |
| **Data Retrieval**     | 100/minute    | Getting types, sources, step details |
| **Webhook Management** | 10/minute     | Creating/updating webhooks           |

***

### Upgrading Your Limits

#### When You Need Higher Limits

Contact our team if you need higher rate limits due to:

* High-volume verification requirements
* Enterprise-level integration
* Batch processing needs
* Real-time application requirements

#### How to Request Limit Increases

1. **Contact Support**
   * Email: <support@cr3dentials.xyz>
   * Include your current API key ID
   * Describe your use case and required limits
2. **Provide Usage Justification**
   * Expected request volume
   * Business use case
   * Current limit constraints
3. **Consider Enterprise Plans**
   * Higher default limits
   * Custom rate limit configurations
   * Priority support

***

### Monitoring and Alerts

#### Track Your Usage

```javascript
// Log rate limit info for monitoring
function logRateLimitInfo(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');
  
  console.log(`Rate Limit: ${remaining}/${limit}, resets at ${new Date(reset * 1000)}`);
  
  // Alert when getting low
  if (remaining < 10) {
    console.warn('⚠️ Rate limit running low!');
  }
}
```

#### Set Up Monitoring

Consider implementing:

* Rate limit usage dashboards
* Alerts when approaching limits
* Automatic request throttling
* Usage pattern analysis

***

### Quick Reference

#### Rate Limit Checklist

* \[ ] Monitor rate limit headers in responses
* \[ ] Implement proper error handling for 429 responses
* \[ ] Use webhooks instead of polling when possible
* \[ ] Cache frequently accessed data
* \[ ] Implement request queuing for high-volume apps
* \[ ] Set up monitoring and alerts

***

###
