Skip to content
FramesField
FIX 44 · API & BATCH PIPELINES
raw .md ↗ Verified Dec 1, 2026

Fix Veo, Kling & fal.ai HTTP 429 Limits and Polling Timeouts

Direct Fix: Never use Promise.all() or synchronous HTTP endpoints for AI video APIs: enforce MAX_CONCURRENT=2, submit exclusively to async queue endpoints, persist every job_id atomically into render-manifest.json keyed by shot SHA-256 hash, and poll with Retry-After plus jittered 10s-to-30s backoff.
Exact Error / Visual Signature
HTTP 429 RESOURCE_EXHAUSTED (Quota exceeded for generate_video) | Kling code 1303: Concurrent task limit exceeded | fal.ai 429 Too Many Requests | UND_ERR_HEADERS_TIMEOUT / Vercel 504 FUNCTION_INVOCATION_TIMEOUT after 60s
OBSERVED SYMPTOM

Your batch video render script fires 12 shots simultaneously to Google Gemini Omni 1.2 Flash, Kling 4.0, or fal.ai, immediately trips HTTP 429 rate limits or drops mid-render with a 60-second HTTP timeout—and restarting the script submits duplicate billable video jobs that silently double-charge your API balance.

TECHNICAL ROOT CAUSE

Unbounded Promise.all() bursts exceed per-minute RPM and concurrent video-slot ceilings, synchronous HTTP calls time out while 1080p video diffusion jobs take 60–240 seconds, and stateless scripts keep async operation IDs solely in RAM so crashes force duplicate paid POST submissions.

Copy-Paste Verified Fix

Resumable Async Video Queue Runner (Concurrency Cap, Retry-After & Atomic Manifest) safe-video-queue-runner.sh
#!/usr/bin/env bash
set -euo pipefail

# Writes a production-grade Node.js ESM async queue helper for fal.ai / Veo / Kling pipelines
# Usage: ./safe-video-queue-runner.sh [target_script_path]
OUT_JS="${1:-scripts/video-queue-runner.mjs}"
mkdir -p "$(dirname "$OUT_JS")"

cat << 'JSEOF' > "$OUT_JS"
import { createHash } from 'node:crypto';
import { existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs';

const MANIFEST_PATH = process.env.RENDER_MANIFEST || 'render-manifest.json';
const MAX_CONCURRENT = Number(process.env.MAX_CONCURRENT || 2);
const POLL_TIMEOUT_MS = Number(process.env.POLL_TIMEOUT_MS || 600_000); // 10 min hard budget

export function shotHash(payload) {
  return createHash('sha256').update(JSON.stringify(payload)).digest('hex').slice(0, 16);
}

export function loadManifest() {
  return existsSync(MANIFEST_PATH) ? JSON.parse(readFileSync(MANIFEST_PATH, 'utf8')) : {};
}

export function saveManifestAtomic(manifest) {
  const tmp = `${MANIFEST_PATH}.${process.pid}.tmp`;
  writeFileSync(tmp, JSON.stringify(manifest, null, 2));
  renameSync(tmp, MANIFEST_PATH); // Atomic POSIX rename prevents corrupted manifests
}

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

export async function fetchWithBackoff(url, init = {}, maxRetries = 5) {
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
    const res = await fetch(url, { ...init, signal: AbortSignal.timeout(30_000) });
    if (res.ok) return res;

    // Non-retryable client or policy errors: fail fast, never loop!
    if ([400, 401, 403, 404, 422].includes(res.status)) {
      const body = await res.text();
      throw new Error(`NON_RETRYABLE_HTTP_${res.status}: ${body.slice(0, 400)}`);
    }

    if (attempt === maxRetries) {
      throw new Error(`EXHAUSTED_RETRIES_HTTP_${res.status} on ${url}`);
    }

    // Honor server Retry-After header when present; else decorrelated exponential backoff + jitter
    const retryAfterSec = Number(res.headers.get('retry-after'));
    const baseMs = Number.isFinite(retryAfterSec) && retryAfterSec > 0
      ? retryAfterSec * 1000
      : Math.min(60_000, 2_000 * 2 ** attempt);
    const waitMs = Math.round(baseMs + Math.random() * 1_500);
    console.warn(`HTTP ${res.status} on ${url} -> backing off ${waitMs}ms (attempt ${attempt + 1}/${maxRetries})`);
    await sleep(waitMs);
  }
}

export async function runWithConcurrency(items, worker, limit = MAX_CONCURRENT) {
  const queue = [...items];
  const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
    while (queue.length > 0) {
      const item = queue.shift();
      await worker(item);
    }
  });
  await Promise.all(workers);
}

export async function submitOrResumeJob({ shotId, payload, submitFn, pollFn, dryRun = true }) {
  const manifest = loadManifest();
  const hash = shotHash(payload);
  const existing = manifest[hash];

  if (existing?.status === 'completed' && existing.localPath && existsSync(existing.localPath)) {
    console.log(`[SKIP $0] ${shotId} already rendered -> ${existing.localPath}`);
    return existing;
  }

  let jobId = existing?.jobId;
  if (!jobId) {
    if (dryRun) {
      console.log(`[DRY-RUN] Would submit ${shotId} (hash=${hash})`);
      return { status: 'dry_run', hash };
    }
    const submitted = await submitFn(payload);
    jobId = submitted.jobId;
    manifest[hash] = { shotId, hash, jobId, status: 'submitted', submittedAt: new Date().toISOString() };
    saveManifestAtomic(manifest); // Saved BEFORE first poll so restarts never double-bill
    console.log(`[SUBMITTED] ${shotId} -> jobId=${jobId}`);
  } else {
    console.log(`[RESUME $0] ${shotId} -> polling saved jobId=${jobId}`);
  }

  const startedAt = Date.now();
  let delayMs = 10_000;
  while (Date.now() - startedAt < POLL_TIMEOUT_MS) {
    await sleep(delayMs);
    const state = await pollFn(jobId);
    if (state.status === 'completed') {
      manifest[hash] = { ...manifest[hash], status: 'completed', resultUrl: state.url, completedAt: new Date().toISOString() };
      saveManifestAtomic(manifest);
      return manifest[hash];
    }
    if (state.status === 'failed') {
      manifest[hash] = { ...manifest[hash], status: 'failed', error: state.error };
      saveManifestAtomic(manifest);
      throw new Error(`JOB_FAILED ${shotId}: ${state.error}`);
    }
    delayMs = Math.min(30_000, Math.round(delayMs * 1.4 + Math.random() * 1_500));
  }
  // Hard timeout reached: keep jobId intact in manifest so next run resumes for $0!
  throw new Error(`POLL_TIMEOUT after ${POLL_TIMEOUT_MS / 1000}s; jobId=${jobId} preserved in ${MANIFEST_PATH}`);
}
JSEOF

node --check "$OUT_JS" && echo "OK: Verified ESM syntax -> $OUT_JS"

Before vs. After (Broken Pattern vs. Verified Fix)

Broken · Broken Stateless Burst (Triggers 429 + 60s Timeout + Double-Billing)
// Fires 15 synchronous paid video jobs at once with zero manifest persistence:
const results = await Promise.all(
  shots.map((s) =>
    fetch('https://fal.run/fal-ai/bytedance/seedance-2.5/image-to-video', {
      method: 'POST',
      body: JSON.stringify(s), // Times out at 60s; rerun bills all 15 clips again!
    })
  )
);
Verified · Verified Async Queue + Concurrency Cap + Atomic Manifest Resume
// 1. Deterministic shot_hash -> skip completed OR resume existing job_id for $0
// 2. Async queue submit (queue.fal.run / Veo LRO) with MAX_CONCURRENT = 2
// 3. Atomic save (write tmp -> rename) of job_id BEFORE polling begins
// 4. Honor Retry-After on 429/503; poll 10s -> 15s -> 22s -> 30s cap (max 600s)
// 5. Hard-stop on non-retryable 400 / 401 / 403 / 422 without burning retries

Why this works: Persisting the async request_id atomically before polling eliminates double-billing on restarts, while capping concurrency to 2 slots and obeying Retry-After keeps 429 errors near zero.

Under the Hood

Why This Failure Happens in Real Pipelines

Video diffusion endpoints behave completely differently from sub-second LLM chat completions. A single 8-second Google Gemini Omni 1.2 Flash clip (~$0.56 720p / ~$0.83 1080p), 5-second Kling 4.0 1080p clip ($1.18), or 5-second ByteDance Seedance 2.5 render (~$0.22–$1.84/s depending on resolution) commonly takes 45 to 210 seconds of dedicated GPU time. Calling synchronous wrapper endpoints like fal.run()—or running a polling loop inside a 60-second serverless HTTP handler—almost guarantees a client timeout while the remote GPU continues rendering and billing your account in the background.

The second costly trap is firing Promise.all(shots.map(submitShot)) across a 10-to-50 shot storyboard. Direct vendor APIs enforce tight concurrent task caps (such as Tier 1 limits of 8 req/min and 40/day on Gemini Omni 1.2 Flash, or 2–5 simultaneous video slots on Kling, MiniMax H3, and Vertex AI Veo LRO quotas). Bursting past that cap triggers HTTP 429 Too Many Requests or vendor code 1303; naive retry loops that hammer the endpoint every 1 second extend the rate-limit lockout and risk cascading duplicate submissions.

Production media batch runners decouple submission from status polling using three mandatory primitives: a bounded concurrency semaphore (MAX_CONCURRENT=2 by default), an atomic on-disk render-manifest.json keyed by deterministic SHA-256 shot hash that persists each provider job_id / operation.name immediately upon HTTP 200/202 acceptance, and a jittered exponential backoff loop honoring HTTP Retry-After headers. If your laptop sleeps, Wi-Fi drops, or a 600-second polling window expires, rerunning the script resumes polling the saved job ID for $0 instead of double-billing.

Step-by-Step Resolution & Verification

  1. 01

    Switch every video integration from synchronous endpoints to async queues

    Use queue.fal.run (fal.queue.submit + webhooks or status polling), Google Veo Long-Running Operations (predictLongRunning), and Kling async task creation endpoints—never blocking HTTP calls inside 60-second serverless routes.

  2. 02

    Persist every returned job_id atomically into render-manifest.json before polling

    Hash each shot’s model, prompt, duration, and input frame SHA-256. Save the job_id via write-temp-plus-rename immediately on submit so restarts resume existing jobs for $0 instead of double-billing.

  3. 03

    Cap concurrency to 2 slots and classify 429/503 separately from 400/422 errors

    Honor HTTP Retry-After headers with jittered exponential backoff on 429 and 503 responses, cap poll cadence at 10s–30s intervals, and fail fast on 400/401/403/422 without looping.

Verification Check · Verify Module Syntax and Dry-Run Deterministic SHA-256 Hashing
node --input-type=module -e 'import { shotHash, submitOrResumeJob } from "./scripts/video-queue-runner.mjs"; const h = shotHash({ model: "veo-3.1-fast", prompt: "85mm dolly", duration: 8 }); const r = await submitOrResumeJob({ shotId: "S01", payload: { h }, dryRun: true }); console.log({ hash: h, status: r.status });'
Expected healthy output:
{ hash: '...', status: 'dry_run' }   # Zero network calls or charges during dry-run verification

How to Prevent This Error From Recurring

GUARDRAIL 01

Default every paid batch script to --dry-run with a hard --max-usd budget guard

Printing exact line-item USD spend before issuing a single POST prevents runaway loops from burning hundreds of dollars on typos.

GUARDRAIL 02

Use provider webhooks instead of serverless polling for user-facing web apps

Pass a webhook URL on fal.ai, Replicate, or Kling so your API route returns HTTP 202 in 200ms and updates Postgres cleanly when the GPU render finishes two minutes later.

GUARDRAIL 03

Never delete job_id from the manifest on a polling timeout

A client-side timeout only means the clip took longer than expected—keeping job_id intact lets the next run fetch the finished video without paying twice.

Troubleshooting FAQs

Why does Vercel or Cloudflare Workers throw a 504 timeout when awaiting a Gemini Omni Flash or fal.ai render?
Serverless HTTP functions enforce hard 10s–60s execution caps, whereas 1080p video renders routinely take 60–240 seconds. Submit the job asynchronously from your API route, save the request_id to your database, return HTTP 202 immediately, and handle completion via provider webhooks or a background queue worker.
Does polling the status endpoint every second count against my HTTP 429 rate limit?
Yes. Tight 1-second polling loops across even 4 parallel jobs generate 240 requests per minute, tripping RPM quotas on Gemini/Veo, Kling, and fal.ai. Start polling after 10 seconds and step up toward 20–30 seconds with random jitter.
Will honoring Retry-After still risk double-charging if a POST times out before returning a job_id?
If a POST submit request itself times out at the TCP layer (rather than returning a clean 429), the provider may have already queued the job. Log submit attempts clearly, avoid blind auto-retries on client read-timeouts for POST creation, and use provider idempotency keys where supported.
What concurrency limit is safe when batch-rendering across multiple accounts or endpoints?
Start with MAX_CONCURRENT=2 on standard Gemini Omni Flash, Kling 4.0, and MiniMax H3 tiers, and scale to 4–8 only after verifying your tier quota in the vendor dashboard. For mixed pipelines, running 2 jobs on fal.ai and 2 on the Google Gemini API in parallel doubles throughput without hitting either provider’s RPM wall.
Why use writeFileSync to a temp file followed by renameSync for render-manifest.json?
Writing directly over render-manifest.json risks leaving a half-written truncated JSON file if Node crashes or receives SIGINT mid-write—wiping out every saved job_id. POSIX renameSync swaps the directory pointer atomically so the manifest is always 100% valid JSON.
Use this page in AI tools or notes
raw .md