💻 Dev

🛠️ 처음부터 만드는 Retry — 실패해도 다시 시도하기

API 호출이 실패했을 때 자동으로 재시도하는 `retry` 함수를 직접 만들어봅니다.

핵심 아이디어


네트워크는 불안정합니다. 한 번 실패했다고 포기하지 말고, 정해진 횟수만큼 간격을 두고 재시도하면 성공률을 높일 수 있습니다.

구현


```typescript
type RetryOptions = {
maxAttempts?: number;
delayMs?: number;
backoff?: boolean; // 지수 백오프 적용 여부
};
async function retry(
fn: () => Promise,
options: RetryOptions = {}
): Promise {
const { maxAttempts = 3, delayMs = 1000, backoff = true } = options;
let lastError: Error;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
return await fn();
} catch (error) {
lastError = error as Error;
console.warn(`시도 ${attempt}/${maxAttempts} 실패: ${lastError.message}`);
if (attempt < maxAttempts) {
const wait = backoff ? delayMs * 2 ** (attempt - 1) : delayMs;
await new Promise((r) => setTimeout(r, wait));
}
}
}
throw lastError!;
}
```

사용 예시


```typescript
const data = await retry(
() => fetch('https://api.example.com/data').then((r) => {
if (!r.ok) throw new Error(`HTTP ${r.status}`);
return r.json();
}),
{ maxAttempts: 3, delayMs: 500, backoff: true }
);
// 실패 시: 500ms → 1000ms → 최종 에러
```

지수 백오프란?


재시도 간격을 `delay × 2^(attempt-1)`로 늘려가는 전략입니다. 서버가 과부하일 때 모든 클라이언트가 동시에 재시도하는 thundering herd 문제를 완화합니다.

실무 팁


  • 멱등성 확인: POST 요청을 무작정 재시도하면 중복 생성될 수 있습니다. GET이나 멱등한 작업에만 적용하세요.

  • jitter 추가: `wait + Math.random() * wait`로 랜덤 지연을 더하면 동시 재시도 충돌을 줄입니다.

  • 취소 지원: `AbortController`와 조합하면 사용자가 재시도를 중단할 수 있습니다.
  • 💬 0
    👁 0 views

    Comments (0)

    💬

    No comments yet.

    Be the first to comment!