💻 Dev

🛠️ 처음부터 만드는 Retry — 실패한 함수를 자동으로 재시도하기

# 재시도 로직을 직접 구현해보자
API 호출이나 데이터베이스 쿼리는 일시적인 네트워크 오류로 실패할 수 있다. Retry는 실패한 함수를 지정된 횟수만큼 자동으로 다시 실행하는 패턴이다.

기본 구현


```javascript
function retry(fn, options = {}) {
const { maxAttempts = 3, delay = 1000 } = options;

return async function(...args) {
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
return await fn(...args);
} catch (error) {
if (attempt === maxAttempts) throw error;
await new Promise(resolve => setTimeout(resolve, delay));
}
}
};
}
```

조건부 재시도 (지수 백오프)


실패 간격을 점점 늘려서 서버 부하를 줄일 수 있다:
```javascript
function retryWithBackoff(fn, options = {}) {
const { maxAttempts = 3, initialDelay = 1000, backoffMultiplier = 2, shouldRetry = () => true } = options;

return async function(...args) {
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
return await fn(...args);
} catch (error) {
if (attempt === maxAttempts || !shouldRetry(error)) throw error;
const delay = initialDelay * Math.pow(backoffMultiplier, attempt - 1);
await new Promise(resolve => setTimeout(resolve, delay));
}
}
};
}
```

실전 예제: API 호출


```javascript
// 네트워크 오류만 재시도하고, 4xx 에러는 즉시 실패
const fetchWithRetry = retryWithBackoff(
async (url) => {
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
},
{
maxAttempts: 3,
initialDelay: 500,
shouldRetry: (error) => !error.message.includes('HTTP 4')
}
);
await fetchWithRetry('https://api.example.com/data');
```


  • 비동기 전용: 콜백 기반 함수는 프로미스로 변환(`promisify`) 후 사용

  • 재시도 상한: 무한 루프 방지를 위해 최대 재시도 횟수는 필수

  • 선택적 재시도: 특정 에러만 재시도하도록 필터링하면 불필요한 대기 시간 절감

  • 참고: [Promise 문서](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
    💬 0
    👁 0 views

    Comments (0)

    💬

    No comments yet.

    Be the first to comment!