0Pricing
API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) · 강의

재시도 및 시간 제한 설정

일시적인 장애에 자동으로 재시도하도록 설정하고 장시간 실행되는 요청이 리소스를 차단하지 않도록 시간 제한을 지정해 보세요.

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

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

Build Resilient Gateways

In microservices, services can fail or become slow. To keep our applications running smoothly, we need to build resilience.

  • Resilience means your system can recover from failures and continue to function.
  • Spring Cloud Gateway provides tools to make your API Gateway more resilient.
  • Two key strategies for resilience are Timeouts and Retries.

Preventing Slow Responses with Timeouts

A timeout is a limit on how long an operation is allowed to take. If the operation doesn't complete within that time, it's automatically stopped.

  • Timeouts prevent requests from hanging indefinitely.
  • They free up resources (like network connections and threads) that would otherwise be tied up by a slow or unresponsive service.
  • In a gateway, timeouts ensure that a slow backend service doesn't slow down the entire gateway or other requests.

Configuring Read Timeouts

Spring Cloud Gateway allows you to configure specific timeouts for routes. The ReadTimeout filter is commonly used to limit how long the gateway waits for a response from the backend service after the connection is established.

  • This timeout is applied per route.
  • It helps prevent a single slow backend from impacting the gateway's overall performance.
  • The value is typically set in milliseconds.

Read Timeout Configuration Example

Here's how you can configure a ReadTimeout for a specific route in your application.yml. This example sets a 5-second read timeout for requests to /service-a/**:

Remember, this is part of your Spring Boot application's configuration.

spring:
  cloud:
    gateway:
      routes:
        - id: service_a_route
          uri: http://localhost:8081
          predicates:
            - Path=/service-a/**
          filters:
            - ReadTimeout=5000

Handling Transient Failures with Retries

Retries involve automatically re-sending a request that has failed, hoping it will succeed on a subsequent attempt.

  • They are ideal for transient failures: temporary issues like network glitches or a brief service restart.
  • Retries should be used cautiously, especially for non-idempotent operations (actions that produce different results if performed multiple times).
  • Spring Cloud Gateway can be configured to automatically retry requests to backend services.

The Retry GatewayFilter

Spring Cloud Gateway provides a Retry filter to enable automatic retries for failed requests. You can configure various aspects of the retry logic:

  • retries: The maximum number of retry attempts.
  • statuses: HTTP status codes that should trigger a retry (e.g., 503 for Service Unavailable).
  • methods: HTTP methods that can be retried (e.g., GET, PUT).

Retry Configuration Example

Let's configure a Retry filter. This example retries requests up to 3 times if the backend returns a 5XX error or a 404, specifically for GET requests to /service-b/**:

spring:
  cloud:
    gateway:
      routes:
        - id: service_b_route
          uri: http://localhost:8082
          predicates:
            - Path=/service-b/**
          filters:
            - name: Retry
              args:
                retries: 3
                statuses: 
                  - SERVER_ERROR
                  - NOT_FOUND
                methods:
                  - GET

Simple Retry Logic Demo

While Spring Cloud Gateway handles retries via configuration, the core concept involves looping until success or max attempts. Here's a basic Java program demonstrating a retry loop:

public class RetryDemo {
  private static int attempt = 0;

  public static boolean simulateBackendCall() {
    System.out.println("Attempt " + (++attempt));
    return attempt < 3; // Fails for first 2 attempts
  }

  public static void main(String[] args) {
    int maxRetries = 2;
    for (int i = 0; i <= maxRetries; i++) {
      if (!simulateBackendCall()) {
        System.out.println("Success!");
        return;
      }
      System.out.println("Failed. Retrying...");
      try { Thread.sleep(100); } catch (InterruptedException e) {}
    }
    System.out.println("Max retries reached. Operation failed.");
  }
}

Combining Timeouts & Retries

Timeouts and retries often work together:

  • A timeout can trigger a retry if the request doesn't complete within the specified time.
  • If a request times out, the gateway might then attempt a retry, hoping the next attempt will be faster or the service will respond.
  • It's crucial to configure these carefully to avoid endless loops or excessive delays. For example, a retry might happen *after* a read timeout, or a global timeout could encompass all retries.

Best Practices for Resilience

When implementing timeouts and retries, consider these best practices:

  • Idempotency: Only retry idempotent operations (e.g., GET, PUT) unless you have specific logic to handle non-idempotent ones (e.g., POST).
  • Exponential Backoff: Introduce increasing delays between retries to avoid overwhelming a struggling service.
  • Circuit Breakers: Combine with circuit breakers (covered in Lesson 10.1) to stop retrying services that are clearly down.
  • Monitoring: Monitor retry counts and timeouts to identify persistently problematic services.

Quick Check on Gateway Resilience

You're configuring a Spring Cloud Gateway route for a backend service that sometimes experiences brief network hiccups, resulting in a 503 Service Unavailable error. You want the gateway to automatically try the request again a few times before giving up. Which filter and configuration would best achieve this?

Recap: Timeouts & Retries

We've explored how Timeouts and Retries are fundamental for building resilient API Gateways with Spring Cloud Gateway.

  • Timeouts prevent requests from hanging, freeing up resources.
  • The ReadTimeout filter configures the wait time for backend responses.
  • Retries automatically re-send requests for transient failures.
  • The Retry filter allows fine-grained control over retry attempts, statuses, and HTTP methods.
  • Combining these with best practices helps create robust microservice architectures.

자주 묻는 질문

“재시도 및 시간 제한 설정” 강의는 무료인가요?

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

“재시도 및 시간 제한 설정”에서 뭘 배우나요?

일시적인 장애에 자동으로 재시도하도록 설정하고 장시간 실행되는 요청이 리소스를 차단하지 않도록 시간 제한을 지정해 보세요. 브라우저에서 직접 실행하는 실습 코드로 API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway)을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway)을(를) 시작하는 데 경험이 필요한가요?

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

“재시도 및 시간 제한 설정” 강의는 얼마나 걸리나요?

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

이 API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) 강의에서 코드를 작성하고 실행할 수 있나요?

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

이 강의의 모든 강의

  1. Resilience4j를 사용한 회로 차단기
  2. 재시도 및 시간 제한 설정
  3. 오류 처리 및 대체 처리
  4. 복원력을 위한 벌크헤드 및 속도 제한
← API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway)(으)로 돌아가기