Skip to main content
MAGIAI
核心 API 規格實測驗證 2026-12-02

MAGI-2 API 併發限制、非同步輪詢與 Webhook 架構實戰

在一般雲端負載下,旗艦級 480B MAGI-2 的單次算圖耗時為 7 至 26 分鐘——遠超過無伺服器函式或負載平衡器的 HTTP 逾時上限——且許多首發封裝服務更強制限制同時僅能執行 1 至 2 筆任務。生產環境後端必須將任務提交(HTTP 202 + 用戶端冪等鍵 + 持久化帳本預扣)與背景核對流程(具備隨機抖動退避機制的 20–30 秒有界輪詢、原子化點數退款與即時 R2/S3 成品鏡像轉存)徹底拆離。

實測算圖延遲
7–26 分鐘(尖峰時段更久)
建議輪詢節奏
寬限 60 秒 -> 間隔 25 秒
Studio 併發上限
2(Creator)/ 5(Dir)/ 12(API)
重複提交防護
用戶端 idempotency_key

1. 建構確定性的 PostgreSQL / SQLite 任務狀態機

開發者整合長耗時影片模型時最常回報的生產環境錯誤,是在容器重啟、瀏覽器斷線或無伺服器函式逾時後遺失執行中任務的追蹤狀態——這會導致使用者點數遭到永久鎖死,或重複送出多筆單價 $2.40 的 30 秒算圖任務。請將每一筆 MAGI-2 任務建模為不可變的狀態機,並以複式記帳的 `credit_ledger` 資料表作為底層支撐。

標準 MAGI-2 生產環境任務生命週期
狀態觸發條件帳本狀態允許轉換的下個狀態
queued用戶端 POST 驗證通過並寫入冪等鍵原子化預扣(鎖定)點數submitted, refunded
submitted上游回傳 HTTP 200/202 並附帶 `request_id`額度鎖定生效中processing, completed, refunded
processing輪詢器確認上游正在進行算圖生成額度鎖定生效中completed, refunded
completedMP4 已鏡像轉存至 R2/S3 並驗證檔案非空預扣額度永久結算終止狀態(Terminal)
refunded上游失敗、逾時超過 45 分鐘或觸發 `policy_filtered`寫入 +100% 冪等沖銷退款分錄終止狀態(Terminal)

2. 針對 7–26 分鐘算圖佇列的有界輪詢節奏

在長達 15 分鐘的算圖過程中每秒輪詢一次,等於每筆任務浪費 900 次 HTTP 呼叫並極易觸發上游限流機制。由於旗艦級 480B MAGI-2 絕不可能在 1 分鐘內完成 1080p 含音訊影片的算圖,請採用兩階段輪詢排程:提交任務後先等待 60 秒初始寬限期,接著在回應正常時每 25 秒(附加 ±4 秒隨機抖動)輪詢一次。當狀態端點回傳暫時性的 HTTP 429 或 5xx 錯誤時,請執行指數退避(15 秒 -> 30 秒 -> 60 秒 -> 最高 120 秒),切勿過早判定任務失敗。

建議將硬性核對逾時門檻保守設為 45 至 60 分鐘,超過後再升級為人工查核或自動退款;因為依據 `r/HiggsfieldAI` 社群回報,流量尖峰期間,複雜的 30 秒多鏡頭佇列可能會暫時超出 26 分鐘的常態區間。

具冪等性與退避機制的有界工作進程輪詢器(TypeScript)
typescript
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. 簽章 Webhook、冪等性與併發工作池

在 MagiAI Studio 的 Studio API 方案(單一統一錢包支援 12 筆併發任務)下,完成與退款的任務皆可發送經簽章的 HTTPS Webhook,讓你的應用程式徹底省去背景輪詢迴圈。驗證 Webhook 簽章時,務必針對原始請求主體與時間戳記重放視窗(<= 5 分鐘)執行常數時間的 HMAC-SHA256 比對(`crypto.timingSafeEqual`),並以 `job_id` 作為冪等鍵處理推送事件,確保重試推送絕不會重複入帳或重複通知使用者。

若將批次任務路由至單一併發或低併發上限的供應商,請務必在前端加上嚴格對齊已驗證供應商槽位數量的有界 FIFO 號誌(例如 Redis BullMQ、Cloud Tasks 或 Postgres `FOR UPDATE SKIP LOCKED` 工作池)。切勿盲目同時發出 20 個併發 `POST /generateVideo` 瞬間大量請求——這會立即觸發 HTTP 429 拒絕服務並引發混亂的重試風暴。

常數時間 HMAC-SHA256 Webhook 簽章驗證(Node.js)
typescript
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);
}
工程備註: MagiAI Studio 在 Studio 任務 Webhook 與 Airwallex 支付 Webhook 上皆套用完全相同的常數時間 HMAC-SHA256 簽章驗證標準。

相關工程文件

MAGI-2 API 併發控制、非同步佇列與 Webhook 架構