Skip to content
ImageVideoAsync

Async Image and Video Generation: Task IDs, Polling and Webhooks Done Right

Image and video generation often takes seconds to minutes, so a successful submission is the start of a workflow—not the finished asset.

By the Openrouter API team6 min read
Async Image and Video Generation: Task IDs, Polling and Webhooks Done Right

Image and video generation often takes seconds to minutes, so a successful submission is the start of a workflow—not the finished asset. A reliable integration stores the task ID, tracks completion without excessive polling, and copies generated files into durable storage before their download URLs expire.

Treat generation as a durable job

Openrouter API provides one API key and an OpenAI-compatible base URL, https://openrouterapi.ru/v1, for 250+ models. Async image and video generation uses a task-based lifecycle:

  1. Submit to POST /v1/images/generations or POST /v1/videos/generations.
  2. Read the task ID from data[0].task_id.
  3. Persist that ID alongside your application’s job record.
  4. Query GET /v1/tasks/{task_id} or receive a completion callback.
  5. Download and persist successful outputs.

Generation is asynchronous because the work can outlast a reasonable interactive HTTP request. Keeping submission separate from execution also lets your application recover after a browser disconnects or a worker restarts.

Your application might label its initial state submitted. The documented task-status values are pending, processing, completed, failed, and cancelled; do not assume submitted is a status returned by the polling endpoint.

StateMeaningApplication action
Submitted locallySubmission accepted; task ID storedSchedule status tracking
pendingQueued for processingContinue waiting
processingGeneration in progressContinue waiting; display progress if useful
completedGeneration succeededPersist result metadata and download assets
failedGeneration failedRecord the error and stop polling
cancelledTask was cancelledStop polling

The status response includes id, status, cost, credits_cost, and progress-related fields. A completed task includes result, with images for image generation or videos for video generation. Consult the relevant docs for the generated-object structure rather than assuming every model returns identical asset metadata.

Choose a model, then budget for its output

Async handling is shared across these models, but output capabilities and billing units differ.

ModelTypePublished prices
seedream-5-5ByteDance imageDefault $0.0308 per image; 1K $0.0176 per image; 1K-layer $0.0176 per image; 2K $0.0308 per image; 2K-layer $0.0308 per image
gpt-image-2OpenAI imageDefault $0.00935 per image; 1K $0.00935 per image; 2K $0.0165 per image; 4K $0.0242 per image
seedance-2.0ByteDance video1080P $0.3898 per second; 1080P · with input video $0.2372 per second; 480P $0.0726 per second; 480P · with input video $0.044 per second; 4K $0.7942 per second; 4K · with input video $0.4888 per second
kling-v3Kuaishou videoDefault $0.07392 per second; 4k $0.4714 per second; 4k-sound $0.4714 per second; pro $0.09856 per second; pro-sound $0.1478 per second; sound $0.1109 per second
veo3.1-fastGoogle video1080P $0.1031 per second; 4K $0.2475 per second; 720P $0.0825 per second

These pricing labels are not request-parameter instructions. Check each model page for supported settings and their exact field names.

seedream-5-5 supports text generation or up to 10 reference images, transparent backgrounds, and configurable layer decomposition with text OCR. The other models listed here also document asynchronous processing with task IDs for subsequent queries.

Openrouter API is pay-as-you-go in USD, and only successful requests are billed: failed generation tasks are not charged. However, accidentally submitting the same job twice can produce two successful, billable tasks. Retry discipline is therefore part of cost control. See pricing for rates, and retain the returned cost and credits_cost for reconciliation.

Submit once and store the task ID

The following Python example uses the official openai SDK’s custom HTTP methods because these async task endpoints are not standard OpenAI SDK resource methods.

Set OPENROUTERAPI_API_KEY in your environment; $OPENROUTERAPI_API_KEY represents your secret key. Keep it on the server, not in browser-delivered code.

python
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["OPENROUTERAPI_API_KEY"],  # $OPENROUTERAPI_API_KEY
    base_url="https://openrouterapi.ru/v1",
    max_retries=0,  # Avoid automatic retries of generation submissions.
)

submission = client.post(
    "/images/generations",
    body={
        "model": "gpt-image-2",
        "prompt": "A studio photograph of a ceramic cup on a plain table",
    },
    cast_to=dict,
)

task_id = submission["data"][0]["task_id"]

# Persist task_id in your database before scheduling a polling worker.
print(task_id)

A useful job record contains your internal job ID, task ID, model, request fingerprint, local state, timestamps, and eventual result metadata. Use a uniqueness constraint on the task ID and an application-level submission lock to prevent concurrent workers from creating duplicate jobs.

There is an important ambiguity: a submission request can time out after the server has accepted it. Without documented server-side idempotency support, blindly retrying that POST may create another task. Mark the submission outcome as unknown and reconcile it rather than pretending a timeout proves nothing happened.

Poll with backoff and a deadline

A practical starting interval is 3–10 seconds. Begin around three seconds, increase the delay exponentially, and cap it at ten seconds. These are client-side recommendations, not promised completion times or API limits.

Polling should have both a per-request timeout and an overall deadline. A deadline stops your worker from waiting forever; it does not cancel generation. Keep the task ID so another worker can resume tracking later.

Retry transient failures when reading status—network errors, HTTP 429, and server errors—but stop on permanent client errors. Add jitter across production workers so they do not all query simultaneously.

Python polling helper

This helper retries safe status reads, handles terminal states, and returns the full completed response. Its backoff grows from three to ten seconds.

python
import time
from openai import APIConnectionError, APIStatusError

def wait_for_task(client, task_id, timeout_seconds=900):
    deadline = time.monotonic() + timeout_seconds
    delay = 3.0

    while True:
        remaining = deadline - time.monotonic()
        if remaining <= 0:
            raise TimeoutError(
                f"Stopped waiting for {task_id}; retain the ID and resume later"
            )

        task = None
        try:
            task = client.with_options(
                timeout=min(30.0, remaining),
                max_retries=0,
            ).get(
                f"/tasks/{task_id}",
                options={"params": {"language": "en"}},
                cast_to=dict,
            )
        except APIConnectionError:
            pass  # Includes connection and request-timeout failures.
        except APIStatusError as exc:
            if exc.status_code != 429 and exc.status_code < 500:
                raise

        if task is not None:
            status = task["status"]
            if status == "completed":
                return task
            if status in {"failed", "cancelled"}:
                raise RuntimeError(
                    f"Task {task_id} ended as {status}: {task.get('error')}"
                )
            if status not in {"pending", "processing"}:
                raise RuntimeError(f"Unexpected task status: {status}")

        remaining = deadline - time.monotonic()
        if remaining <= 0:
            raise TimeoutError(f"Polling deadline reached for {task_id}")

        time.sleep(min(delay, remaining))
        delay = min(delay * 2, 10.0)

completed_task = wait_for_task(client, task_id)
print(completed_task["result"])

The 900-second default is an example application deadline, not a service guarantee. Set it according to your product’s waiting experience and recovery policy. For many concurrent jobs, schedule the next check in a queue instead of dedicating one sleeping worker to each task.

JavaScript polling helper

This Node.js example uses native fetch. Keep it server-side so the API key remains private. It separates HTTP errors from transport failures and aborts individual requests when their allotted time expires.

javascript
const BASE_URL = "https://openrouterapi.ru/v1";
const API_KEY = process.env.OPENROUTERAPI_API_KEY; // $OPENROUTERAPI_API_KEY

if (!API_KEY) throw new Error("Set OPENROUTERAPI_API_KEY");

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function waitForTask(taskId, { timeoutMs = 900_000 } = {}) {
  const deadline = performance.now() + timeoutMs;
  let delayMs = 3_000;

  while (true) {
    const remaining = deadline - performance.now();
    if (remaining <= 0) {
      throw new Error(`Polling deadline reached; retain task ID ${taskId}`);
    }

    const controller = new AbortController();
    const timer = setTimeout(
      () => controller.abort(),
      Math.min(30_000, remaining),
    );

    let response;
    let task;

    try {
      response = await fetch(
        `${BASE_URL}/tasks/${encodeURIComponent(taskId)}?language=en`,
        {
          headers: { Authorization: `Bearer ${API_KEY}` },
          signal: controller.signal,
        },
      );
      if (response.ok) task = await response.json();
    } catch (error) {
      // Retry transport failures and request timeouts, not malformed JSON.
      if (error.name !== "AbortError" && !(error instanceof TypeError)) {
        throw error;
      }
    } finally {
      clearTimeout(timer);
    }

    if (response && !response.ok) {
      if (response.status !== 429 && response.status < 500) {
        throw new Error(`Task query failed: HTTP ${response.status}`);
      }
    }

    if (task) {
      if (task.status === "completed") return task;
      if (["failed", "cancelled"].includes(task.status)) {
        throw new Error(
          `Task ${taskId}: ${task.status}; ${JSON.stringify(task.error)}`,
        );
      }
      if (!["pending", "processing"].includes(task.status)) {
        throw new Error(`Unexpected task status: ${task.status}`);
      }
    }

    const left = deadline - performance.now();
    if (left <= 0) {
      throw new Error(`Polling deadline reached for ${taskId}`);
    }

    await sleep(Math.min(delayMs, left));
    delayMs = Math.min(delayMs * 2, 10_000);
  }
}

// Load an already-persisted task ID from your job record.
const completedTask = await waitForTask(process.env.TASK_ID);
console.log(completedTask.result);

The polling endpoint accepts language to translate failed-task error.message. Supported codes are en, zh, ja, ko, ru, fr, de, id, pt, and es. Values are case-insensitive and trimmed; regional tags such as en-US are not recognized. Unsupported values preserve the original message.

Use webhooks, but retain reconciliation polling

Where callbacks are supported, add webhook at the top level of the submission body. Openrouter API sends a POST to your supplied URL plus /callback when the task finishes.

bash
curl --request POST 'https://openrouterapi.ru/v1/videos/generations' \
  --header "Authorization: Bearer $OPENROUTERAPI_API_KEY" \
  --header 'Content-Type: application/json' \
  --data '{
    "model": "veo3.1-fast",
    "prompt": "A slow camera move through a sunlit greenhouse",
    "webhook": "https://example.com/generation",
    "language": "en"
  }'

For this example, implement the receiver at https://example.com/generation/callback, not merely /generation. Both webhook and language belong at the top level. Submission-time language applies to image and video generation failure messages; it does not change task IDs, progress, costs, or result URLs.

Configure a callback signing secret and follow the exact verification procedure in the docs. Do not invent a signature header or hashing algorithm, and do not treat possession of a task ID as proof of authenticity.

A production receiver should:

  • Verify authenticity before accepting state changes.
  • Match the task ID to an existing job.
  • Persist the event or enqueue durable processing before acknowledging it.
  • Make repeated completion handling idempotent.
  • Avoid moving a terminal job back into an earlier state.

Do not assume callback delivery order or an unspecified retry guarantee. Keep a periodic reconciler that queries outstanding tasks. Polling and webhooks should feed the same completion handler so simultaneous notifications cannot duplicate downloads or downstream work.

Upload references before generation

Local file paths are not public reference URLs. Upload a supported image first, then pass its returned public URL in the reference field documented for your chosen model.

bash
curl --request POST \
  'https://openrouterapi.ru/v1/uploads/images?retention_days=3' \
  --header "Authorization: Bearer $OPENROUTERAPI_API_KEY" \
  --form 'file=@./reference.png'

The upload endpoint accepts JPEG, PNG, GIF, and WebP, with a default maximum file size of 30MB. It validates file content; renaming an unsupported file does not convert it. Send an actual multipart file part and let your client generate the Content-Type boundary.

Supported retention_days values are 3, 7, 15, and 30, supplied as URL query parameters. Omitting the parameter uses the effective console default, which is not necessarily three days. Choose retention that covers queueing, processing, and any planned reuse.

Uploads require a valid key and positive account balance. Paid uploads also require sufficient balance and remaining key spending allowance. Do not infer that upload billing follows generation-task billing.

Persist outputs before their URLs expire

Generated output URLs are delivery locations, not permanent storage. Some expire after 24–72 hours; do not assume a universal retention window across models.

On completion, enqueue asset ingestion promptly. Download each output into storage you control, validate the response, and record its durable location. Retry interrupted downloads independently of generation: an asset-transfer failure is not a reason to generate another billable output.

Keep separate application states for “generation completed” and “asset persisted.” This distinction makes recovery possible when generation succeeds but your storage service is temporarily unavailable.

For larger deployments, monitor outstanding-task age, polling errors, terminal failures, and download backlog. Avoid logging bearer tokens or full output URLs, which may grant access to private assets.

Key takeaways

  • Persist data[0].task_id immediately and resume tracking after restarts.
  • Poll with bounded backoff, request timeouts, and an overall deadline.
  • Retry status reads safely; do not blindly retry ambiguous submissions.
  • Verify callbacks and make completion handling idempotent.
  • Copy outputs promptly; failed generation tasks are not charged.

Create an account and top up from $50; credits never expire.

Models in this article

More articles

All articles
Depth: 250+ models · Minimum top-up $50

One key. Every model. Start shipping today.

Create an account, top up from $50, and point your existing OpenAI, Anthropic or Gemini SDK at Openrouter API. No subscriptions, no seat fees, no idle charges.