0Pricing
Spring Boot 4 Complete Guide · 강의

호출률 제한, 재시도 및 시간 제한기

호출률 제한기, 재시도 및 시간 제한을 조합해 부하를 조절하고 연쇄적인 장애를 억제합니다.

호출률 제한, 재시도 및 시간 제한기은(는) CoddyKit의 무료 Spring Boot 4 Complete Guide 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Spring Boot 4 Complete Guide 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Spring Boot 4 Complete Guide 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Three Knobs for Shaping Load

Circuit breakers stop calling a dead dependency, but they are only one tool in the resilience toolbox. To shape inbound load and contain cascading failures you combine three more Resilience4j primitives:

  • RateLimiter — caps how many calls per time window are allowed to start. Excess callers wait or are rejected.
  • Retry — re-invokes a failed call a bounded number of times, ideally with backoff, to ride out transient errors.
  • TimeLimiter — caps how long a single call may run before it is cancelled, freeing the thread and bounding tail latency.

Used together they protect both you (don't overload your own service) and your downstream (don't hammer a struggling dependency).

Adding Resilience4j to Spring Boot 4

Spring Boot 4 integrates Resilience4j through the Spring Cloud Circuit Breaker / resilience4j-spring-boot3 starter, which exposes annotation-driven aspects for every primitive.

Add the starter and AOP support so the annotations are woven in:

  • resilience4j-spring-boot3 brings RateLimiter, Retry, TimeLimiter, CircuitBreaker, and Bulkhead aspects.
  • spring-boot-starter-aop is required — the annotations are implemented as AOP advice.
  • Metrics flow into Micrometer automatically when Actuator is present.
<dependencies>
  <dependency>
    <groupId>io.github.resilience4j</groupId>
    <artifactId>resilience4j-spring-boot3</artifactId>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
  </dependency>
</dependencies>

RateLimiter: Capping Calls Per Window

A RateLimiter divides time into refresh periods. Each period grants a fixed number of permits. A caller that finds no permit available waits up to timeoutDuration; if still none, it fails fast with RequestNotPermitted.

Configure instances in application.yml under resilience4j.ratelimiter:

  • limitForPeriod — permits granted each refresh period.
  • limitRefreshPeriod — how often the permit count resets.
  • timeoutDuration — how long a caller blocks waiting for a permit before being rejected.
resilience4j:
  ratelimiter:
    instances:
      pricingApi:
        limitForPeriod: 50
        limitRefreshPeriod: 1s
        timeoutDuration: 200ms
        registerHealthIndicator: true

Applying @RateLimiter

Annotate the method that calls the protected resource. The name must match the YAML instance. When the limit is exceeded and no permit frees up within timeoutDuration, Resilience4j throws RequestNotPermitted — route it to a fallback so clients get a graceful 429 instead of a stack trace.

Key decision: a RateLimiter throttles your outbound calls. It does not slow down inbound HTTP traffic by itself — pair it with a fallback that signals back-pressure.

@Service
public class PricingClient {

    private final RestClient restClient;

    public PricingClient(RestClient restClient) {
        this.restClient = restClient;
    }

    @RateLimiter(name = "pricingApi", fallbackMethod = "throttled")
    public Quote fetchQuote(String symbol) {
        return restClient.get()
                .uri("/quotes/{symbol}", symbol)
                .retrieve()
                .body(Quote.class);
    }

    private Quote throttled(String symbol, RequestNotPermitted ex) {
        throw new ResponseStatusException(HttpStatus.TOO_MANY_REQUESTS,
                "Pricing rate limit exceeded, retry shortly");
    }
}

Retry: Riding Out Transient Failures

A Retry re-invokes a failed call up to maxAttempts times. It is only correct for transient faults — connection resets, 503s, brief timeouts — and only safe on idempotent operations. Retrying a non-idempotent POST can double-charge a customer.

Use exponential backoff to avoid synchronized retry storms, and be explicit about which exceptions retry vs. which abort immediately:

  • retryExceptions — only these trigger a retry.
  • ignoreExceptions — these abort instantly (e.g. 4xx client errors).
  • enableExponentialBackoff with a multiplier spreads attempts out.
resilience4j:
  retry:
    instances:
      pricingApi:
        maxAttempts: 3
        waitDuration: 200ms
        enableExponentialBackoff: true
        exponentialBackoffMultiplier: 2
        retryExceptions:
          - java.io.IOException
          - org.springframework.web.client.HttpServerErrorException
        ignoreExceptions:
          - org.springframework.web.client.HttpClientErrorException

Exponential Backoff with Jitter, Conceptually

Exponential backoff multiplies the wait after each attempt: 200ms, 400ms, 800ms... But if thousands of clients fail at the same instant, they all back off in lock-step and re-converge — a retry storm. Adding jitter (randomized wait) de-synchronizes them.

This standalone program models the wait schedule so you can see the spread of backoff-with-jitter delays an online judge can run with no framework:

import java.util.concurrent.ThreadLocalRandom;

public class BackoffDemo {
    static long backoffWithJitter(int attempt, long baseMillis, double multiplier) {
        double exp = baseMillis * Math.pow(multiplier, attempt - 1);
        long jitter = ThreadLocalRandom.current().nextLong((long) (exp / 2) + 1);
        return (long) (exp / 2) + jitter; // half fixed, half random
    }

    public static void main(String[] args) {
        for (int attempt = 1; attempt <= 4; attempt++) {
            long wait = backoffWithJitter(attempt, 200, 2.0);
            System.out.println("Attempt " + attempt + " -> wait ~" + wait + "ms");
        }
    }
}

Applying @Retry

Stack @Retry on the same method. Order matters when annotations combine: Resilience4j applies aspects in the order Retry → CircuitBreaker → RateLimiter → TimeLimiter → Bulkhead (outermost to innermost), so a retry wraps the rate-limited call and each attempt re-acquires a permit.

The fallback receives the final exception after all attempts are exhausted:

@Service
public class PricingClient {

    @Retry(name = "pricingApi")
    @RateLimiter(name = "pricingApi", fallbackMethod = "throttled")
    public Quote fetchQuote(String symbol) {
        return restClient.get()
                .uri("/quotes/{symbol}", symbol)
                .retrieve()
                .body(Quote.class);
    }

    private Quote throttled(String symbol, Throwable ex) {
        // Returns a last-known-good or default after retries + limit exhausted
        return Quote.unavailable(symbol);
    }
}

TimeLimiter: Bounding Tail Latency

A TimeLimiter caps how long a single asynchronous call may run. It only works with futures — the method must return CompletableFuture (or another supported async type) so Resilience4j can cancel it when the deadline passes.

This is the antidote to slow dependencies: a retry handles failures, but a call that simply hangs for 30 seconds will exhaust your thread pool. The TimeLimiter converts a hang into a fast TimeoutException.

  • timeoutDuration — the per-call deadline.
  • cancelRunningFuture — interrupt the running task on timeout to free its thread.
resilience4j:
  timelimiter:
    instances:
      pricingApi:
        timeoutDuration: 2s
        cancelRunningFuture: true

Applying @TimeLimiter on an Async Method

@TimeLimiter requires the method to return a CompletableFuture. Without an async return type the aspect silently does nothing. Combine it with a CircuitBreaker so repeated timeouts eventually open the breaker and stop wasting effort.

Note the fallback also returns a CompletableFuture — its signature must match the protected method's return type:

@Service
public class PricingClient {

    @TimeLimiter(name = "pricingApi")
    @CircuitBreaker(name = "pricingApi", fallbackMethod = "timedOut")
    public CompletableFuture<Quote> fetchQuoteAsync(String symbol) {
        return CompletableFuture.supplyAsync(() ->
                restClient.get()
                        .uri("/quotes/{symbol}", symbol)
                        .retrieve()
                        .body(Quote.class));
    }

    private CompletableFuture<Quote> timedOut(String symbol, Throwable ex) {
        return CompletableFuture.completedFuture(Quote.unavailable(symbol));
    }
}

Ordering the Three Together Correctly

When you stack all three, the aspect order determines behavior. Resilience4j's documented default decoration order, from outer to inner, is:

Retry( CircuitBreaker( RateLimiter( TimeLimiter( Bulkhead( call ) ) ) ) )

  • Retry outermost so a retry re-runs the whole protected chain, re-checking the circuit breaker and re-acquiring a rate-limit permit each attempt.
  • TimeLimiter inner so each individual attempt has its own deadline — a retry of a timed-out call gets a fresh clock.
  • Putting Retry inside the RateLimiter would let one logical call consume several permits per attempt — usually wrong, and it can starve other callers.

With annotations you don't manually order them; Resilience4j enforces this order via aspect precedence.

Observing and Tuning via Actuator

You cannot tune what you cannot see. With Actuator on the classpath, every instance publishes Micrometer metrics and health indicators. Expose them and watch the key signals:

  • resilience4j_ratelimiter_available_permissions — if this sits at zero, you are throttling real traffic; raise the limit or scale out.
  • resilience4j_retry_calls tagged kind=successful_with_retry vs failed_with_retry — high failed-with-retry means retries aren't helping; the fault isn't transient.
  • resilience4j_timelimiter_calls tagged kind=timeout — rising timeouts signal a degrading dependency before the breaker even opens.
management:
  endpoints:
    web:
      exposure:
        include: health, metrics, ratelimiters, retries
  metrics:
    tags:
      application: tracing-service
  health:
    ratelimiters:
      enabled: true

Quick Check: Choosing the Right Primitive

A downstream pricing API occasionally hangs for 30+ seconds instead of returning an error, and these hangs are exhausting your service's request threads. Which Resilience4j primitive most directly addresses this specific failure mode?

Recap: Shaping Load and Containing Failure

You combined three complementary primitives to shape load and contain cascading failures:

  • RateLimiter caps calls per window, rejecting excess with RequestNotPermitted so you never overload yourself or a downstream.
  • Retry rides out transient faults on idempotent calls, using exponential backoff plus jitter to avoid retry storms.
  • TimeLimiter bounds tail latency on async (CompletableFuture) calls, turning hangs into fast timeouts that free threads.

Stack them via annotations; Resilience4j enforces the order Retry → CircuitBreaker → RateLimiter → TimeLimiter → Bulkhead so a retry re-runs the whole protected chain while each attempt keeps its own deadline. Always wire fallbacks for graceful degradation and watch Actuator/Micrometer metrics to tune the limits against real traffic.

자주 묻는 질문

“호출률 제한, 재시도 및 시간 제한기” 강의는 무료인가요?

네 — “호출률 제한, 재시도 및 시간 제한기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Spring Boot 4 Complete Guide 강의 전체를 잠금 해제할 수 있습니다. Spring Boot 4 Complete Guide 강의에는 총 4개의 강의가 포함되어 있습니다.

“호출률 제한, 재시도 및 시간 제한기”에서 뭘 배우나요?

호출률 제한기, 재시도 및 시간 제한을 조합해 부하를 조절하고 연쇄적인 장애를 억제합니다. 브라우저에서 직접 실행하는 실습 코드로 Spring Boot 4 Complete Guide을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Spring Boot 4 Complete Guide을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Spring Boot 4 Complete Guide은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“호출률 제한, 재시도 및 시간 제한기” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Spring Boot 4 Complete Guide 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Spring Boot 4 Complete Guide 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 컨텍스트 전파 및 스팬 계측
  2. 회로 차단기 및 격벽 격리
  3. 호출률 제한, 재시도 및 시간 제한기
  4. 로그, 메트릭 및 추적 상관관계 분석
← Spring Boot 4 Complete Guide(으)로 돌아가기