> ## 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.

# Async Processing

> Understanding the asynchronous video generation workflow

# Asynchronous Processing

Video generation is a computationally intensive process that can take several minutes to complete. The VibePeak API uses an asynchronous task-based architecture to handle this efficiently.

## How It Works

<Steps>
  <Step title="Submit Request">
    Send a POST request to create a slideshow. The API validates your request and returns immediately with a task ID.
  </Step>

  <Step title="Task Queued">
    Your video generation task is added to the processing queue. You receive a `202 Accepted` response with the task details.
  </Step>

  <Step title="Processing">
    The system processes your images, applies AI enhancements, generates narration, and creates the final video.
  </Step>

  <Step title="Completion">
    Once complete, you can retrieve the video URL via polling or webhook notification.
  </Step>
</Steps>

## Task Lifecycle

Tasks progress through the following statuses:

| Status       | Description                             |
| ------------ | --------------------------------------- |
| `queued`     | Task is waiting in the processing queue |
| `processing` | Video generation is in progress         |
| `completed`  | Video is ready for download             |
| `failed`     | An error occurred during processing     |

```mermaid theme={null}
graph LR
    A[Submit Request] --> B[queued]
    B --> C[processing]
    C --> D{Success?}
    D -->|Yes| E[completed]
    D -->|No| F[failed]
```

## Submitting a Task

When you create a slideshow, you'll receive an immediate response:

<CodeGroup>
  ```bash Request theme={null}
  curl -X POST https://api.vibepeak.ai/v1/real-estate/narrated-slideshow \
    -H "Authorization: Bearer vpk_live_xxxxx" \
    -H "Content-Type: application/json" \
    -d '{
      "images": [
        "https://example.com/living-room.jpg",
        "https://example.com/kitchen.jpg",
        "https://example.com/bedroom.jpg",
        "https://example.com/bathroom.jpg",
        "https://example.com/backyard.jpg"
      ]
    }'
  ```

  ```json Response (202 Accepted) theme={null}
  {
    "task_id": "task_abc123xyz",
    "status": "queued",
    "queue_position": 3,
    "estimated_completion": "2026-01-04T12:30:00Z",
    "created_at": "2026-01-04T12:00:00Z"
  }
  ```
</CodeGroup>

## Polling for Status

Check the task status by polling the tasks endpoint:

<CodeGroup>
  ```bash Request theme={null}
  curl https://api.vibepeak.ai/v1/tasks/task_abc123xyz \
    -H "Authorization: Bearer vpk_live_xxxxx"
  ```

  ```json Response (Processing) theme={null}
  {
    "task_id": "task_abc123xyz",
    "status": "processing",
    "created_at": "2026-01-04T12:00:00Z",
    "started_at": "2026-01-04T12:05:00Z"
  }
  ```

  ```json Response (Completed) theme={null}
  {
    "task_id": "task_abc123xyz",
    "status": "completed",
    "created_at": "2026-01-04T12:00:00Z",
    "started_at": "2026-01-04T12:05:00Z",
    "completed_at": "2026-01-04T12:15:00Z",
    "result": {
      "video_url": "https://storage.vibepeak.ai/videos/task_abc123xyz.mp4",
      "duration_seconds": 45,
      "resolution": "1080p",
      "expires_at": "2026-01-11T12:15:00Z"
    }
  }
  ```
</CodeGroup>

## Response Headers

When creating a task, the API returns helpful headers for async workflows:

| Header        | Description                                                 |
| ------------- | ----------------------------------------------------------- |
| `Location`    | URL to poll for task status (e.g., `/v1/tasks/task_abc123`) |
| `Retry-After` | Recommended polling interval in seconds (default: 30)       |

```bash theme={null}
HTTP/1.1 202 Accepted
Location: /v1/tasks/task_abc123xyz
Retry-After: 30
Content-Type: application/json
```

## Polling Best Practices

<Warning>
  Video generation typically takes **4-10 minutes**. Polling too frequently wastes resources and may trigger rate limiting.
</Warning>

<Info>
  The API returns a `Retry-After: 30` header - we recommend polling every **30 seconds** for video generation tasks.
</Info>

We recommend the following polling strategy:

```javascript theme={null}
async function waitForCompletion(taskId, apiKey) {
  const maxAttempts = 40; // 40 attempts × 30 seconds = 20 minutes max
  const pollInterval = 30000; // 30 seconds (matches Retry-After header)

  for (let attempt = 0; attempt < maxAttempts; attempt++) {
    const response = await fetch(
      `https://api.vibepeak.ai/v1/tasks/${taskId}`,
      { headers: { 'Authorization': `Bearer ${apiKey}` } }
    );

    const task = await response.json();

    if (task.status === 'completed') {
      return task.result;
    }

    if (task.status === 'failed') {
      throw new Error(task.error.message);
    }

    // Wait before next poll (use Retry-After header if available)
    const retryAfter = response.headers.get('Retry-After');
    const waitTime = retryAfter ? parseInt(retryAfter) * 1000 : pollInterval;
    await new Promise(resolve => setTimeout(resolve, waitTime));
  }

  throw new Error('Task timed out');
}
```

**Recommended intervals:**

* Default: Poll every **30 seconds** (matches `Retry-After` header)
* Video generation typically completes in 4-10 minutes
* Maximum wait: 20 minutes before timing out

## Using Webhooks Instead

For production applications, we recommend using [webhooks](/concepts/webhooks) instead of polling. Webhooks provide:

* **Real-time notifications** - No delay between completion and notification
* **Reduced API calls** - No need for repeated polling requests
* **Better scalability** - Handle more concurrent tasks efficiently

```json theme={null}
{
  "images": ["..."],
  "webhook_url": "https://yourserver.com/webhooks/vibepeak"
}
```

## Video URL Expiration

<Info>
  Video URLs expire after **7 days**. Download or store the video before expiration.
</Info>

The `expires_at` field in the task result indicates when the video URL will become invalid. Make sure to:

1. Download the video to your own storage, or
2. Re-request the task status to get a fresh URL (if the video is still available)

## Handling Failures

If a task fails, the response will include error details:

```json theme={null}
{
  "task_id": "task_abc123xyz",
  "status": "failed",
  "created_at": "2026-01-04T12:00:00Z",
  "started_at": "2026-01-04T12:05:00Z",
  "completed_at": "2026-01-04T12:06:00Z",
  "error": {
    "code": "IMAGE_PROCESSING_FAILED",
    "message": "Failed to process image at index 2: Invalid image format"
  }
}
```

Common failure reasons:

* Invalid or inaccessible image URLs
* Unsupported image formats
* Images too small or corrupted
* Internal processing errors

For failed tasks, review the error message, fix the issue, and submit a new request.
