Microservices Communication Patterns (Saga, Circuit Breaker) · レッスン

再試行パターンの基礎

失敗した操作を自動的に再実行してシステムの堅牢性を高める、再試行パターンの基礎を学習します。

レッスン 2/412 ステップ

「再試行パターンの基礎」はCoddyKit上の無料Microservices Communication Patterns (Saga, Circuit Breaker)レッスンです。 これはレッスン2/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはMicroservices Communication Patterns (Saga, Circuit Breaker)学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Microservices Communication Patterns (Saga, Circuit Breaker)コースには全4レッスンが含まれています。

このレッスンの一部はまだ翻訳されておらず、英語で表示されています。

Facing Temporary Glitches?

Imagine you're trying to send a message, but your internet connection blips for a second. What do you do?

You probably try again! This simple human behavior is the core idea behind the Retry Pattern in software.

What is the Retry Pattern?

The Retry Pattern is a fundamental resilience technique. It involves automatically re-attempting an operation that has failed.

It's used when we expect the failure to be transient, meaning temporary and likely to resolve itself shortly, such as a brief network outage or a temporary database lock.

Why Use Retries?

In distributed systems, services often depend on each other. Failures can occur for many reasons:

  • Network issues: A brief disconnection or high latency.
  • Resource contention: A database or service is temporarily overloaded.
  • Service restarts: A dependent service is briefly unavailable during an update.

Retries help your application recover gracefully from these hiccups without crashing or requiring manual intervention.

The Basic Retry Loop

At its simplest, the retry pattern works like this:

  1. Attempt an operation.
  2. If it fails, check if it's a retriable error.
  3. If retriable, increment a counter and try again.
  4. Stop after a certain number of attempts or if it succeeds.

Let's see a basic example without any delays yet.

Code: Simple Retry Logic

This code simulates an operation that fails twice before succeeding. Notice how the while loop keeps trying until it works or runs out of attempts.

public class Main {
  public static void main(String[] args) {
    boolean success = false;
    int maxAttempts = 3;
    int currentAttempt = 0;

    while (!success && currentAttempt < maxAttempts) {
      currentAttempt++;
      System.out.println("Attempt " + currentAttempt + ": Trying to connect...");
      // Simulate failure for first two attempts
      if (currentAttempt < 3) {
        System.out.println("Connection failed!");
      } else {
        System.out.println("Connection successful!");
        success = true;
      }
    }

    if (!success) {
      System.out.println("Failed after " + maxAttempts + " attempts.");
    }
  }
}

Adding a Delay: Fixed Retry

Simply retrying immediately might overwhelm a struggling service or fail again if the issue needs time to resolve. That's why we add delays.

A Fixed Delay Retry waits the same amount of time between each failed attempt. This gives the system a chance to recover.

Code: Fixed Delay Retry

Here, we've added a 1-second delay (1000ms) using Thread.sleep() after each failed attempt. This is a common practice to give the system some breathing room.

public class Main {
  public static void main(String[] args) {
    boolean success = false;
    int maxAttempts = 3;
    int currentAttempt = 0;
    long delayMillis = 1000; // 1 second delay

    while (!success && currentAttempt < maxAttempts) {
      currentAttempt++;
      System.out.println("Attempt " + currentAttempt + ": Trying to connect...");
      // Simulate failure for first two attempts
      if (currentAttempt < 3) {
        System.out.println("Connection failed!");
        try {
          Thread.sleep(delayMillis); // Wait before retrying
          System.out.println("Waiting " + delayMillis + "ms...");
        } catch (InterruptedException e) {
          Thread.currentThread().interrupt();
        }
      } else {
        System.out.println("Connection successful!");
        success = true;
      }
    }

    if (!success) {
      System.out.println("Failed after " + maxAttempts + " attempts.");
    }
  }
}

Smarter Waits: Exponential Backoff

While fixed delays work, sometimes it's better to increase the wait time with each successive retry. This is called Exponential Backoff.

For example, you might wait 1s, then 2s, then 4s, then 8s. This reduces the load on a struggling service and gives it more time to recover.

When to Use the Retry Pattern

Retries are most effective for:

  • Transient network errors: Brief disconnections, timeouts.
  • Temporary resource unavailability: A database connection pool is momentarily exhausted.
  • Optimistic concurrency conflicts: When multiple users try to update the same record at once.
  • Brief service restarts: A microservice is being redeployed.

When NOT to Use Retries

Retries are not a silver bullet. Avoid using them for:

  • Non-transient errors: Errors caused by invalid input, authorization failures, or missing resources that won't resolve on their own.
  • Non-idempotent operations: If repeating an operation has unintended side effects (e.g., charging a customer twice). Idempotency means an operation can be performed multiple times without changing the result beyond the initial application.
  • Long-lasting failures: If a service is permanently down or has a major outage.

Test Your Knowledge!

Which scenario is generally a good candidate for applying the Retry Pattern?

Retry Pattern Summary

You've learned the fundamentals of the Retry Pattern!

  • It's for automatically re-attempting failed operations.
  • It's crucial for handling transient failures in distributed systems.
  • Basic implementation involves a loop with a maximum number of attempts.
  • Adding delays (fixed or exponential backoff) is key to giving systems time to recover.
  • Know when to use it (e.g., network issues) and when to avoid it (e.g., non-transient errors, non-idempotent operations).

Next, we'll explore other resilience patterns like fallbacks and timeouts!

無料で開始

AI チューターと学ぶ Microservices Communication Patterns (Saga, Circuit Breaker) — 無料

ブラウザでリアルコードを書いて実行し、24/7 の AI チューターから瞬時にサポートを受け、ウェブまたはアプリで続きから学習できます。

コース
12
レッスン
48

よくある質問

「再試行パターンの基礎」レッスンは無料ですか?

はい。「再試行パターンの基礎」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Microservices Communication Patterns (Saga, Circuit Breaker)コースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Microservices Communication Patterns (Saga, Circuit Breaker)コースには全4レッスンが含まれています。

「再試行パターンの基礎」で何を学びますか?

失敗した操作を自動的に再実行してシステムの堅牢性を高める、再試行パターンの基礎を学習します。 ブラウザで直接実行するハンズオンコードでMicroservices Communication Patterns (Saga, Circuit Breaker)を演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

Microservices Communication Patterns (Saga, Circuit Breaker)を始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのMicroservices Communication Patterns (Saga, Circuit Breaker)は初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン2/4です。

「再試行パターンの基礎」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このMicroservices Communication Patterns (Saga, Circuit Breaker)レッスンでコードを書いて実行できますか?

はい。すべてのMicroservices Communication Patterns (Saga, Circuit Breaker)レッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. レジリエンスが重要な理由
  2. 再試行パターンの基礎
  3. フォールバックとタイムアウトの実装
  4. バルクヘッドパターン
← Microservices Communication Patterns (Saga, Circuit Breaker)に戻る