PHpullh
학습 라이브러리/Kotlin/재시도 패턴 (Retry Pattern)

KOTLIN · 예외처리

재시도 패턴 (Retry Pattern)

일시적 실패에 대해 지수 백오프로 재시도하는 패턴입니다. 최대 횟수와 타임아웃을 설정합니다.

예외처리고급retryexponential-backoffresiliencetransient-error

핵심 설명

일시적 실패에 대해 지수 백오프로 재시도하는 패턴입니다. 최대 횟수와 타임아웃을 설정합니다.

Kotlin code

import kotlinx.coroutines.*

class RetryConfig(
    val maxRetries: Int = 3,
    val initialDelay: Long = 100,
    val maxDelay: Long = 5000,
    val factor: Double = 2.0
)

suspend fun <T> withRetry(
    config: RetryConfig = RetryConfig(),
    block: suspend (attempt: Int) -> T
): T {
    var currentDelay = config.initialDelay
    repeat(config.maxRetries) { attempt ->
        try {
            return block(attempt + 1)
        } catch (e: Exception) {
            println("시도 ${attempt + 1} 실패: ${e.message}")
            if (attempt == config.maxRetries - 1) throw e
            delay(currentDelay)
            currentDelay = (currentDelay * config.factor).toLong()
                .coerceAtMost(config.maxDelay)
        }
    }
    throw IllegalStateException("도달 불가")
}

var callCount = 0
suspend fun unreliableApi(): String {
    callCount++
    if (callCount < 3) throw RuntimeException("서버 오류 ($callCount)")
    return "성공!"
}

fun main() = runBlocking {
    val result = withRetry(RetryConfig(maxRetries = 5)) { attempt ->
        println("시도 $attempt...")
        unreliableApi()
    }
    println("결과: $result")
}

학습 팁

지수 백오프에 coerceAtMost로 최대 지연을 제한하면 무한히 긴 대기를 방지합니다.

주의할 점

모든 예외에 재시도하면 안 됩니다. 인증 오류(401)나 잘못된 요청(400) 같은 영구적 실패에 재시도는 무의미합니다.

자주 묻는 질문

재시도 패턴 (Retry Pattern)란 무엇인가요?

일시적 실패에 대해 지수 백오프로 재시도하는 패턴입니다. 최대 횟수와 타임아웃을 설정합니다.

재시도 패턴 (Retry Pattern) 학습 시 주의할 점은 무엇인가요?

모든 예외에 재시도하면 안 됩니다. 인증 오류(401)나 잘못된 요청(400) 같은 영구적 실패에 재시도는 무의미합니다.