PHpullh
학습 라이브러리/Java/리트라이 패턴

JAVA · 디자인패턴

리트라이 패턴

일시적 장애에 대응하는 재시도 로직과 지수 백오프 전략입니다.

디자인패턴중급retry재시도지수백오프장애허용

핵심 설명

일시적 장애에 대응하는 재시도 로직과 지수 백오프 전략입니다.

Java code

import java.util.concurrent.*;
import java.util.function.Supplier;

public class RetryPattern {
    record RetryConfig(int maxAttempts, long initialDelay, double multiplier) {}

    // 지수 백오프 재시도
    static <T> T retryWithBackoff(Supplier<T> action, RetryConfig config) {
        Exception lastException = null;
        long delay = config.initialDelay();

        for (int attempt = 1; attempt <= config.maxAttempts(); attempt++) {
            try {
                T result = action.get();
                if (attempt > 1) {
                    System.out.println("성공 (시도 " + attempt + ")");
                }
                return result;
            } catch (Exception e) {
                lastException = e;
                System.out.printf("시도 %d/%d 실패: %s%n",
                    attempt, config.maxAttempts(), e.getMessage());

                if (attempt < config.maxAttempts()) {
                    try {
                        // 지터 추가 (무작위 변동)
                        long jitter = (long)(delay * Math.random() * 0.3);
                        Thread.sleep(delay + jitter);
                        delay = (long)(delay * config.multiplier());
                    } catch (InterruptedException ie) {
                        Thread.currentThread().interrupt();
                        break;
                    }
                }
            }
        }
        throw new RuntimeException("최대 재시도 초과", lastException);
    }

    public static void main(String[] args) {
        var config = new RetryConfig(3, 100, 2.0);
        int[] callCount = {0};

        try {
            String result = retryWithBackoff(() -> {
                callCount[0]++;
                if (callCount[0] < 3) throw new RuntimeException("일시 장애");
                return "성공!";
            }, config);
            System.out.println("결과: " + result);
        } catch (RuntimeException e) {
            System.out.println("최종 실패: " + e.getMessage());
        }
    }
}

학습 팁

지터(jitter)를 추가하면 여러 클라이언트가 동시에 재시도하는 thundering herd 문제를 완화합니다.

주의할 점

재시도 대상이 아닌 예외(인증 실패, 잘못된 요청 등)까지 재시도하면 불필요한 부하가 발생합니다. 재시도 가능한 예외를 구분하세요.

자주 묻는 질문

리트라이 패턴란 무엇인가요?

일시적 장애에 대응하는 재시도 로직과 지수 백오프 전략입니다.

리트라이 패턴 학습 시 주의할 점은 무엇인가요?

재시도 대상이 아닌 예외(인증 실패, 잘못된 요청 등)까지 재시도하면 불필요한 부하가 발생합니다. 재시도 가능한 예외를 구분하세요.