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

# Rate Limits

> Understanding API rate limits and concurrent task quotas

# Rate Limits

The VibePeak API implements rate limiting to ensure fair usage and maintain service quality for all users. Rate limits are based on your subscription plan.

## Concurrent Task Limits

The primary rate limit is the number of **concurrent video generation tasks** you can have in progress at any time:

| Plan       | Concurrent Tasks | API Access |
| ---------- | ---------------- | ---------- |
| Plus       | 1                | Yes        |
| Pro        | 3                | Yes        |
| Max        | 5                | Yes        |
| Enterprise | Custom           | Yes        |

<Info>
  A task is considered "in progress" while it's in `queued` or `processing` status. Once a task reaches `completed` or `failed` status, it no longer counts against your limit.
</Info>

## How It Works

When you submit a new slideshow request, the API checks your current number of in-progress tasks:

1. If you're under your limit, the task is accepted and queued
2. If you've reached your limit, you receive a `429 Too Many Requests` error

```mermaid theme={null}
graph TD
    A[Submit Request] --> B{Check concurrent tasks}
    B -->|Under limit| C[Accept task]
    B -->|At limit| D[Reject with 429]
    C --> E[Return 202 Accepted]
    D --> F[Return 429 Too Many Requests]
```

## Rate Limit Response

When you exceed your concurrent task limit, you'll receive:

```json theme={null}
{
  "error": {
    "code": "CONCURRENCY_LIMIT_EXCEEDED",
    "message": "You have reached your concurrent task limit of 1. Please wait for existing tasks to complete.",
    "request_id": "req_xyz123",
    "details": {
      "limit": 1,
      "in_flight": 1,
      "plan": "Plus"
    }
  }
}
```

| Field       | Description                           |
| ----------- | ------------------------------------- |
| `limit`     | Your maximum allowed concurrent tasks |
| `in_flight` | Number of tasks currently in progress |
| `plan`      | Your current subscription plan        |

## Plan Required Response

If your account doesn't have a qualifying plan (Plus, Pro, Max, or Enterprise):

```json theme={null}
{
  "error": {
    "code": "PLAN_REQUIRED",
    "message": "API access requires a Plus, Pro or Max plan. Please upgrade your subscription.",
    "request_id": "req_xyz123",
    "details": {
      "current_plan": "none",
      "required_plans": ["Plus", "Pro", "Max"]
    }
  }
}
```

## Handling Rate Limits

<CodeGroup>
  ```javascript Node.js theme={null}
  async function createSlideshowWithRetry(images, apiKey, maxRetries = 3) {
    for (let attempt = 0; attempt < maxRetries; attempt++) {
      const response = await fetch('https://api.vibepeak.ai/v1/real-estate/narrated-slideshow', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${apiKey}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ images })
      });

      if (response.status === 429) {
        const error = await response.json();
        console.log(`Rate limited. In-flight: ${error.error.details.in_flight}`);

        // Wait for some tasks to complete
        await new Promise(resolve => setTimeout(resolve, 60000)); // Wait 1 minute
        continue;
      }

      if (!response.ok) {
        throw new Error(`API error: ${response.status}`);
      }

      return response.json();
    }

    throw new Error('Max retries exceeded');
  }
  ```

  ```python Python theme={null}
  import time
  import requests

  def create_slideshow_with_retry(images, api_key, max_retries=3):
      for attempt in range(max_retries):
          response = requests.post(
              'https://api.vibepeak.ai/v1/real-estate/narrated-slideshow',
              headers={
                  'Authorization': f'Bearer {api_key}',
                  'Content-Type': 'application/json'
              },
              json={'images': images}
          )

          if response.status_code == 429:
              error = response.json()
              print(f"Rate limited. In-flight: {error['error']['details']['in_flight']}")
              time.sleep(60)  # Wait 1 minute
              continue

          response.raise_for_status()
          return response.json()

      raise Exception('Max retries exceeded')
  ```
</CodeGroup>

## Best Practices

<CardGroup cols={2}>
  <Card title="Monitor Task Status" icon="chart-line">
    Track your in-progress tasks to avoid hitting limits
  </Card>

  <Card title="Use Webhooks" icon="bell">
    Get notified when tasks complete instead of polling
  </Card>

  <Card title="Queue Requests" icon="list">
    Implement a local queue to manage submission rate
  </Card>

  <Card title="Handle 429 Gracefully" icon="rotate">
    Implement exponential backoff for rate limit errors
  </Card>
</CardGroup>

### Implementing a Task Queue

For high-volume applications, implement a local queue:

```javascript theme={null}
class TaskQueue {
  constructor(apiKey, concurrencyLimit) {
    this.apiKey = apiKey;
    this.concurrencyLimit = concurrencyLimit;
    this.inFlight = 0;
    this.queue = [];
  }

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

  async processQueue() {
    while (this.queue.length > 0 && this.inFlight < this.concurrencyLimit) {
      const { images, resolve, reject } = this.queue.shift();
      this.inFlight++;

      try {
        const result = await this.createSlideshow(images);
        resolve(result);
      } catch (error) {
        reject(error);
      } finally {
        this.inFlight--;
        this.processQueue();
      }
    }
  }

  async createSlideshow(images) {
    // Implementation here
  }
}

// Usage
const queue = new TaskQueue(apiKey, 3); // Pro plan limit
await queue.submit(images1);
await queue.submit(images2);
// Tasks are automatically queued and processed within limits
```

## Upgrading Your Plan

Need higher limits? [Upgrade your plan](https://vibepeak.ai/pricing) to increase your concurrent task quota:

* **Plus**: 1 concurrent task
* **Pro**: 3 concurrent tasks
* **Max**: 5 concurrent tasks

## Monitoring Usage

<Tip>
  Keep track of your in-flight tasks to avoid rate limiting. The task status endpoint shows your active tasks.
</Tip>

You can monitor your usage by:

1. Tracking the `in_flight` count in 429 error responses
2. Maintaining a local counter of submitted vs completed tasks
3. Using webhooks to get real-time completion notifications
