処理が失敗したときにリトライするには
一時的な失敗で終わった処理を、待ち時間を倍にしながら最大回数までやり直すコードを各言語で示す。
使い切ったときは最後のエラーを呼び出し元へ返す形にする。
公開:
選んだ言語は、ほかのサンプルコードを開いたときも最初に表示する。
Python
import time
calls = 0
def fetch():
global calls
calls += 1
if calls < 3:
raise ConnectionError(f"一時的な失敗 {calls} 回目")
return "成功"
def retry(func, max_attempts=3, base_delay=0.1):
for attempt in range(1, max_attempts + 1):
try:
return func()
except ConnectionError as e:
print(f"{attempt} 回目の失敗: {e}") # -> 1 回目の失敗: 一時的な失敗 1 回目
if attempt == max_attempts:
raise # 最後の失敗は握りつぶさず、そのまま呼び出し元へ返す
time.sleep(base_delay * 2 ** (attempt - 1)) # 0.1 秒 → 0.2 秒と待ちを倍にする
print(retry(fetch)) # -> 成功for ループの中で try と except を使い、失敗したら待ってから同じ処理をやり直す。
最後の試行で失敗したときは raise で例外をそのまま呼び出し元へ返すので、失敗を握りつぶさずに済む。
JavaScript
let calls = 0;
async function fetchData() {
calls += 1;
if (calls < 3) throw new Error(`一時的な失敗 ${calls} 回目`);
return "成功";
}
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function retry(fn, maxAttempts = 3, baseDelay = 100) {
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
return await fn();
} catch (err) {
console.log(`${attempt} 回目の失敗: ${err.message}`); // -> 1 回目の失敗: 一時的な失敗 1 回目
if (attempt === maxAttempts) throw err; // 最後の失敗は呼び出し元へ返す
await sleep(baseDelay * 2 ** (attempt - 1)); // 100ms → 200ms と待ちを倍にする
}
}
}
console.log(await retry(fetchData)); // -> 成功async 関数の中でループと try と catch を組み合わせ、失敗したら setTimeout で待ってからやり直す。
最後の試行では throw err で呼び出し元へ返し、失敗を握りつぶさない。
TypeScript
let calls = 0;
async function fetchData(): Promise<string> {
calls += 1;
if (calls < 3) throw new Error(`一時的な失敗 ${calls} 回目`);
return "成功";
}
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
async function retry<T>(fn: () => Promise<T>, maxAttempts = 3, baseDelay = 100): Promise<T> {
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
return await fn();
} catch (err: unknown) {
const message = err instanceof Error ? err.message : String(err); // err は unknown なので絞り込む
console.log(`${attempt} 回目の失敗: ${message}`); // -> 1 回目の失敗: 一時的な失敗 1 回目
if (attempt === maxAttempts) throw err; // 最後の失敗は呼び出し元へ返す
await sleep(baseDelay * 2 ** (attempt - 1)); // 100ms → 200ms と待ちを倍にする
}
}
throw new Error("maxAttempts は 1 以上にする");
}
console.log(await retry(fetchData)); // -> 成功ジェネリクスの retry<T> にすると、渡した関数の戻り値の型がそのまま保たれる。catch の変数は unknown なので、instanceof Error で絞り込んでから message を読む。
Go
package main
import (
"errors"
"fmt"
"time"
)
var calls = 0
func fetch() (string, error) {
calls++
if calls < 3 {
return "", fmt.Errorf("一時的な失敗 %d 回目", calls)
}
return "成功", nil
}
func retry(maxAttempts int, baseDelay time.Duration, fn func() (string, error)) (string, error) {
var lastErr error
for attempt := 1; attempt <= maxAttempts; attempt++ {
result, err := fn()
if err == nil {
return result, nil
}
lastErr = err
fmt.Printf("%d 回目の失敗: %v\n", attempt, err) // -> 1 回目の失敗: 一時的な失敗 1 回目
if attempt < maxAttempts {
time.Sleep(baseDelay << (attempt - 1)) // 100ms → 200ms と待ちを倍にする
}
}
return "", errors.Join(errors.New("リトライ回数を使い切った"), lastErr)
}
func main() {
result, err := retry(3, 100*time.Millisecond, fetch)
fmt.Println(result, err) // -> 成功 <nil>
}Go に例外はないため、error が nil になるまで関数を呼び直す。
待ち時間は time.Duration を左シフトして倍にし、使い切ったときは errors.Join で最後のエラーを包んで返す。
Rust
use std::{thread, time::Duration};
fn retry<T, E: std::fmt::Display>(
max_attempts: u32,
base_delay: Duration,
mut f: impl FnMut() -> Result<T, E>,
) -> Result<T, E> {
let mut attempt = 1;
loop {
match f() {
Ok(v) => return Ok(v),
Err(e) if attempt >= max_attempts => return Err(e), // 最後の失敗はそのまま返す
Err(e) => {
println!("{} 回目の失敗: {}", attempt, e); // -> 1 回目の失敗: 一時的な失敗 1 回目
thread::sleep(base_delay * 2u32.pow(attempt - 1)); // 100ms → 200ms と待ちを倍にする
attempt += 1;
}
}
}
}
fn main() {
let mut calls = 0;
let result = retry(3, Duration::from_millis(100), || {
calls += 1;
if calls < 3 {
Err(format!("一時的な失敗 {} 回目", calls))
} else {
Ok("成功")
}
});
println!("{:?}", result); // -> Ok("成功")
}Result が Ok になるまでクロージャを呼び直す。FnMut を受け取るので、呼び出し回数の記録のように状態を変えるクロージャも渡せる。
最後の失敗は Err のまま返し、失敗を隠さない。
Java
import java.util.concurrent.Callable;
public class Main {
static int calls = 0;
static String fetch() throws Exception {
calls++;
if (calls < 3) throw new Exception("一時的な失敗 " + calls + " 回目");
return "成功";
}
static <T> T retry(int maxAttempts, long baseDelayMs, Callable<T> task) throws Exception {
for (int attempt = 1; ; attempt++) {
try {
return task.call();
} catch (Exception e) {
System.out.println(attempt + " 回目の失敗: " + e.getMessage()); // -> 1 回目の失敗: 一時的な失敗 1 回目
if (attempt >= maxAttempts) throw e; // 最後の失敗は呼び出し元へ返す
Thread.sleep(baseDelayMs << (attempt - 1)); // 100ms → 200ms と待ちを倍にする
}
}
}
public static void main(String[] args) throws Exception {
System.out.println(retry(3, 100, Main::fetch)); // -> 成功
}
}Callable を受け取るメソッドにすると、検査例外を投げる処理もそのまま渡せる。
待ち時間は Thread.sleep にシフト演算で倍にした値を渡し、最後の失敗は throw e で呼び出し元へ返す。
C#
var calls = 0;
string Fetch()
{
calls++;
if (calls < 3) throw new InvalidOperationException($"一時的な失敗 {calls} 回目");
return "成功";
}
T Retry<T>(Func<T> func, int maxAttempts = 3, int baseDelayMs = 100)
{
for (var attempt = 1; ; attempt++)
{
try
{
return func();
}
catch (InvalidOperationException e) when (attempt < maxAttempts)
{
Console.WriteLine($"{attempt} 回目の失敗: {e.Message}"); // -> 1 回目の失敗: 一時的な失敗 1 回目
Thread.Sleep(baseDelayMs << (attempt - 1)); // 100ms → 200ms と待ちを倍にする
}
}
}
Console.WriteLine(Retry(Fetch)); // -> 成功catch に when (attempt < maxAttempts) の条件を付けると、最後の試行の例外だけは捕捉されずに呼び出し元へそのまま伝わる。Thread.Sleep に倍にした待ち時間を渡して間隔を空ける。
つまずき: 最後の失敗を握りつぶすと、失敗に気づけない
リトライ処理で最後の試行が失敗したときに例外を捕捉したまま何も返さないと、呼び出し元は成功したのか失敗したのかを判断できない。
ここでは Python で raise、JavaScript と Java で throw、Go で error の戻り値、Rust で Err を返し、使い切った失敗を必ず呼び出し元へ渡している。
リトライしてよい例外だけを捕捉する
Python の例では except ConnectionError に絞った。
別の関数で ValueError を投げる処理を同じ retry に渡して実行したところ、1 回目で例外がそのまま伝わり、リトライは行われなかった。
入力の誤りのように、何度やっても結果が変わらない失敗を繰り返しても待ち時間が増えるだけである。
一方、接続エラーのように一時的な失敗を ConnectionError で 3 回投げ続けた場合は、3 回試したあとに同じ例外が呼び出し元へ返った。
待ち時間を倍にしていく理由
一定の間隔でやり直すと、相手のサーバーが不調なときに同じタイミングで要求が集中しやすい。
待ち時間を 100ms、200ms と倍にしていくと、回復する時間を稼げる。
ここで示した例は動作を確かめやすいよう、待ち時間を短くして試行回数も 3 回にしている。
実際の通信ではもっと長い待ち時間と、ランダムなずれの追加を検討する。