LoginSignup
5
1

More than 3 years have passed since last update.

RustでもExponential backoff and jitterアルゴリズムでリトライしたい

Last updated at Posted at 2020-12-05

はじめに

ハンズラボ Advent Calendar 2020 6日目を担当します@ryosukeeeeeです。

RustでExponential backoff and jitterアルゴリズムでリトライしたくなって、良さげなCrateを見つけたのでご紹介します。
Crate名は「exponential-backoff」です。最終更新は2年前ですが、Rust 1.48.0でも問題なく動作しました。
exponential-backoff - crates.io: Rust Package Registry

Exponential backoff and jitterの詳細はこちらの記事をご覧ください。めちゃくちゃ分かりやすいのでおすすめです。
AWS Solutions Architect ブログ: Exponential Backoff And Jitter

サンプルコード

README.mdのコードを元にしたサンプルコードがこちらです。
設定は以下の通りです。

  • 最大リトライ数: 8
  • 最小待ち時間: 100ms
  • 最大待ち時間: 10s
  • ジッター: 0.3
  • 繰り返し毎の倍率: 2倍
extern crate exponential_backoff;

use exponential_backoff::Backoff;
use std::{fs, thread, time::Duration};

fn main() {
    let retries = 8;
    let backoff = Backoff::new(retries)
        .timeout_range(Duration::from_millis(100), Duration::from_secs(10))
        .jitter(0.3)
        .factor(2);

    for duration in &backoff {
        match fs::read_to_string("README.md") {
            Ok(string) => println!("{}", string),
            Err(_) => match duration {
                Some(duration) => {
                    println!("{:?}", duration);
                    thread::sleep(duration);
                }
                None => {
                    println!("finish");
                    return;
                }
            },
        }
    }
}

実行してみると、待ち時間が指数関数的に増加していることが確認できます。

$ ./target/release/backoffsample 
100ms
240ms
284ms
960ms
1.92s
2.592s
5.504s
10s
finish

終わりに

ハンズラボ Advent Calendar 2020 明日の7日目は、 @shnskfjwr さんです!お楽しみに🎉

5
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
1