Skip to content
Guides

Polling vs Webhooks for AI Image and Video Jobs

Polling vs webhooks for AI image and video jobs: latency, effort and reliability compared, how often to poll, and a hybrid that never misses a result.

Updated 6 min read

Polling vs webhooks comes down to who asks: with polling, your code reads the job every few seconds until it is done; with a webhook, the API sends your server a request the moment the job settles. Poll in scripts, notebooks and anything without a public URL; take webhooks in services that run many jobs or react to jobs started elsewhere; and in production, use both, with the webhook as the main path and a slow poll as a safety net.

This guide compares the two for image and video generation, gives polling intervals that are neither wasteful nor slow, shows an async Python poller for many jobs, and builds the hybrid that never loses a result. The examples use Seedance 2.5, but every model ends the same way.

Sync vs async APIs: why generation jobs come back later

A synchronous API answers your request with the result: you ask, you wait, you get it in the same response. That works when the work takes milliseconds. Generating an image or a clip is not that kind of work: the job runs on well after the request that started it, longer than a connection can be trusted to stay open.

So generation APIs are asynchronous. POST /v1/videos/generations checks the request, holds its price and answers at once with 202 Accepted and a generation id in the queued state. The work happens afterwards: the generation moves to running, then ends succeeded (with a file link per output) or failed (with a reason, and nothing charged). Polling and webhooks are simply the two ways to learn which, and when.

Polling vs webhooks: the trade-off in one table

PollingWebhooks
How you learn the resultYou GET the generation until it settlesThe API POSTs it to your endpoint
What you needA loop with a timeoutA public https URL that answers within 10 seconds
Works from a laptop or notebookYesOnly through a tunnel
Delay after the job endsUp to one polling intervalSent when the job closes
Cost in rate limitNone: reads are not countedNone
Survives your process restartingNo: the loop dies with itYes, while the endpoint is up
What can go wrongLoops left running, intervals too tightMissed deliveries, forged requests, duplicates
Jobs started elsewhere (the Studio, an agent)Only if you know their idsDelivered like any other

Neither costs money: reads are free and not counted against the workspace's 60 requests a minute, and deliveries are free. The real difference is operational: a loop is easy to write and easy to lose, an endpoint takes more setup and keeps working while your code sleeps.

How often to poll

Match the interval to how long the job takes, and grow it as you wait:

  • Images: read every 2 seconds or so. Most of the wait is short, and a tighter loop gains nothing.
  • Clips: start at about 5 seconds and let the interval grow to 15 or 20. A clip that has been running for three minutes will not be faster for being asked every second.
  • A deadline: stop the loop after a generous limit (half an hour for long clips) and look again later. A generation never disappears; its id answers whenever you read it.

Each read brings the generation up to date before it answers, so a read is never stale. When you poll many jobs at once, do it concurrently rather than one after another. With Python's asyncio and httpx (pip install httpx):

poll_many.py: async API calls in Python
import asyncio
import os

import httpx

API = "https://frameport.ai/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['FRAMEPORT_API_KEY']}"}


async def wait_for(client, gen_id, first=5.0, longest=20.0, deadline=1800.0):
    delay, waited = first, 0.0
    while waited < deadline:
        await asyncio.sleep(delay)
        waited += delay
        gen = (await client.get(f"{API}/generations/{gen_id}")).json()
        if gen["status"] not in ("queued", "running"):
            return gen
        delay = min(longest, delay * 1.5)  # 5, 7.5, 11, 17, then 20 s
    raise TimeoutError(f"{gen_id} is still running: read it again later")


async def main(ids):
    async with httpx.AsyncClient(headers=HEADERS, timeout=30) as client:
        results = await asyncio.gather(*(wait_for(client, gen_id) for gen_id in ids), return_exceptions=True)
    for result in results:
        print(result if isinstance(result, Exception) else f"{result['id']} {result['status']} {result['cost_usd']}")


asyncio.run(main(["gen_9sLq2VbX7mN4kR1tYc8WpE", "gen_6Pq3WnT8vXc1Lm5Rk9YbZs"]))

For images, call wait_for with first=2.0, longest=3.0. The generations reference lists every field the read returns.

When webhooks win

Webhooks take over as soon as polling stops being simple:

  • Many jobs at once. Ten loops are fine; a thousand open loops in a web server are not. One endpoint handles them all.
  • Jobs you did not start in this process. A delivery covers every generation of the workspace, including clips started from the Studio, the MCP server or another service.
  • Serverless and short-lived code. A function that cannot stay alive until a clip finishes can submit, return, and let the webhook resume the work.
  • Workflows that should sleep. An automation tool can start a second scenario on the delivery instead of keeping a run open.

Each delivery is a signed POST with the generation exactly as a read would return it, so the handler has everything it needs. A delivery your endpoint does not acknowledge with a 2xx is retried after 1, 5 and 15 minutes. The AI video API webhooks guide shows how to verify the signature and deal with duplicates; the webhooks reference has every header.

The hybrid: webhook first, poll as a backstop

A webhook can be missed: your endpoint was mid-deploy, a certificate expired, all four attempts fell inside an outage. And deliveries go out when a job closes, which happens either when someone reads it or when a background check that runs every minute picks it up. A slow poll for overdue jobs covers both cases. The pattern:

  1. At submit, store the generation id with a pending status.
  2. The webhook handler and the sweeper call the same settle() function, which does nothing if the job is already closed.
  3. Every few minutes, the sweeper reads any job still pending after ten minutes, by id. The read brings it up to date, and settle() takes it from there.
hybrid.py
import hashlib
import hmac
import json
import os
import sqlite3
import time

import requests
from flask import Flask, request

API = "https://frameport.ai/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['FRAMEPORT_API_KEY']}"}
SECRET = os.environ["WEBHOOK_SECRET"].encode()  # whsec_..., shown once
db = sqlite3.connect("jobs.db", check_same_thread=False)
db.execute("CREATE TABLE IF NOT EXISTS jobs (generation TEXT PRIMARY KEY, status TEXT, sent_at REAL)")
app = Flask(__name__)


def settle(gen):
    closed = db.execute(
        "UPDATE jobs SET status = ? WHERE generation = ? AND status = 'pending'", (gen["status"], gen["id"]),
    ).rowcount
    db.commit()
    if closed:  # the first to bring the news does the work, once
        print("settled", gen["id"], gen["status"], gen["cost_usd"])  # download, notify...


def signed(raw, header):
    parts = dict(item.split("=", 1) for item in header.split(",") if "=" in item)
    if not parts.get("t", "").isdigit() or abs(time.time() - int(parts["t"])) > 300:
        return False
    digest = hmac.new(SECRET, parts["t"].encode() + b"." + raw, hashlib.sha256).hexdigest()
    return hmac.compare_digest(digest, parts.get("v1", ""))


@app.post("/hooks/generations")
def webhook():
    raw = request.get_data()
    if not signed(raw, request.headers.get("Frameport-Signature", "")):
        return "", 400
    settle(json.loads(raw)["data"])
    return "", 204


def sweep(overdue=600):
    rows = db.execute("SELECT generation FROM jobs WHERE status = 'pending' AND sent_at < ?", (time.time() - overdue,))
    for (gen_id,) in rows.fetchall():
        gen = requests.get(f"{API}/generations/{gen_id}", headers=HEADERS, timeout=30).json()
        if gen["status"] in ("succeeded", "failed"):
            settle(gen)

Run sweep() from a cron job or a scheduler every five minutes. On a normal day it finds nothing; on a bad one it closes every job the webhook missed, and a delivery that arrives later finds the row closed and does nothing. Rows whose ids are not in your table, such as clips someone made in the Studio, are ignored by the UPDATE.

Long polling, WebSockets and webhooks

Two other patterns come up in the same searches. Long polling keeps a request open on the server until there is news, then answers; WebSockets keep a two-way connection open for messages in both directions. Both suit browsers and chat-like apps that need many small updates.

This API uses neither. A read is a plain GET that answers immediately, and completion is pushed by webhook. If a web page should show a job's progress live, let your server receive the webhook (or poll), then pass the news to the page over server-sent events or the WebSocket your app already has. Keep the API key on the server either way: it spends your balance. For a full polling script with downloads, see the Python video guide. Both patterns run inside a chat bot too: a Discord bot or a Telegram bot that replies with the file.

FAQ

Is polling an API bad practice?

Not for jobs like these. Reads are free and not rate-limited here, so polling every few seconds with a growing interval and a deadline is a sound choice for scripts and small batches. It becomes a problem only when loops are tight, unbounded, or too many to keep track of.

Are webhooks faster than polling?

Usually, because a webhook is sent as soon as the job is closed, while a poll notices it on its next read. In practice the gap is at most one polling interval, which is why the hybrid uses webhooks first and a slow poll for anything overdue.

What is the difference between a webhook and an API?

An API is something you call: you send a request and get an answer. A webhook is the reverse: the service calls a URL you gave it when something happens. Generation APIs use both, an API call to start a job and a webhook to report its end.

Which is more reliable, polling or webhooks?

Each fails differently. A polling loop stops when your process does, and a webhook can be missed while your endpoint is down, even with retries. Using both, with one idempotent handler, is more reliable than either alone.

Do I need webhooks for image generation?

Rarely. An image job is short, so a polling loop that reads every couple of seconds is simpler for most code. Webhooks pay off for images when you run large batches in a service, or when images are started from places your code does not control.

Start building.

Your API key is free. Top up from $10 when you are ready.