冪等キーで安全にリトライする
このレシピでは、ネットワーク障害やあいまいなエラーの後に、インポート開始の呼び出しを安全にリトライする方法を紹介します。POST /api/v1/monitoring/loan/imports に Idempotency-Key ヘッダーを付けると、2回目の呼び出しでは1回目と同じインポートIDが、新たに発行されたアップロードURLとともに返されます。重複したインポートは作成されません。
これを使う場面
直前のインポート開始の呼び出しが受け付けられたかどうかわからない場合は、常に使います。代表的なケースは次の2つです。
- レスポンスが届く前に、HTTPクライアントがタイムアウトを発生させた。リクエストはWaafirに届いてインポートを開始しているかもしれませんが、それはわかりません。
- 冪等でない処理から5xxエラーが返され、重複した処理を発生させるリスクを負わずにリトライしたい。
プラットフォーム共通の規則として、すべての変更系エンドポイント が Idempotency-Key を受け付けます。ここで扱うインポート開始エンドポイントのほか、エクスポートエンドポイントや、その他の監査関連の変更系エンドポイントも同様です。論理的な操作ごとに新しいキーを使い、同じ操作のリトライでは同じキーを再利用してください。よくあるパターンは、「日次インポートバッチ」という意図ごとにUUID v4を1回生成し、呼び出しが成功するまでジョブの状態に保持しておく方法です。
契約
- ヘッダーは
Idempotency-Key: <your-string>です。最大255文字です。 - 本文でも
idempotencyKeyフィールドを受け付けますが、両方が存在する場合は ヘッダーが優先されます。プラットフォーム共通の正規の指定場所であるヘッダーを使うことをお勧めします。 - 同じ
(orgId, idempotencyKey)で繰り返し呼び出すと、次の内容が返されます。- 同じ
importId。 - レスポンス内の
reused: true。 - 新たに発行されたアップロードURL(元のURLは期限切れになるため、新しいURLを使うのが安全です)。
- 同じ
- 同じキーで 異なる 本文を送って繰り返し呼び出すと、拒否されます。キーは元のリクエストの形式に紐づけられています。
レシピ
# curl — start an import with an idempotency key, then retry safely
set -euo pipefail
PAT="${WAAFIR_PAT}"
BASE_URL="${WAAFIR_BASE_URL:-https://app.waafir.io}"
NDJSON_FILE="loans-2026-05-22.ndjson"
# Generate a fresh key per logical batch intent; keep it stable across retries.
IDEMPOTENCY_KEY="loan-import-2026-05-22-$(uuidgen)"
start_import() {
curl -fsS -X POST "${BASE_URL}/api/v1/monitoring/loan/imports" \
-H "Authorization: Bearer ${PAT}" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: ${IDEMPOTENCY_KEY}" \
-d "$(cat <<JSON
{
"kind": "loan",
"filename": "${NDJSON_FILE}",
"sizeBytes": $(stat -c%s "${NDJSON_FILE}")
}
JSON
)"
}
# First call. If the network bombs out we have no idea whether the
# request landed — but the same key on the next attempt guarantees no
# duplicate import.
RESULT=$(start_import || true)
if [ -z "${RESULT}" ] || ! echo "${RESULT}" | jq -e .importId > /dev/null; then
echo "first call ambiguous; retrying with the same idempotency key…"
RESULT=$(start_import)
fi
echo "${RESULT}" | jq '{importId, reused, uploadUrl}'
# On a retry, reused == true; the importId matches the first call's; the
# uploadUrl is fresh.// TypeScript — retry start-import safely with an Idempotency-Key
import { randomUUID } from "node:crypto";
import { statSync } from "node:fs";
const PAT = process.env.WAAFIR_PAT!;
const BASE_URL = process.env.WAAFIR_BASE_URL ?? "https://app.waafir.io";
const NDJSON_FILE = "loans-2026-05-22.ndjson";
const idempotencyKey = `loan-import-2026-05-22-${randomUUID()}`;
async function startImport() {
return fetch(`${BASE_URL}/api/v1/monitoring/loan/imports`, {
method: "POST",
headers: {
Authorization: `Bearer ${PAT}`,
"Content-Type": "application/json",
"Idempotency-Key": idempotencyKey,
},
body: JSON.stringify({
kind: "loan",
filename: NDJSON_FILE,
sizeBytes: statSync(NDJSON_FILE).size,
}),
});
}
// Retry up to 3 times on transient failures; the same key makes this safe.
let lastError: unknown;
let result: { importId: string; reused: boolean; uploadUrl: string } | null = null;
for (let attempt = 1; attempt <= 3; attempt++) {
try {
const res = await startImport();
if (!res.ok) throw new Error(`HTTP ${res.status}: ${await res.text()}`);
result = (await res.json()) as typeof result;
break;
} catch (err) {
lastError = err;
console.warn(`attempt ${attempt} failed; retrying with same idempotency key`, err);
await new Promise((r) => setTimeout(r, 1_000 * attempt));
}
}
if (!result) throw lastError;
console.log({ importId: result.importId, reused: result.reused, uploadUrl: result.uploadUrl });# python — retry start-import safely with an Idempotency-Key
import os
import uuid
import time
import requests
from pathlib import Path
PAT = os.environ["WAAFIR_PAT"]
BASE_URL = os.environ.get("WAAFIR_BASE_URL", "https://app.waafir.io")
NDJSON_FILE = Path("loans-2026-05-22.ndjson")
idempotency_key = f"loan-import-2026-05-22-{uuid.uuid4()}"
def start_import():
return requests.post(
f"{BASE_URL}/api/v1/monitoring/loan/imports",
headers={
"Authorization": f"Bearer {PAT}",
"Content-Type": "application/json",
"Idempotency-Key": idempotency_key,
},
json={
"kind": "loan",
"filename": NDJSON_FILE.name,
"sizeBytes": NDJSON_FILE.stat().st_size,
},
timeout=30,
)
# Retry up to 3 times on transient errors. The same key makes a second
# successful call a guaranteed replay of the first.
last_exc = None
result = None
for attempt in range(1, 4):
try:
response = start_import()
response.raise_for_status()
result = response.json()
break
except requests.RequestException as exc:
last_exc = exc
print(f"attempt {attempt} failed; retrying with same idempotency key: {exc}")
time.sleep(attempt)
if result is None:
raise RuntimeError("all retries exhausted") from last_exc
print({
"importId": result["importId"],
"reused": result["reused"],
"uploadUrl": result["uploadUrl"],
})確認すべきこと
最初の呼び出しが成功した場合、reused は false です。同じキーでのそれ以降の呼び出しでは、reused は true になり、importId は最初の呼び出しのものと一致します。uploadUrl は呼び出しのたびに再生成されるため、古いURLの期限が切れた後にリトライしても安全です。常に最新のレスポンスのURLを使用してください。
同じキーで 異なる リクエスト本文を送ってリトライすると、APIは、そのキーが矛盾するリクエストの形式に紐づけられていることを示すエラーを返します。新しい意図に対してはキーを変更してください。