공공부하자개발 · 영어 학습 노트
실무 배치대용량 데이터 처리0/6 완료
  • 01배치 프로세스 개념과 아키텍처
  • 02대용량 파일 I/O (NIO, Buffered)
  • 03Chunk 단위 처리와 OOM 방지
  • 04트랜잭션: 커밋과 롤백 시뮬레이션
  • 05Skip과 Retry 로직 구현
  • 06메서드 활용 패턴 (배치 유틸)
사이트 소개개인정보처리방침연락처
© 2026 공부하자
홈 › 실무 배치 › 05 / 6

Skip과 Retry 로직 구현

섹션 7 · 전체 보기진행 0 / 6
1왜 배우는가2핵심 원리3코드 예제4응용 변형 예제5자주 하는 실수 (Tip)6연습 문제7정리전체 보기‹ 이전다음 ›

실패를 일시적/영구적/치명적으로 분류해, 재시도할 것은 백오프와 함께 재시도하고, 건너뛸 것은 한도 안에서 건너뛰며 데드 레터에 남기고, 멈춰야 할 것은 즉시 멈추는 배치를 순수 자바로 구현하고 최종 리포트까지 출력할 수 있게 됩니다.

1. 왜 배우는가

100만 건 회원에게 알림을 보내는 배치가 있습니다. 999,999건은 정상인데 한 건의 전화번호가 010-abcd-1234 입니다. 이 한 건 때문에 배치 전체가 죽어야 할까요? 그러면 새벽에 운영자가 불려 나와 그 행을 손으로 고치고 재실행해야 합니다. 반대로 외부 알림 API 가 0.1% 확률로 타임아웃을 낸다면, 그 1,000건을 실패로 기록하고 끝내야 할까요? 다시 한 번만 호출하면 대부분 성공할 텐데요.

실패는 한 종류가 아닙니다. 다시 하면 되는 실패(네트워크 타임아웃, DB 락 대기), 다시 해도 안 되는 실패(데이터 형식 오류, 존재하지 않는 계좌), 더 진행하면 안 되는 실패(DB 접속 불가, 디스크 꽉 참). 세 가지를 같은 catch (Exception e) 로 다루면 어느 쪽으로든 사고가 납니다.

재시도해야 할 것을 스킵하면 데이터가 빠지고, 스킵해야 할 것을 재시도하면 시간만 낭비하고, 중단해야 할 것을 스킵하면 "입력 파일이 통째로 깨졌는데 정상 종료"가 됩니다.

Spring Batch 의 retry(), skip(), skipLimit(), noRollback() 은 이 분류를 설정으로 표현한 것입니다. 이 레슨에서는 그 밑에 있는 RetryTemplate 과 SkipPolicy 를 직접 만들어 04 레슨의 청크 처리에 통합하고, 04 에서 "청크 전체 롤백"으로 남겨 둔 문제를 "실패 건만 제외하고 나머지 커밋"으로 완성합니다.

2. 핵심 원리

2.1 실패 유형 분류 — 모든 설계의 출발점

유형 예 특징 대응
일시적(transient) 네트워크 타임아웃, DB 락 타임아웃, 커넥션 풀 고갈, 외부 API 429/503, 데드락 시간이 지나면 저절로 해결됨. 같은 입력으로 다시 하면 성공할 가능성이 높음 재시도 (횟수 제한 + 백오프)
영구적(permanent) 숫자 컬럼에 문자, 필수 필드 누락, 존재하지 않는 참조 키, API 400 Bad Request 입력 데이터 자체의 문제. 몇 번을 다시 해도 같은 결과 스킵 (기록 후 건너뜀)
치명적(fatal) DB 접속 불가, 디스크 풀, 설정 파일 없음, OOM, 인증 만료 이 건만의 문제가 아님. 다음 건도 전부 실패할 것 중단 (즉시 FAILED, 알림)

분류 기준은 "같은 입력으로 다시 하면 결과가 달라지는가"와 "다른 건도 영향을 받는가"입니다.

text
                        다시 하면 결과가 달라지는가?
                          ┌────────┴────────┐
                         예                 아니오
                          │                  │
                       재시도          다른 건도 실패하는가?
                      (transient)      ┌──────┴──────┐
                                      예             아니오
                                       │               │
                                     중단            스킵
                                    (fatal)       (permanent)

분류는 예외 타입으로 표현합니다. TransientApiException 은 재시도, PermanentApiException 과 IllegalArgumentException 은 스킵, 그 밖의 예외는 중단. 예외 계층을 이렇게 설계하는 것이 배치 코드의 절반입니다.

2.2 재시도 원리 — 횟수, 백오프, 지터

text
시도 1 ──✗──▶ 대기 100ms ──▶ 시도 2 ──✗──▶ 대기 200ms ──▶ 시도 3 ──✗──▶ 대기 400ms ──▶ 시도 4 ──✓
                                                                                        (maxAttempts=4)
시도 4 ──✗──▶ RetryExhaustedException (원인 예외를 cause 로 보존)
요소 왜 필요한가
최대 횟수 무한 재시도는 배치를 영원히 매달아 둔다. 3~5회가 관행
백오프(대기) 즉시 재시도는 상대가 아직 회복되지 않은 상태에서 다시 때리는 것. 락 경합이라면 상대 트랜잭션이 끝날 시간을 줘야 한다
지수 증가 대기를 100, 200, 400, 800 으로 늘리면 짧은 장애는 빨리, 긴 장애는 상대에 부담 없이 기다린다
최대 대기 지수 증가가 무한히 커지지 않도록 상한(예: 5초)
재시도 가능 예외 판별 영구 오류를 재시도하면 시간만 낭비. 화이트리스트로 명시
리스너 재시도가 일어났다는 사실을 로그로 남겨야 "왜 30분 더 걸렸는지" 알 수 있다

지터(jitter)가 필요한 이유 — thundering herd

외부 API 가 1초간 죽었다가 살아났습니다. 워커 100개가 동시에 실패하고, 모두 정확히 200ms 후에 재시도하면 API 는 같은 순간에 100개 요청을 받아 다시 죽습니다. 그리고 400ms 후에 또 동시에... 이것이 thundering herd(우르르 몰려드는 무리) 문제입니다.

text
지터 없음:   |100 요청|        |100 요청|                |100 요청|         ← 매번 스파이크
지터 있음:   | 3| 7|12| 9|15|11| 8|10| 6|13| 4| 2| ...                    ← 분산

대기 시간에 랜덤(예: 50%~100%)을 곱하면 재시도가 시간축에 흩어집니다. AWS 가 권장하는 "full jitter" 는 random(0, base × 2^attempt) 입니다.

정책 대기 시간 (attempt 1, 2, 3, 4) 용도
fixed(200) 200, 200, 200, 200 단순, 내부 시스템
exponential(100, 2, 5000) 100, 200, 400, 800 외부 API 기본
exponentialWithJitter(100, 2, 5000) 50100, 100200, 200400, 400800 워커 다수, 외부 API 권장

2.3 재시도가 안전하려면 — 멱등성 재등장

재시도는 "같은 요청을 다시 보내는 것"입니다. 첫 요청이 실제로는 성공했는데 응답만 유실된 경우(타임아웃의 흔한 실체), 재시도는 이중 처리가 됩니다. 결제 API 를 재시도해 두 번 결제되는 사고가 이렇게 납니다. 04 레슨의 멱등 키가 여기서 다시 필요합니다. 재시도하는 모든 외부 호출에는 멱등 키가 있어야 하고, 없다면 재시도 대신 스킵 + 수동 확인이 안전합니다.

2.4 스킵 원리 — 한도와 데드 레터

text
건 처리 ──✗──▶ 스킵 가능 예외?
                ├─ 아니오 → 던짐 (중단)
                └─ 예     → skipCount++
                            ├─ skipCount > skipLimit → SkipLimitExceededException (중단)
                            └─ 아니면 → 데드 레터에 기록, 다음 건으로
요소 왜 필요한가
스킵 가능 예외 화이트리스트 아무 예외나 스킵하면 치명적 오류(DB 다운)도 "건너뛰고" 100만 건을 전부 스킵한 뒤 정상 종료한다
skipLimit 0.1% 오류는 정상, 10% 면 입력 파일 문제. 한도를 넘으면 실패시켜 사람이 보게 한다
데드 레터(dead letter) 스킵 건을 사유·원본과 함께 별도 기록. 기록 없는 스킵은 데이터 유실
스킵 건수 리포트 총 건수 대비 스킵 비율을 매일 비교. 갑자기 늘면 상류 시스템 변경 신호

"데드 레터"는 메시지 큐 용어에서 왔습니다. 배달할 수 없는 편지를 모아 두는 우체국의 사서함입니다.

2.5 청크 처리에 스킵/재시도 통합 — 전체 흐름

04 레슨에서 청크 안의 한 건이 실패하면 청크 전체를 롤백했습니다. 이제 실패 건만 제외합니다.

text
청크 (200건) 시작
  │
  ├─ 건 1: parse ✓ → api.send ✓                          → sent 에 추가
  ├─ 건 2: parse ✗ (NumberFormatException)
  │        └ 스킵 가능? 예 → skipCount++ (한도 검사) → 데드 레터 기록
  ├─ 건 3: parse ✓ → api.send ✗ Transient
  │        └ 재시도 1 (2ms) ✗ → 재시도 2 (4ms) ✓         → sent 에 추가
  ├─ 건 4: parse ✓ → api.send ✗ Transient ✗ ✗ ✗
  │        └ RetryExhausted (cause=Transient) → 스킵 가능? 예 → 데드 레터
  ├─ 건 5: parse ✓ → api.send ✗ Permanent (400)
  │        └ 재시도 대상 아님 → 즉시 → 스킵 가능? 예 → 데드 레터
  ├─ 건 6: db 접속 불가 (SQLException)
  │        └ 재시도 대상 아님 → 스킵 가능? 아니오 → 던짐 → 배치 FAILED
  │
  └─ (건 6 이 없었다면) writer.write(sent) → 커밋: 200건 중 197건
단계 판단 결과
1 재시도 가능 예외인가? 예 → 백오프 후 재시도 (최대 N회)
2 재시도 소진 또는 재시도 불가 스킵 정책에 넘김
3 스킵 가능 예외인가? (RetryExhausted 는 cause 로 판별) 예 → 한도 검사 → 데드 레터 → 다음 건
4 스킵 불가 던짐 → 청크 롤백 → 배치 FAILED

Spring Batch 는 여기에 한 단계가 더 있습니다. Writer(청크 쓰기)에서 실패하면 어느 건이 원인인지 모르므로, 청크를 롤백한 뒤 한 건씩 다시 처리하며 실패 건을 찾아 스킵합니다(scan 모드). 이 레슨은 건별 처리 단계에서 실패를 잡는 단순한 형태를 다룹니다.

2.6 재시도와 트랜잭션의 관계

재시도 범위가 어디까지인지가 중요합니다.

재시도 범위 설명 주의
건별 연산(API 호출 하나) 이 레슨의 방식. 가볍고 안전 호출이 멱등해야 함
청크 전체 청크 롤백 후 청크 처음부터 다시. DB 데드락 처리에 사용 청크 안의 외부 호출이 반복됨 → 멱등 키 필수
Step/Job 전체 04 의 재시작. 사람이 또는 스케줄러가 트리거 체크포인트 필요

DB 데드락(SQLTransientException)은 건별이 아니라 청크 트랜잭션 전체가 롤백되므로 청크 단위 재시도가 맞습니다. 외부 API 타임아웃은 건별 재시도가 맞습니다. 둘을 혼동하면 "API 는 성공했는데 청크 재시도로 또 호출"이 됩니다.

2.7 서킷 브레이커 — 재시도의 상위 개념

외부 API 가 완전히 죽어 있는데 100만 건 각각을 4번씩 재시도하면 400만 번 실패하고 백오프까지 합쳐 몇 시간을 낭비합니다. 서킷 브레이커(circuit breaker)는 연속 실패가 임계치를 넘으면 회로를 열어 일정 시간 동안 호출 자체를 하지 않고 즉시 실패시킵니다.

text
CLOSED (정상) ──연속 실패 ≥ 5──▶ OPEN (즉시 실패, 30초) ──시간 경과──▶ HALF-OPEN (1건 시험)
   ▲                                                                       │
   └──────────────────── 성공 ◀───────────────────────────────────────────┘
                                                            실패 → 다시 OPEN

배치에서는 "OPEN 이 되면 배치를 FAILED 로 중단하고 나중에 재시작"이 보통 맞습니다. 상대가 죽었을 때 계속 두드리는 것보다 체크포인트를 남기고 멈추는 것이 낫습니다. 구현은 Resilience4j 같은 라이브러리가 있지만, 원리는 "연속 실패 카운터 + 상태 + 타이머"뿐입니다.

2.8 최종 리포트 — 배치가 남겨야 할 숫자

항목 의미 이상 징후
총 건수 읽은 건수 어제보다 크게 다르면 입력 문제
성공 쓰기까지 완료 -
스킵 데드 레터 건수 비율 급증 = 상류 변경
재시도 횟수 일시 오류 총량 급증 = 외부 시스템/네트워크 불안정
재시도 소진 끝내 실패 0 이 아니면 확인
소요 시간 / 처리 속도 시간 창 관리 추세 상승 = 용량 계획

총 건수 = 성공 + 스킵 이 맞아떨어져야 합니다. 안 맞으면 어딘가에서 건이 조용히 사라진 것입니다.

3. 코드 예제

java-src/batch/05_skip_retry/ 에서 javac *.java && java Main 100000.

예제 1: BackoffPolicy — 고정 / 지수 / 지터

java
@FunctionalInterface
public interface BackoffPolicy {
    long delayMillis(int attempt);                                   // attempt 는 1부터

    static BackoffPolicy none()             { return attempt -> 0; }
    static BackoffPolicy fixed(long millis) { return attempt -> millis; }

    static BackoffPolicy exponential(long initialMillis, double multiplier, long maxMillis) {
        return attempt -> (long) Math.min(initialMillis * Math.pow(multiplier, attempt - 1), maxMillis);
    }

    static BackoffPolicy exponentialWithJitter(long initialMillis, double multiplier, long maxMillis) {
        BackoffPolicy base = exponential(initialMillis, multiplier, maxMillis);
        return attempt -> {
            long d = base.delayMillis(attempt);
            return d == 0 ? 0 : ThreadLocalRandom.current().nextLong(d / 2, d + 1);   // 50%~100%
        };
    }
}
// BackoffPolicy p = BackoffPolicy.exponential(100, 2, 5000);
// for (int a = 1; a <= 7; a++) System.out.print(p.delayMillis(a) + " ");
// 출력: 100 200 400 800 1600 3200 5000     ← 상한 5000 에서 멈춤
// exponentialWithJitter(100, 2, 5000):  73 151 322 512 1043 2890 4012  (매번 다름)

예제 2: RetryTemplate — 재시도 가능 예외만, 횟수 제한, 리스너

java
public class RetryTemplate {
    public static class RetryExhaustedException extends Exception {
        public RetryExhaustedException(String msg, Throwable cause) { super(msg, cause); }
    }
    @FunctionalInterface
    public interface RetryListener { void onRetry(int attempt, long delayMillis, Exception cause); }

    private final int maxAttempts;
    private final BackoffPolicy backoff;
    private final Set<Class<? extends Exception>> retryable;          // 화이트리스트
    private final RetryListener listener;
    private final AtomicLong totalRetries = new AtomicLong();
    private final AtomicLong exhausted = new AtomicLong();

    public RetryTemplate(int maxAttempts, BackoffPolicy backoff,
                         Set<Class<? extends Exception>> retryable, RetryListener listener) {
        this.maxAttempts = maxAttempts; this.backoff = backoff; this.retryable = retryable;
        this.listener = listener == null ? (a, d, e) -> {} : listener;
    }

    public boolean isRetryable(Exception e) {
        for (Class<? extends Exception> c : retryable) if (c.isInstance(e)) return true;
        return false;
    }

    public <T> T execute(Callable<T> action) throws Exception {
        int attempt = 1;
        while (true) {
            try {
                return action.call();
            } catch (Exception e) {
                if (!isRetryable(e)) throw e;                              // 영구 오류: 즉시 던짐
                if (attempt >= maxAttempts) {
                    exhausted.incrementAndGet();
                    throw new RetryExhaustedException("재시도 " + maxAttempts + "회 모두 실패: " + e.getMessage(), e);
                }
                long delay = backoff.delayMillis(attempt);
                listener.onRetry(attempt, delay, e);
                totalRetries.incrementAndGet();
                if (delay > 0) Thread.sleep(delay);
                attempt++;
            }
        }
    }
    public long totalRetries() { return totalRetries.get(); }
    public long exhaustedCount() { return exhausted.get(); }
}

// 사용: 30% 확률로 타임아웃 나는 API 를 20번 호출
FlakyApiClient api = new FlakyApiClient(1, 0.30, 0);
RetryTemplate retry = new RetryTemplate(4, BackoffPolicy.exponentialWithJitter(10, 2.0, 200),
        Set.of(FlakyApiClient.TransientApiException.class),
        (attempt, delay, cause) -> System.out.printf("    retry #%d after %dms: %s%n", attempt, delay, cause.getMessage()));
for (long id = 1; id <= 20; id++) {
    final long fid = id;
    try { retry.execute(() -> api.send(fid)); ok++; }
    catch (RetryTemplate.RetryExhaustedException e) { failed++; }
}
// 출력:
//     retry #1 after 7ms: 504 Gateway Timeout: id=2
//     retry #1 after 9ms: 504 Gateway Timeout: id=5
//     retry #2 after 14ms: 504 Gateway Timeout: id=5
//     ...
//   20건 중 성공 20, 포기 0 / API 호출 28회, 재시도 8회

예제 3: SkipPolicy — 스킵 가능 예외 판별 + 한도

java
public class SkipPolicy {
    public static class SkipLimitExceededException extends RuntimeException {
        public SkipLimitExceededException(String msg, Throwable cause) { super(msg, cause); }
    }
    private final int skipLimit;
    private final Set<Class<? extends Throwable>> skippable;
    private final AtomicLong skipCount = new AtomicLong();

    public SkipPolicy(int skipLimit, Set<Class<? extends Throwable>> skippable) {
        this.skipLimit = skipLimit; this.skippable = skippable;
    }

    public boolean isSkippable(Throwable t) {
        // 재시도 소진은 원인(cause)으로 판별: Transient 를 skippable 에 넣으면 "재시도 다 해도 안 되면 스킵"
        Throwable target = t instanceof RetryTemplate.RetryExhaustedException && t.getCause() != null ? t.getCause() : t;
        for (Class<? extends Throwable> c : skippable) if (c.isInstance(target) || c.isInstance(t)) return true;
        return false;
    }

    /** 스킵 가능하면 카운트 후 true, 한도 초과면 예외, 스킵 불가면 false */
    public boolean shouldSkip(Throwable t) {
        if (!isSkippable(t)) return false;
        long n = skipCount.incrementAndGet();
        if (n > skipLimit) throw new SkipLimitExceededException("스킵 한도 " + skipLimit + " 초과 (" + n + "번째 스킵)", t);
        return true;
    }
    public long skipCount() { return skipCount.get(); }
}

// 사용: 잘못된 CSV 행 스킵 → 데드 레터
SkipPolicy skipPolicy = new SkipPolicy(rows / 50, Set.of(IllegalArgumentException.class));   // NumberFormatException 포함
try (BufferedReader r = Files.newBufferedReader(orders, UTF_8);
     BatchReport report = new BatchReport("csvParseJob", Path.of("data/orders.error.csv"))) {
    r.readLine();
    String line; long lineNo = 1;
    while ((line = r.readLine()) != null) {
        lineNo++; report.read();
        try { Order.parse(line); parsedOk++; }
        catch (RuntimeException e) {
            if (!skipPolicy.shouldSkip(e)) throw e;                     // 스킵 불가 → 중단
            report.skip("line " + lineNo, e, line);                     // 데드 레터
        }
    }
    report.success(parsedOk);
    report.print(0);
}
// 출력:
//   ┌─ csvParseJob 리포트 ─────────────────
//   │ 총 건수   : 100,000
//   │ 성공      : 99,012
//   │ 스킵      : 988  (-> data\orders.error.csv)
//   │ 재시도    : 0회
//   │ 소요 시간 : 142 ms  (704,225 items/s)
//   └────────────────────────────────────
//   데드 레터 앞 3줄:
//     lineOrId,reason,rawData
//     line 137,NumberFormatException: For input string: "136abc",136;cust-412;136abc
//     line 251,IllegalArgumentException: 필드 수 2 (3 필요),250;cust-87

// skipLimit=5 로 다시 실행하면:
//   배치 FAILED: 스킵 한도 5 초과 (6번째 스킵) / 원인: For input string: "612abc"

예제 4: BatchReport — 통계와 데드 레터 파일

java
public class BatchReport implements AutoCloseable {
    private final String jobName;
    private final long startMillis = System.currentTimeMillis();
    private final AtomicLong total = new AtomicLong(), success = new AtomicLong(), skipped = new AtomicLong();
    private final BufferedWriter deadLetter;
    private final Path deadLetterFile;

    public BatchReport(String jobName, Path deadLetterFile) throws IOException {
        this.jobName = jobName; this.deadLetterFile = deadLetterFile;
        Files.createDirectories(deadLetterFile.getParent());
        this.deadLetter = Files.newBufferedWriter(deadLetterFile, StandardCharsets.UTF_8);
        deadLetter.write("lineOrId,reason,rawData"); deadLetter.newLine();
    }

    public void read() { total.incrementAndGet(); }
    public void read(long n) { total.addAndGet(n); }
    public void success(long n) { success.addAndGet(n); }

    public synchronized void skip(String idOrLine, Throwable reason, String raw) {   // 사유 + 원본
        skipped.incrementAndGet();
        try {
            deadLetter.write(idOrLine + "," + reason.getClass().getSimpleName() + ": "
                    + String.valueOf(reason.getMessage()).replace(',', ';') + "," + raw.replace(',', ';'));
            deadLetter.newLine();
        } catch (IOException e) { throw new IllegalStateException("데드 레터 기록 실패", e); }
    }

    public void print(long retries) {
        long elapsed = System.currentTimeMillis() - startMillis;
        System.out.println("  ┌─ " + jobName + " 리포트 ─────────────────");
        System.out.printf ("  │ 총 건수   : %,d%n", total.get());
        System.out.printf ("  │ 성공      : %,d%n", success.get());
        System.out.printf ("  │ 스킵      : %,d  (-> %s)%n", skipped.get(), deadLetterFile);
        System.out.printf ("  │ 재시도    : %,d회%n", retries);
        System.out.printf ("  │ 소요 시간 : %,d ms  (%,d items/s)%n", elapsed, elapsed == 0 ? total.get() : total.get() * 1000 / elapsed);
        System.out.println("  └────────────────────────────────────");
    }
    @Override public void close() throws IOException { deadLetter.close(); }
}

데드 레터 기록이 실패하면(디스크 풀) 예외를 던져 배치를 중단시킵니다. "스킵했는데 기록은 못 했다"는 유실이기 때문입니다.

예제 5: 통합 — 청크 + 재시도 + 스킵 + 리포트

java
FlakyApiClient api3 = new FlakyApiClient(2, 0.10, 997);              // 10% 일시 오류, id 997 배수는 영구 오류
RetryTemplate retry3 = new RetryTemplate(3, BackoffPolicy.exponential(1, 2.0, 4),
        Set.of(FlakyApiClient.TransientApiException.class), null);
SkipPolicy skip3 = new SkipPolicy(1_000, Set.of(
        IllegalArgumentException.class,                                  // 파싱 오류
        FlakyApiClient.PermanentApiException.class,                      // 영구 API 오류
        FlakyApiClient.TransientApiException.class));                    // 재시도 소진(cause) 도 스킵

try (BufferedReader r = Files.newBufferedReader(orders, UTF_8);
     BatchReport report = new BatchReport("sendOrdersJob", Path.of("data/orders.deadletter.csv"))) {
    r.readLine();
    List<String> chunk = new ArrayList<>(200);
    long readLines = 0; int chunkNo = 0;
    while (true) {
        chunk.clear();
        String line;
        while (chunk.size() < 200 && readLines < apiRows && (line = r.readLine()) != null) {
            chunk.add(line); readLines++;
        }
        if (chunk.isEmpty()) break;
        chunkNo++;
        report.read(chunk.size());

        List<String> sent = new ArrayList<>(chunk.size());               // 이 청크에서 성공한 것만
        for (String raw : chunk) {
            try {
                Order o = Order.parse(raw);                              // 영구 오류 가능 → 스킵
                String res = retry3.execute(() -> api3.send(o.id()));    // 일시 오류 → 재시도, 소진 → 스킵
                sent.add(res);
            } catch (Exception e) {
                if (!skip3.shouldSkip(e)) throw e;                      // 치명적 → 배치 중단
                report.skip(raw.split(",")[0], e, raw);
            }
        }
        report.success(sent.size());                                    // 커밋 포인트: 실패 건 제외하고 커밋
        if (chunkNo % 5 == 0)
            System.out.printf("    chunk#%d committed: %d/%d sent, skipped so far %d, retries so far %d%n",
                    chunkNo, sent.size(), chunk.size(), skip3.skipCount(), retry3.totalRetries());
    }
    report.print(retry3.totalRetries());
    System.out.printf("  API 호출 %,d회, 재시도 소진 %d건%n", api3.calls(), retry3.exhaustedCount());
}
// 출력 (앞 5,000건):
//     chunk#5 committed: 197/200 sent, skipped so far 12, retries so far 108
//     chunk#10 committed: 199/200 sent, skipped so far 21, retries so far 221
//     ...
//   ┌─ sendOrdersJob 리포트 ─────────────────
//   │ 총 건수   : 5,000
//   │ 성공      : 4,946
//   │ 스킵      : 54  (-> data\orders.deadletter.csv)
//   │ 재시도    : 551회
//   │ 소요 시간 : 1,830 ms  (2,732 items/s)
//   └────────────────────────────────────
//   API 호출 5,502회 (성공건 + 재시도), 재시도 소진 5건
// 검산: 성공 4,946 + 스킵 54 = 5,000 ✓

스킵 54건의 내역은 데드 레터에 있습니다. 파싱 오류 ~25건(1%의 절반씩 두 종류), 영구 API 오류 5건(997, 1994, 2991, 3988, 4985), 재시도 소진 5건(0.1³ ≈ 0.1% × 5,000)... 이런 식으로 숫자가 설명되어야 정상입니다.

4. 응용 변형 예제

3절에서는 RetryTemplate + SkipPolicy + BatchReport 를 하나의 통합 루프에 넣었습니다. 여기서는 같은 부품을 다른 각도에서 다시 씁니다.

백오프 정책의 실제 대기 시간을 재고, "재시도할 것인가"를 예외 클래스가 아니라 Predicate 로 판단하고, Writer 수준 실패를 Spring Batch 식 scan 모드로 격리하고, 백오프 대기 중 인터럽트로 배치를 정상 중단시키고, 스킵 한도가 마지막 건에서 걸릴 때 데드 레터에 무엇이 남는지 확인합니다.

변형 1: 백오프 정책별 실제 대기 시간 측정 — none / fixed / exponential / jitter

2.2 절의 표는 "계획된" 대기 시간입니다. 실제로 Thread.sleep 이 얼마나 걸리는지, 정책마다 총 대기가 어떻게 달라지는지를 같은 결정적 실패 시퀀스(3번 실패 후 4번째 성공)로 측정합니다. 지터는 Random(42) 시드를 고정해 재현 가능하게 했습니다. 재시도 총 대기 시간을 예측할 수 있어야 "배치가 왜 30분 더 걸렸는지"를 설명할 수 있습니다.

java
import java.util.*;
import java.util.concurrent.Callable;

public class BackoffCompare {
    @FunctionalInterface interface BackoffPolicy { long delayMillis(int attempt); }

    static BackoffPolicy none() { return a -> 0; }
    static BackoffPolicy fixed(long ms) { return a -> ms; }
    static BackoffPolicy exponential(long init, double mul, long max) {
        return a -> (long) Math.min(init * Math.pow(mul, a - 1), max);
    }
    static BackoffPolicy exponentialWithJitter(long init, double mul, long max, Random rnd) {   // 시드 고정 → 재현 가능
        BackoffPolicy base = exponential(init, mul, max);
        return a -> { long d = base.delayMillis(a); return d == 0 ? 0 : d / 2 + rnd.nextLong(d / 2 + 1); };
    }

    static class Transient extends RuntimeException { Transient(int n) { super("timeout #" + n); } }

    /** 처음 failures 번은 실패, 그 다음 성공하는 결정적 액션 */
    static Callable<String> failingThenOk(int failures) {
        int[] calls = {0};
        return () -> { if (++calls[0] <= failures) throw new Transient(calls[0]); return "ok@" + calls[0]; };
    }

    record Run(String result, List<Long> delays, long elapsedMs) {}

    static Run retry(Callable<String> action, int maxAttempts, BackoffPolicy backoff) throws Exception {
        List<Long> delays = new ArrayList<>();
        long t0 = System.nanoTime();
        for (int attempt = 1; ; attempt++) {
            try { return new Run(action.call(), delays, (System.nanoTime() - t0) / 1_000_000); }
            catch (Transient e) {
                if (attempt >= maxAttempts) throw e;
                long d = backoff.delayMillis(attempt);
                delays.add(d);
                Thread.sleep(d);
            }
        }
    }

    public static void main(String[] args) throws Exception {
        Random rnd = new Random(42);
        Map<String, BackoffPolicy> policies = new LinkedHashMap<>();
        policies.put("none", none());
        policies.put("fixed(30)", fixed(30));
        policies.put("exponential(10,2,1000)", exponential(10, 2, 1000));
        policies.put("jitter(10,2,1000)", exponentialWithJitter(10, 2, 1000, rnd));

        System.out.printf("%-24s %-8s %-22s %s%n", "policy", "result", "delays(ms)", "measured");
        for (var e : policies.entrySet()) {
            Run r = retry(failingThenOk(3), 5, e.getValue());                       // 3번 실패 후 4번째 성공
            long best = r.elapsedMs();
            for (int rep = 0; rep < 2; rep++) best = Math.min(best, retry(failingThenOk(3), 5, e.getValue()).elapsedMs());   // 최소값
            long planned = r.delays().stream().mapToLong(Long::longValue).sum();
            System.out.printf("%-24s %-8s %-22s plan %3dms / real %3dms%n", e.getKey(), r.result(), r.delays(), planned, best);
        }
    }
}
// 출력 (real 은 환경·부하에 따라 다름. delays 는 시드 고정으로 항상 같음):
// policy                   result   delays(ms)             measured
// none                     ok@4     [0, 0, 0]              plan   0ms / real 467ms
// fixed(30)                ok@4     [30, 30, 30]           plan  90ms / real 106ms
// exponential(10,2,1000)   ok@4     [10, 20, 40]           plan  70ms / real 371ms
// jitter(10,2,1000)        ok@4     [6, 16, 28]            plan  50ms / real 144ms

none 이 계획 0ms 인데도 수백 ms 가 나온 것은 첫 실행의 클래스 로딩·JIT 과 측정 시점의 CPU 경합 때문입니다 — 실측은 항상 이런 노이즈를 포함하므로 여러 번 중 최소값을 보는 습관이 필요합니다. 지터는 같은 지수 정책보다 대기가 짧게(50%~100%) 흩어지고, 시드를 고정하면 테스트에서도 재현됩니다.

변형 2: 재시도 판별을 클래스 집합 대신 Predicate<Exception> 으로

예제 2 의 RetryTemplate 은 예외 클래스로 재시도 여부를 정합니다. 그런데 실무에서는 같은 ApiException 이라도 HTTP 429/503 은 일시적, 400/404 는 영구적이고, DB 데드락은 벤더 메시지 문자열로만 구분되는 경우가 많습니다. 판별 로직을 Predicate<Exception> 으로 받으면 상태 코드·메시지·원인 체인 어떤 기준이든 or() 로 합성해 넘길 수 있습니다.

java
import java.util.*;
import java.util.concurrent.Callable;
import java.util.function.Predicate;

public class PredicateRetry {
    static class ApiException extends RuntimeException {
        final int status;
        ApiException(int status, String msg) { super(status + " " + msg); this.status = status; }
    }
    static class RetryExhausted extends Exception { RetryExhausted(String m, Throwable c) { super(m, c); } }

    /** 클래스 집합 대신 Predicate 로 "재시도할 것인가" 를 판단하는 제네릭 재시도 함수 */
    static <T> T retry(Callable<T> action, int maxAttempts, Predicate<Exception> retryOn, List<String> log) throws Exception {
        for (int attempt = 1; ; attempt++) {
            try { return action.call(); }
            catch (Exception e) {
                if (!retryOn.test(e)) throw e;                                       // 재시도 대상 아님 → 즉시 전파
                if (attempt >= maxAttempts) throw new RetryExhausted("재시도 " + maxAttempts + "회 소진", e);
                log.add("retry#" + attempt + "(" + e.getMessage() + ")");
            }
        }
    }

    // HTTP 상태 코드 기준: 429/503/504 만 일시적. 같은 예외 클래스라도 상태로 갈린다
    static final Predicate<Exception> TRANSIENT_STATUS =
        e -> e instanceof ApiException a && Set.of(429, 503, 504).contains(a.status);
    // DB 데드락은 메시지로만 구분되는 경우가 많다 (SQLException 의 vendor 메시지)
    static final Predicate<Exception> DEADLOCK_MESSAGE =
        e -> e.getMessage() != null && e.getMessage().toLowerCase().contains("deadlock");

    /** 스크립트대로 응답하는 가짜 API: id 별 상태 코드 순서 */
    static Callable<String> scripted(String id, int... statuses) {
        int[] i = {0};
        return () -> {
            int s = statuses[Math.min(i[0]++, statuses.length - 1)];
            if (s == 200) return id + " sent";
            throw new ApiException(s, switch (s) { case 429 -> "Too Many Requests"; case 400 -> "Bad Request";
                                                    case 503 -> "Service Unavailable"; default -> "Error"; });
        };
    }

    public static void main(String[] args) {
        Map<String, Callable<String>> calls = new LinkedHashMap<>();
        calls.put("ORD-1", scripted("ORD-1", 503, 200));           // 일시 오류 1회 후 성공
        calls.put("ORD-2", scripted("ORD-2", 400));                // 영구 오류 → 재시도 없이 즉시
        calls.put("ORD-3", scripted("ORD-3", 429, 429, 429, 429)); // 계속 429 → 소진
        calls.put("ORD-4", scripted("ORD-4", 200));
        calls.put("ORD-5", () -> { throw new IllegalStateException("Deadlock found when trying to get lock"); });

        Predicate<Exception> retryOn = TRANSIENT_STATUS.or(DEADLOCK_MESSAGE);
        for (var e : calls.entrySet()) {
            List<String> log = new ArrayList<>();
            String outcome;
            try { outcome = retry(e.getValue(), 3, retryOn, log); }
            catch (RetryExhausted ex) { outcome = "EXHAUSTED (cause: " + ex.getCause().getMessage() + ")"; }
            catch (Exception ex) { outcome = "SKIP (" + ex.getMessage() + ")"; }
            System.out.printf("%-6s %-45s %s%n", e.getKey(), outcome, log);
        }
    }
}
// 출력:
// ORD-1  ORD-1 sent                                    [retry#1(503 Service Unavailable)]
// ORD-2  SKIP (400 Bad Request)                        []
// ORD-3  EXHAUSTED (cause: 429 Too Many Requests)      [retry#1(429 Too Many Requests), retry#2(429 Too Many Requests)]
// ORD-4  ORD-4 sent                                    []
// ORD-5  EXHAUSTED (cause: Deadlock found when trying to get lock) [retry#1(Deadlock found when trying to get lock), retry#2(Deadlock found when trying to get lock)]

ORD-2 는 같은 ApiException 인데도 400 이라 재시도 로그가 비어 있습니다 — 클래스 기준이었다면 3번 헛되이 재시도했을 것입니다. ORD-5 는 IllegalStateException 이지만 메시지의 "deadlock" 으로 재시도 대상이 되었습니다.

Predicate 는 클래스 화이트리스트를 포함하는 상위 개념이므로(c::isInstance 를 넘기면 동일), 기준이 하나뿐이라면 클래스 집합이, 둘 이상이면 Predicate 가 낫습니다.

변형 3: Writer 수준 실패와 scan 모드 — 청크 안의 범인 찾기

2.5 절 끝에서 언급한 Spring Batch 의 scan 모드입니다. DB 배치 INSERT 는 청크 안에 제약 위반 행이 하나만 있어도 통째로 거부하고 어느 행인지는 알려주지 않습니다. 그래서 청크를 롤백한 뒤 한 건씩 다시 써서 범인을 찾아 스킵하고 나머지는 건별 커밋합니다. 정상 청크는 writer 1회·커밋 1회로 빠르게, 문제 청크만 건별로 느리게 처리하는 것이 핵심입니다.

java
import java.util.*;

public class WriterScanMode {
    record Order(long id, long amount) {}

    static class Db {
        final Map<Long, Long> committed = new LinkedHashMap<>();
        Map<Long, Long> pending;
        int commits, rollbacks, writerCalls;
        void begin() { pending = new LinkedHashMap<>(); }
        void commit() { committed.putAll(pending); pending = null; commits++; }
        void rollback() { pending = null; rollbacks++; }

        /** 배치 INSERT: 청크 안에 잘못된 행이 하나라도 있으면 DB 가 통째로 거부. 어느 행인지는 알려주지 않는다 */
        void batchInsert(List<Order> orders) {
            writerCalls++;
            if (orders.stream().anyMatch(o -> o.amount() <= 0))
                throw new IllegalArgumentException("CHECK 제약 위반 (amount > 0), 배치 크기 " + orders.size());
            for (Order o : orders) pending.put(o.id(), o.amount());
        }
    }

    static void processChunk(Db db, List<Order> chunk, List<String> deadLetter) {
        db.begin();
        try {
            db.batchInsert(chunk);                                   // 1) 청크 통째로 시도
            db.commit();
            System.out.println("  청크 커밋 (" + chunk.size() + "건, writer 1회)");
            return;
        } catch (IllegalArgumentException e) {
            db.rollback();                                           // 2) 실패 → 청크 롤백
            System.out.println("  청크 쓰기 실패: " + e.getMessage() + " -> scan 모드 진입");
        }
        int ok = 0;
        for (Order o : chunk) {                                      // 3) 한 건씩 다시 써서 범인을 찾는다
            db.begin();
            try { db.batchInsert(List.of(o)); db.commit(); ok++; }
            catch (IllegalArgumentException e) {
                db.rollback();
                deadLetter.add(o.id() + "," + e.getMessage().split(",")[0] + "," + o);
                System.out.println("    id=" + o.id() + " 스킵 -> 데드 레터");
            }
        }
        System.out.println("  scan 완료: " + ok + "/" + chunk.size() + "건 커밋 (건별 커밋 " + ok + "회)");
    }

    public static void main(String[] args) {
        Db db = new Db();
        List<String> deadLetter = new ArrayList<>();
        List<Order> chunk1 = new ArrayList<>(), chunk2 = new ArrayList<>();
        for (long i = 1; i <= 10; i++) chunk1.add(new Order(i, i * 100));
        for (long i = 11; i <= 20; i++) chunk2.add(new Order(i, i == 17 ? 0 : i * 100));   // 17번이 독약

        processChunk(db, chunk1, deadLetter);
        processChunk(db, chunk2, deadLetter);
        System.out.println("committed=" + db.committed.size() + " commits=" + db.commits + " rollbacks=" + db.rollbacks
                + " writerCalls=" + db.writerCalls);
        System.out.println("deadLetter=" + deadLetter);
    }
}
// 출력:
//   청크 커밋 (10건, writer 1회)
//   청크 쓰기 실패: CHECK 제약 위반 (amount > 0), 배치 크기 10 -> scan 모드 진입
//     id=17 스킵 -> 데드 레터
//   scan 완료: 9/10건 커밋 (건별 커밋 9회)
// committed=19 commits=10 rollbacks=2 writerCalls=12
// deadLetter=[17,CHECK 제약 위반 (amount > 0),Order[id=17, amount=0]]

두 번째 청크는 writer 호출이 1(실패) + 10(scan) = 11회, 커밋 9회, 롤백 2회(청크 1회 + 범인 1회)입니다. scan 모드는 비싸므로 Writer 실패가 잦다면 Processor 단계에서 미리 검증해 스킵하는 것이 낫습니다 — scan 은 "Processor 가 잡지 못한 실패"를 위한 안전망입니다. 이 결과에도 SkipPolicy 의 한도 검사를 붙여야 함은 물론입니다.

변형 4: 백오프 대기 중 인터럽트 — 운영자의 중단 요청을 정상 종료로

재시도의 Thread.sleep 은 배치가 가장 오래 멈춰 있는 지점이고, 운영자가 "지금 멈춰"라고 하면 바로 그 대기 중일 확률이 높습니다. InterruptedException 을 삼키지 않고 전파하면 진행 중 청크를 롤백하고 마지막 커밋 위치를 남긴 채 깨끗하게 끝낼 수 있습니다. 이 변형은 워커 스레드를 띄우고 백오프 대기 중에 interrupt() 를 보내 그 흐름을 확인합니다.

java
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicLong;

public class InterruptDuringBackoff {
    static class Transient extends RuntimeException { Transient(String m) { super(m); } }

    /** id 5 부터는 항상 타임아웃 → 재시도가 백오프 대기에 들어간다 */
    static String send(long id) {
        if (id >= 5) throw new Transient("timeout id=" + id);
        return "sent " + id;
    }

    static <T> T retry(Callable<T> action, int maxAttempts, long backoffMs) throws Exception {
        for (int attempt = 1; ; attempt++) {
            try { return action.call(); }
            catch (Transient e) {
                if (attempt >= maxAttempts) throw e;
                Thread.sleep(backoffMs);            // 인터럽트되면 InterruptedException → 그대로 전파 (삼키지 않는다)
            }
        }
    }

    public static void main(String[] args) throws Exception {
        int chunkSize = 3;
        AtomicLong checkpoint = new AtomicLong();
        String[] exit = {"RUNNING"};

        Thread worker = new Thread(() -> {
            List<String> chunk = new ArrayList<>();
            long id = 1;
            try {
                while (id <= 100) {
                    final long cur = id;
                    chunk.add(retry(() -> send(cur), 5, 200));
                    if (chunk.size() == chunkSize) { checkpoint.set(id); chunk.clear(); }   // 청크 커밋
                    id++;
                }
                exit[0] = "COMPLETED";
            } catch (InterruptedException e) {
                chunk.clear();                                                                // 진행 중 청크 롤백
                Thread.currentThread().interrupt();                                           // 플래그 복원 (관례)
                exit[0] = "STOPPED at id=" + id + ", rolled back " + (id - 1 - checkpoint.get()) + " uncommitted item(s)";
            } catch (Exception e) {
                exit[0] = "FAILED " + e;
            }
        }, "batch-worker");

        worker.start();
        Thread.sleep(300);                                        // id 1~3 커밋, id 4 처리 후 id 5 의 백오프 대기 중
        System.out.println("운영자: 중단 요청 (interrupt)");
        worker.interrupt();
        worker.join(2_000);
        System.out.println("worker alive? " + worker.isAlive());
        System.out.println("exit = " + exit[0]);
        System.out.println("checkpoint = " + checkpoint.get() + " -> 재시작 시 id " + (checkpoint.get() + 1) + " 부터");
    }
}
// 출력:
// 운영자: 중단 요청 (interrupt)
// worker alive? false
// exit = STOPPED at id=5, rolled back 1 uncommitted item(s)
// checkpoint = 3 -> 재시작 시 id 4 부터

id 5 는 최대 5회 × 200ms = 1초를 기다릴 참이었지만 300ms 시점의 인터럽트로 즉시 깨어났고, 청크에 들어 있던 id 4 는 롤백되어 재시작이 4 부터 이어집니다.

예제 2 의 RetryTemplate.execute 가 throws Exception 인 이유가 이것입니다 — catch (InterruptedException e) {} 로 삼키면 배치는 인터럽트를 무시하고 남은 800ms 를 계속 기다립니다(02 레슨 멀티스레드의 관례).

shutdownNow(), Ctrl+C 훅, ExecutorService.close() 가 모두 이 경로로 들어옵니다.

변형 5: 스킵 한도가 마지막 건에서 걸릴 때 — 데드 레터에 무엇이 남는가

skipLimit 초과는 "N+1 번째 스킵 시도" 순간에 발생합니다. 그 건이 입력의 마지막 행이면 배치는 99% 를 끝내고 FAILED 가 되고, 한도를 넘긴 그 행은 데드 레터에 기록되지 않습니다(shouldSkip 이 기록 전에 던지므로). 같은 입력(잘못된 행 3, 7, 10)을 한도 3 과 2 로 돌려 리포트와 데드 레터 파일 내용을 대조합니다.

java
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;

public class SkipLimitEdge {
    static class SkipLimitExceeded extends RuntimeException {
        SkipLimitExceeded(String m, Throwable c) { super(m, c); }
    }
    static class SkipPolicy {
        final int limit; int count;
        SkipPolicy(int limit) { this.limit = limit; }
        boolean shouldSkip(Throwable t) {
            if (!(t instanceof IllegalArgumentException)) return false;
            if (++count > limit) throw new SkipLimitExceeded("스킵 한도 " + limit + " 초과 (" + count + "번째 스킵)", t);
            return true;
        }
    }

    record Result(String status, long total, long ok, long skipped, List<String> deadLetter) {}

    static Result run(Path input, Path deadLetterFile, int skipLimit) throws IOException {
        SkipPolicy policy = new SkipPolicy(skipLimit);
        long total = 0, ok = 0;
        String status = "COMPLETED";
        try (BufferedReader r = Files.newBufferedReader(input, StandardCharsets.UTF_8);
             BufferedWriter dl = Files.newBufferedWriter(deadLetterFile, StandardCharsets.UTF_8)) {
            dl.write("line,reason,raw"); dl.newLine();
            String line; long lineNo = 0;
            while ((line = r.readLine()) != null) {
                lineNo++; total++;
                try { Long.parseLong(line.split(",")[1]); ok++; }
                catch (RuntimeException e) {
                    if (!policy.shouldSkip(e)) throw e;                 // 한도 초과 → SkipLimitExceeded 전파
                    dl.write(lineNo + "," + e.getMessage().replace(',', ';') + "," + line); dl.newLine();
                }
            }
        } catch (SkipLimitExceeded e) {
            status = "FAILED: " + e.getMessage();
        }
        List<String> dead = Files.readAllLines(deadLetterFile, StandardCharsets.UTF_8);
        return new Result(status, total, ok, policy.count > skipLimit ? skipLimit : policy.count, dead.subList(1, dead.size()));
    }

    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("skipedge");
        Path input = dir.resolve("orders.csv");
        List<String> lines = new ArrayList<>();
        for (int i = 1; i <= 10; i++) lines.add("ORD-" + i + "," + (i == 3 || i == 7 || i == 10 ? i + "abc" : i * 100));
        Files.write(input, lines, StandardCharsets.UTF_8);       // 잘못된 행: 3, 7, 10(마지막)

        for (int limit : new int[]{3, 2}) {
            Result r = run(input, dir.resolve("dead-" + limit + ".csv"), limit);
            System.out.println("skipLimit=" + limit + " -> " + r.status());
            System.out.println("  총 " + r.total() + " = 성공 " + r.ok() + " + 스킵 " + r.skipped()
                    + (r.total() == r.ok() + r.skipped() ? "  (검산 OK)" : "  (불일치: 마지막 건은 기록 전에 중단됨)"));
            r.deadLetter().forEach(l -> System.out.println("  deadletter: " + l));
        }
    }
}
// 출력:
// skipLimit=3 -> COMPLETED
//   총 10 = 성공 7 + 스킵 3  (검산 OK)
//   deadletter: 3,For input string: "3abc",ORD-3,3abc
//   deadletter: 7,For input string: "7abc",ORD-7,7abc
//   deadletter: 10,For input string: "10abc",ORD-10,10abc
// skipLimit=2 -> FAILED: 스킵 한도 2 초과 (3번째 스킵)
//   총 10 = 성공 7 + 스킵 2  (불일치: 마지막 건은 기록 전에 중단됨)
//   deadletter: 3,For input string: "3abc",ORD-3,3abc
//   deadletter: 7,For input string: "7abc",ORD-7,7abc

한도 2 에서는 총 = 성공 + 스킵 검산이 깨집니다. 한도를 넘긴 10번 행이 데드 레터에 없기 때문인데, 그 행의 정보는 SkipLimitExceeded 의 cause 와 메시지에만 있습니다.

실무에서는 FAILED 로그에 이 원인을 반드시 남겨야 하고(실수 6), 리포트의 검산이 안 맞는 것 자체가 "한도로 중단됐다"는 신호로 읽혀야 합니다. 그리고 한도 초과가 마지막 행에서 났다면 성공한 7건은 이미 커밋된 상태이므로, 재실행은 04 레슨의 체크포인트·멱등성 위에서 이루어져야 합니다.

5. 자주 하는 실수 (Tip)

❌ 실수 1: 모든 예외를 재시도

java
new RetryTemplate(5, backoff, Set.of(Exception.class), null);   // 전부 재시도

NumberFormatException 을 5번 재시도하며 백오프까지 기다립니다. 100만 건 중 1만 건이 형식 오류면 5만 번의 헛된 재시도와 수십 분의 대기. 더 나쁜 것은 OutOfMemoryError... 는 Exception 이 아니라 그나마 다행이지만, DB 접속 불가(SQLException)를 건마다 5번씩 재시도하면 배치가 몇 시간 동안 "실행 중"으로 보입니다.

✅ 재시도는 일시적 오류 타입만 화이트리스트로. 나머지는 즉시 던져서 스킵 정책이 판단하게 합니다.

java
Set.of(SocketTimeoutException.class, SQLTransientException.class, TransientApiException.class)

❌ 실수 2: 스킵 한도 없이 스킵

java
catch (Exception e) { log.warn("skip", e); continue; }   // 한도 없음, 타입 구분 없음

입력 파일 인코딩이 바뀌어 전 행이 파싱 실패해도 배치는 "100만 건 스킵, 정상 종료"합니다. 아침에 아무도 이상을 모릅니다. 하류 시스템은 빈 결과를 받습니다.

✅ 스킵 가능 예외 화이트리스트 + skipLimit. 한도 초과 시 FAILED. 한도는 "정상 데이터의 오류율 × 여유"(예: 평소 0.5% → 한도 2%).

❌ 실수 3: 스킵만 하고 기록하지 않음

java
catch (IllegalArgumentException e) { skipCount++; }   // 어떤 건이 왜 스킵됐는지 없음

"스킵 988건"이라는 숫자만 남습니다. 어느 행이, 왜 스킵됐는지 모르니 수정도 재처리도 불가능합니다. 이것은 조용한 데이터 유실입니다.

✅ 데드 레터에 식별자 + 사유 + 원본 행을 기록합니다. 데드 레터 기록 실패는 배치 실패로 취급합니다.

❌ 실수 4: 지터 없는 지수 백오프로 워커 100개 운용

java
BackoffPolicy.exponential(100, 2, 5000);   // 모든 워커가 같은 시각에 재시도

외부 API 가 잠깐 흔들리면 워커 100개가 정확히 100ms, 200ms, 400ms 후에 동시에 재시도해 API 를 다시 쓰러뜨립니다.

✅ exponentialWithJitter. 워커가 하나뿐이라도 지터는 손해가 없습니다.

❌ 실수 5: 멱등하지 않은 호출을 재시도

java
retry.execute(() -> paymentApi.charge(order));   // 타임아웃 = 응답 유실일 수 있음 → 이중 결제

✅ 멱등 키를 붙이거나(charge(order, key)), 멱등 키를 지원하지 않는 API 는 재시도 대신 스킵 + 수동 확인 목록으로.

❌ 실수 6: 재시도 소진을 스킵과 구분하지 않고 삼킴

java
catch (RetryExhaustedException e) { /* 조용히 */ }

재시도 소진은 "외부 시스템이 불안정하다"는 신호입니다. 소진 건수가 리포트에 없으면 외부 장애를 데이터 오류로 오인합니다.

✅ 소진은 스킵으로 처리하되 원인(cause)을 데드 레터에 남기고, 소진 건수를 리포트에 별도 표기합니다. 소진이 연속으로 N건이면 서킷을 열어 배치를 중단합니다.

6. 연습 문제

문제 1

RetryTemplate 을 사용하지 않고, FlakyApiClient (일시 오류 50%) 에 대해 재시도 없이 1,000건을 호출했을 때의 성공률과, RetryTemplate(maxAttempts=3, none 백오프) 로 호출했을 때의 성공률을 비교 출력하세요. 이론적으로 3회 시도 시 성공률이 얼마여야 하는지 주석으로 계산하세요.

정답 보기
java
FlakyApiClient noRetryApi = new FlakyApiClient(10, 0.50, 0);
int ok1 = 0;
for (long id = 1; id <= 1000; id++) {
    try { noRetryApi.send(id); ok1++; } catch (Exception ignored) {}
}

FlakyApiClient retryApi = new FlakyApiClient(10, 0.50, 0);
RetryTemplate retry = new RetryTemplate(3, BackoffPolicy.none(),
        Set.of(FlakyApiClient.TransientApiException.class), null);
int ok2 = 0;
for (long id = 1; id <= 1000; id++) {
    final long fid = id;
    try { retry.execute(() -> retryApi.send(fid)); ok2++; } catch (Exception ignored) {}
}
System.out.printf("재시도 없음: %.1f%%  /  3회 시도: %.1f%% (호출 %d회, 재시도 %d회)%n",
        ok1 / 10.0, ok2 / 10.0, retryApi.calls(), retry.totalRetries());
// 이론: 1회 성공률 50%. 3회 모두 실패할 확률 = 0.5^3 = 12.5% → 성공률 87.5%
// 출력: 재시도 없음: 49.8%  /  3회 시도: 87.9% (호출 1749회, 재시도 749회)

문제 2

간단한 CircuitBreaker 를 구현하세요. 연속 실패가 threshold 에 도달하면 OPEN 상태가 되어 execute() 가 즉시 CircuitOpenException 을 던집니다.

openMillis 가 지나면 HALF_OPEN 으로 한 번 시도를 허용하고, 성공하면 CLOSED, 실패하면 다시 OPEN. 항상 실패하는 API 에 100번 호출해 실제 API 호출 횟수가 threshold 근처에서 멈추는지 확인하세요.

정답 보기
java
class CircuitBreaker {
    enum State { CLOSED, OPEN, HALF_OPEN }
    static class CircuitOpenException extends RuntimeException {
        CircuitOpenException() { super("circuit OPEN"); }
    }
    private final int threshold;
    private final long openMillis;
    private State state = State.CLOSED;
    private int consecutiveFailures;
    private long openedAt;

    CircuitBreaker(int threshold, long openMillis) { this.threshold = threshold; this.openMillis = openMillis; }

    synchronized <T> T execute(Callable<T> action) throws Exception {
        if (state == State.OPEN) {
            if (System.currentTimeMillis() - openedAt < openMillis) throw new CircuitOpenException();
            state = State.HALF_OPEN;                              // 시험 호출 1건 허용
        }
        try {
            T result = action.call();
            consecutiveFailures = 0;
            state = State.CLOSED;
            return result;
        } catch (Exception e) {
            consecutiveFailures++;
            if (state == State.HALF_OPEN || consecutiveFailures >= threshold) {
                state = State.OPEN;
                openedAt = System.currentTimeMillis();
            }
            throw e;
        }
    }
    State state() { return state; }
}

// 테스트: 항상 실패하는 API (transientFailureRate = 1.0)
FlakyApiClient dead = new FlakyApiClient(1, 1.0, 0);
CircuitBreaker cb = new CircuitBreaker(5, 10_000);
int open = 0, failed = 0;
for (long id = 1; id <= 100; id++) {
    final long fid = id;
    try { cb.execute(() -> dead.send(fid)); }
    catch (CircuitBreaker.CircuitOpenException e) { open++; }
    catch (Exception e) { failed++; }
}
System.out.printf("실제 API 호출 %d회, 실패 %d, 회로 OPEN 으로 즉시 거부 %d, 상태 %s%n",
        dead.calls(), failed, open, cb.state());
// 출력: 실제 API 호출 5회, 실패 5, 회로 OPEN 으로 즉시 거부 95, 상태 OPEN
// 100번 × 재시도 3회 = 300번 두드릴 것을 5번으로 줄였다. 배치는 이 시점에 FAILED 로 중단하는 것이 맞다.

문제 3

예제 5 의 통합 루프에서, 청크 안의 스킵 건수가 청크 크기의 50% 를 넘으면 그 청크를 커밋하지 않고 ChunkSkipRateExceededException 으로 배치를 중단하도록 수정하세요(전체 skipLimit 와 별개의 안전장치).

그리고 FlakyApiClient 의 permanentFailEvery 를 2 로 설정해 실제로 중단되는지 확인하세요. 왜 이런 청크 단위 안전장치가 전체 한도와 별개로 필요한지 주석으로 설명하세요.

정답 보기
java
static class ChunkSkipRateExceededException extends RuntimeException {
    ChunkSkipRateExceededException(int chunkNo, int skipped, int size) {
        super(String.format("청크 %d: %d/%d 스킵 (50%% 초과) -> 입력 구간 이상", chunkNo, skipped, size));
    }
}

// 청크 루프 안
List<String> sent = new ArrayList<>(chunk.size());
int skippedInChunk = 0;
for (String raw : chunk) {
    try {
        Order o = Order.parse(raw);
        sent.add(retry3.execute(() -> api3.send(o.id())));
    } catch (Exception e) {
        if (!skip3.shouldSkip(e)) throw e;
        report.skip(raw.split(",")[0], e, raw);
        skippedInChunk++;
    }
}
if (skippedInChunk * 2 > chunk.size()) {
    throw new ChunkSkipRateExceededException(chunkNo, skippedInChunk, chunk.size());   // 커밋하지 않음
}
report.success(sent.size());

// 왜 별개로 필요한가:
// 전체 skipLimit(1,000) 은 "배치 전체에서 1,000건까지 허용" 이다. 청크 200건 중 190건이 실패해도
// 누적이 1,000 미만이면 통과한다. 그런데 한 청크의 95% 가 실패한다는 것은 "그 구간의 입력이 통째로
// 깨졌다" 는 신호이며, 계속 진행하면 이후 청크도 같은 비율로 실패해 한도에 도달하기 전에
// 수천 건이 데드 레터로 빠진다. 국소적 이상은 국소적 한도로 빨리 잡는다.

// permanentFailEvery = 2 로 실행 (id 짝수는 전부 영구 오류):
// 출력: Exception in thread "main" ChunkSkipRateExceededException: 청크 1: 101/200 스킵 (50% 초과) -> 입력 구간 이상

7. 정리

  • 실패는 일시적(재시도) / 영구적(스킵) / 치명적(중단) 세 가지이고, 분류는 예외 타입 화이트리스트로 표현한다. 이 분류가 배치 신뢰성의 절반이다.
  • 재시도는 횟수 제한 + 지수 백오프 + 지터(thundering herd 방지). 재시도하는 호출은 반드시 멱등해야 한다(타임아웃 = 응답 유실일 수 있음).
  • 스킵은 화이트리스트 + skipLimit(한도 초과 시 FAILED) + 데드 레터(식별자·사유·원본). 기록 없는 스킵은 데이터 유실이다.
  • 청크 안에서 건별로 재시도 → 소진/영구 오류는 스킵 → 스킵 불가는 중단. 성공 건만 모아 커밋한다. 총 = 성공 + 스킵 이 맞아야 한다.
  • 외부 시스템이 죽어 있으면 서킷 브레이커로 두드리기를 멈추고 체크포인트를 남긴 채 FAILED 로 중단하는 것이 옳다. 최종 리포트(총/성공/스킵/재시도/소진/시간)를 매일 비교한다.

이것으로 배치 시리즈 다섯 레슨이 끝났습니다. 01 의 Reader-Processor-Writer 골격, 02 의 스트리밍 파일 I/O, 03 의 청크와 메모리, 04 의 청크 커밋·체크포인트·멱등성, 05 의 재시도·스킵·데드 레터를 합치면 Spring Batch 가 제공하는 핵심 기능의 원리를 모두 직접 구현한 셈입니다.

이제 Spring Batch 문서를 열면 chunk(100).faultTolerant().retry(TransientException.class).retryLimit(3).skip(ParseException.class).skipLimit(1000) 한 줄이 무엇을 하는지, 그리고 그 뒤에서 무엇이 일어나는지 설명할 수 있을 것입니다.

목차
  • 왜 배우는가
  • 핵심 원리
  • 코드 예제
  • 응용 변형 예제
  • 자주 하는 실수 (Tip)
  • 연습 문제
  • 정리
이전 레슨04 트랜잭션: 커밋과 롤백 시뮬레이션전체다음 레슨06 메서드 활용 패턴 (배치 유틸)
참고 영상 · 인터넷 연결 시 유튜브 검색이 열립니다자바 Skip과 Retry 로직 구현스킵 skip 재시도 retry