MAGI-2 API Concurrency, Async Polling & Webhook Architecture
Flagship 480B MAGI-2 renders span 7 to 26 minutes under normal cloud load—far beyond serverless or load-balancer HTTP timeouts—and many launch wrappers enforce strict 1-to-2 concurrent job caps. Production backends must split submission (HTTP 202 + client idempotency key + durable ledger hold) from background reconciliation (bounded 20–30s polling with jittered backoff, atomic credit refunds, and immediate R2/S3 output mirroring).
- Observed Latency
- 7–26 min (longer peak)
- Recommended Poll Cadence
- 60s grace -> 25s interval
- Studio Concurrency
- 2 (Creator) / 5 (Dir) / 12 (API)
- Duplicate Protection
- Client idempotency_key
1. Build a deterministic PostgreSQL / SQLite job state machine
The most common production bug reported by developers integrating long-running video models is losing track of in-flight jobs after a container restart, browser disconnect, or serverless timeout—either stranding user credits forever or re-submitting duplicate 30-second renders costing $2.40 each. Model every MAGI-2 job as an immutable state machine backed by a double-entry `credit_ledger` table.
| State | Trigger | Ledger State | Allowed Next States |
|---|---|---|---|
| queued | Client POST validated + idempotency key inserted | Credits debited (held) atomically | submitted, refunded |
| submitted | Upstream returned HTTP 200/202 with `request_id` | Hold active | processing, completed, refunded |
| processing | Poller confirmed active upstream generation | Hold active | completed, refunded |
| completed | MP4 mirrored to R2/S3 & verified non-empty | Hold permanently settled | Terminal |
| refunded | Upstream failed, timed out >45m, or `policy_filtered` | +100% idempotent reversal entry posted | Terminal |
2. Bounded polling cadence for 7–26 minute render queues
Polling every 1 second during a 15-minute render wastes 900 HTTP calls per job and risks hitting upstream rate limiters. Because flagship 480B MAGI-2 never finishes a 1080p audio-video clip in under a minute, apply a two-stage polling schedule: wait an initial 60-second grace window after submission, then poll every 25 seconds (±4s random jitter) on healthy responses. On transient HTTP 429 or 5xx responses from the status endpoint, back off exponentially (15s -> 30s -> 60s -> 120s max) without prematurely failing the job.
Set a conservative hard reconciliation timeout at 45–60 minutes before escalating to manual check or automatic refund, since community reports on `r/HiggsfieldAI` confirm peak viral traffic can temporarily push complex 30-second multi-shot queues beyond the 26-minute normal band.
export async function pollPredictionWithBackoff(
requestId: string,
apiKey: string,
options = { initialGraceMs: 60_000, pollIntervalMs: 25_000, maxWaitMs: 45 * 60_000 }
) {
const startedAt = Date.now();
await sleep(options.initialGraceMs);
let transientErrors = 0;
while (Date.now() - startedAt < options.maxWaitMs) {
const res = await fetch(
`https://api.atlascloud.ai/api/v1/model/prediction/${encodeURIComponent(requestId)}`,
{ headers: { Authorization: `Bearer ${apiKey}` }, cache: "no-store" }
);
if (!res.ok) {
transientErrors += 1;
const backoff = Math.min(120_000, 15_000 * 2 ** (transientErrors - 1));
await sleep(backoff + Math.floor(Math.random() * 4_000));
continue;
}
transientErrors = 0;
const raw = await res.json();
const data = raw.data ?? raw;
const status = String(data.status || "").toLowerCase();
if (status === "completed" || status === "succeeded") {
const url = data.outputs?.[0];
if (!url) return { terminal: "refunded" as const, reason: "policy_filtered" };
return { terminal: "completed" as const, outputUrl: url };
}
if (status === "failed" || status === "canceled" || status === "cancelled") {
return { terminal: "refunded" as const, reason: data.error || "upstream_failed" };
}
const jitter = Math.floor(Math.random() * 5_000);
await sleep(options.pollIntervalMs + jitter);
}
throw new Error(`Prediction ${requestId} exceeded maxWaitMs; escalate before refunding.`);
}3. Signed webhooks, idempotency & concurrency pools
On MagiAI Studio's Studio API tier (12 concurrent jobs across one unified wallet), completed and refunded jobs can emit signed HTTPS webhooks so your application eliminates background polling loops completely. Always verify webhook signatures using constant-time HMAC-SHA256 comparison (`crypto.timingSafeEqual`) over the raw request body plus timestamp replay window (<=5 minutes), and process webhook deliveries idempotently keyed on `job_id` so retried deliveries never credit or notify users twice.
When routing batches through single-job or low-concurrency providers, insert a bounded FIFO semaphore (Redis BullMQ, Cloud Tasks, or Postgres `FOR UPDATE SKIP LOCKED` worker pool) sized strictly to your verified provider slot count. Never fire 20 concurrent `POST /generateVideo` bursts blindly—doing so triggers immediate HTTP 429 rejections and chaotic retry storms.
import crypto from "node:crypto";
export function verifyWebhookSignature(rawBody: string, headerSig: string, secret: string): boolean {
const expected = crypto.createHmac("sha256", secret).update(rawBody, "utf8").digest("hex");
const expectedBuf = Buffer.from(expected, "hex");
const receivedBuf = Buffer.from(headerSig.replace(/^sha256=/, ""), "hex");
if (expectedBuf.length !== receivedBuf.length) return false;
return crypto.timingSafeEqual(expectedBuf, receivedBuf);
}