AirCubeAirCube
Core Concepts

Async Polling

How the asynchronous submit-and-poll pattern works in the AirCube API.

Why async?

AI generation tasks — especially video and audio — can take anywhere from a few seconds to several minutes. Instead of holding a connection open for the entire duration, the AirCube API uses an asynchronous polling pattern:

  1. You submit a request and get back an ID immediately.
  2. You poll for the result at your own pace until it's ready.

This approach is more reliable than long-lived HTTP connections, works naturally with serverless environments, and lets you manage multiple concurrent generations easily.

The submit-and-poll flow

┌─────────┐    POST /api/v3/{model}/{task}    ┌──────────┐
│  Client  │ ──────────────────────────────▶  │ AirCube  │
│          │ ◀──────────────────────────────  │   API    │
│          │    202 { id: "gen_abc123" }       │          │
│          │                                   │          │
│          │    GET /api/v3/status/gen_abc123  │          │
│          │ ──────────────────────────────▶  │          │
│          │ ◀──────────────────────────────  │          │
│          │    200 { status: "processing" }   │          │
│          │                                   │          │
│          │    ... (wait & retry) ...         │          │
│          │                                   │          │
│          │    GET /api/v3/status/gen_abc123  │          │
│          │ ──────────────────────────────▶  │          │
│          │ ◀──────────────────────────────  │          │
│          │    200 { status: "completed",     │          │
│          │          output_url: "..." }      │          │
└─────────┘                                   └──────────┘

Status values

Each generation goes through these states:

StatusDescription
queuedRequest received, waiting for an available worker
processingActively being generated by the AI model
completedGeneration succeeded — output_url is available
failedGeneration failed — credits are automatically refunded

Transitions are one-way: queuedprocessingcompleted or failed.

Polling intervals

Generation typeRecommended intervalTypical completion time
Image3 seconds5–30 seconds
Video5 seconds30 seconds – 5 minutes
Audio3 seconds5–20 seconds

Best practices

  • Set a maximum timeout — don't poll indefinitely. A reasonable limit is 5 minutes for images and 10 minutes for videos.
  • Use consistent intervals — simple fixed-interval polling works well for most use cases.
  • Handle both terminal states — always check for both completed and failed.

Reusable polling function

Python

import os
import time
import requests

API_KEY = os.environ["AIRCUBE_API_KEY"]

def poll_generation(generation_id, interval=3, timeout=300):
    """
    Poll a generation until it completes or fails.

    Args:
        generation_id: The ID from the submit response.
        interval: Seconds between polls.
        timeout: Maximum seconds to wait.

    Returns:
        The output URL on success.

    Raises:
        Exception on failure or timeout.
    """
    url = f"https://aircube.ai/api/v3/status/{generation_id}"
    headers = {"Authorization": f"Bearer {API_KEY}"}
    elapsed = 0

    while elapsed < timeout:
        response = requests.get(url, headers=headers)
        data = response.json()["data"]

        if data["status"] == "completed":
            return data["output_url"]
        elif data["status"] == "failed":
            raise Exception(f"Generation {generation_id} failed")

        time.sleep(interval)
        elapsed += interval

    raise TimeoutError(f"Generation {generation_id} timed out after {timeout}s")

JavaScript

const API_KEY = process.env.AIRCUBE_API_KEY;

/**
 * Poll a generation until it completes or fails.
 * @param {string} generationId - The ID from the submit response.
 * @param {number} interval - Milliseconds between polls.
 * @param {number} timeout - Maximum milliseconds to wait.
 * @returns {Promise<string>} The output URL.
 */
async function pollGeneration(generationId, interval = 3000, timeout = 300000) {
  const url = `https://aircube.ai/api/v3/status/${generationId}`;
  const headers = { Authorization: `Bearer ${API_KEY}` };
  const start = Date.now();

  while (Date.now() - start < timeout) {
    const response = await fetch(url, { headers });
    const { data } = await response.json();

    if (data.status === "completed") {
      return data.output_url;
    } else if (data.status === "failed") {
      throw new Error(`Generation ${generationId} failed`);
    }

    await new Promise((r) => setTimeout(r, interval));
  }

  throw new Error(`Generation ${generationId} timed out`);
}

Failed generations and refunds

If a generation fails (status becomes failed), the credits charged at submission time are automatically refunded to your account. You do not need to take any action — the refund happens immediately when the failure is detected.

On this page