멱등성 키로 안전하게 재시도하기
이 레시피는 네트워크 장애나 모호한 오류 후에 가져오기 시작 호출을 안전하게 재시도하는 방법을 보여 줍니다. POST /api/v1/monitoring/loan/imports에 Idempotency-Key 헤더를 지정하면 두 번째 호출이 새로 발급된 업로드 URL과 함께 첫 번째 호출과 같은 가져오기 ID를 반환하며, 중복 가져오기는 생성되지 않습니다.
사용 시점
이전 가져오기 시작 호출이 반영되었는지 알 수 없을 때마다 사용합니다. 대표적인 경우는 두 가지입니다.
- 응답이 도착하기 전에 HTTP 클라이언트에서 타임아웃이 발생한 경우. 요청이 Waafir에 도달해 가져오기가 시작되었을 수도 있지만, 알 수 없습니다.
- 멱등하지 않은 인터페이스에서 5xx 오류를 받았고, 중복 작업의 위험 없이 재시도하고 싶은 경우.
플랫폼 전반의 규칙은 모든 변경 엔드포인트가 Idempotency-Key를 받는다는 것입니다. 여기서 다루는 가져오기 시작 엔드포인트, 내보내기 엔드포인트, 그 밖의 감사 변경 엔드포인트가 모두 해당합니다. 논리적 작업마다 새 키를 사용하고, 같은 작업의 재시도에서는 키를 재사용하세요. 일반적인 패턴은 "daily-import-batch" 의도마다 UUID v4를 한 번 생성하고, 호출이 성공할 때까지 작업 상태에 보관하는 것입니다.
계약
- 헤더는
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는 해당 키가 충돌하는 요청 형식에 묶여 있다는 오류를 반환합니다. 새 의도에는 키를 교체하세요.