Skip to content
ryePublic

About

♻️ Run commands with exponential backoff 📈

Topics

Resources

Stars

94 stars

Watchers

1 watching

Forks

Repository files navigation

eb

eb runs a command again and again, with exponential backoff, until it succeeds. It is also a Rust library for retrying any fallible operation the same way.

$ eb -- ssh -oConnectTimeout=5 host

This keeps trying to connect until ssh exits successfully, waiting longer and longer between attempts so that a host that is down is not hammered.

Installing

$ cargo install eb

Run the same command to update. eb requires Rust 1.88 or newer.

Using the command-line tool

eb [-x <max>] [--] <command> [<argument>...]

eb runs command with its arguments. If the command exits with status 0, eb exits with status 0 too. If it exits with any other status, eb waits and runs it again.

  • -x <max> limits the number of times the command runs, counting the first. When the last attempt fails, eb exits with that attempt's exit status. -x 0 exits successfully without running anything. Without -x, eb keeps retrying until the command succeeds or eb is interrupted, for example with Ctrl+C.

  • -- ends eb's own options. It is only needed when the command's name starts with -. Everything after the command's name is passed to it unchanged, so eb make --help shows make's help, not eb's.

The command's standard input, output and error are those of eb itself.

Exit status

Situation eb's exit status
The command succeeded 0
-x attempts ran and the last one failed the last attempt's exit status
The command was killed by a signal 1, with an error message; eb does not retry
No command, or an invalid -x 1, with an error message
The command could not be started, for example because it does not exist 101 (eb panics)

On Windows, an exit status that does not fit in 0–255 is reported as 1.

Timing

eb learns how long the command takes to fail and scales its waiting to match. It keeps the average runtime of the failed attempts so far, called the slot, and after the nth failure waits a random time between zero and slot × (2ⁿ − 1):

After failure Waits between On average
1 0 and 1 slot ½ slot
2 0 and 3 slots 1½ slots
3 0 and 7 slots 3½ slots
10 and later 0 and 1023 slots about 512 slots

The window stops growing after the tenth failure. A command that fails in 100 milliseconds therefore waits at most about 1.7 minutes between attempts, while one that takes 10 seconds to fail can wait up to about 2.8 hours. eb suits commands that fail quickly; for slow ones, consider -x, or wrapping the command in a timeout, such as eb -- timeout 5 some-command.

The random choice spreads out retries from many machines, so that they do not all retry at the same moment. The scheme is adapted from the collision backoff in Ethernet (IEEE 802.3).

Logging

eb can log each retry and how long it will wait. Logging is compiled in only with the simple_logger feature:

$ cargo install eb --features simple_logger

Using the library

The library retries any async or blocking operation that returns a Result, with any error type. Add it without the command-line tool's dependencies. If you use Tokio, also enable the tokio feature, so that eb can wait between attempts with Tokio's timer:

[dependencies]
eb = { version = "0.6", default-features = false, features = ["tokio"] }
use eb::{RetryError, RetryPolicy};
use core::{num::NonZero, time::Duration};
use std::io;

// Stands in for any async operation that can fail, such as an HTTP request.
async fn fetch(url: &str) -> io::Result<String> {
    Ok(format!("the contents of {url}"))
}

async fn fetch_with_retries(url: &str) -> Result<String, RetryError<io::Error>> {
    RetryPolicy::new()
        // Make at most five attempts in total, and stop retrying after a minute.
        .max_attempts(NonZero::new(5).unwrap())
        .max_elapsed(Duration::from_secs(60))
        // Note the `||`: `eb` calls this closure to get a new future for every attempt.
        .retry_async(|| fetch(url))
        .run()
        .await
}

eb takes a closure, || fetch(url), rather than the future that fetch(url) returns. A future runs only once, so to retry, eb needs a way to make a new one for each attempt. The result is the first successful value, or, once eb gives up, a RetryError holding the last attempt's error.

By default, a policy allows three attempts, waiting a random time of up to 1 second after the first failure and up to 3 seconds after the second. Without the tokio feature, pass your runtime's sleep function to .sleep_with(..).

Blocking operations work the same way, with retry_blocking and a run that needs no .await:

use eb::{RetryError, RetryPolicy};
use std::{io, net::TcpStream};

fn connect() -> Result<TcpStream, RetryError<io::Error>> {
    RetryPolicy::new()
        .retry_blocking(|| TcpStream::connect("example.com:80"))
        // Only retry errors that might go away on their own.
        .retry_while(|error| error.kind() == io::ErrorKind::ConnectionRefused)
        // Report each failure before waiting.
        .before_wait(|error, _, delay| eprintln!("{error}; retrying in {delay:?}"))
        .run()
}

You can also change how long eb waits: a different time scale, waits that follow how long the operation takes to fail, a largest delay, the same wait every time, or a strategy of your own. Hooks let you run code, such as logging, before and after each attempt, before each wait, and before each retry.

The API documentation explains every option, states the exact retry rules and backoff formula, and compares eb's backoff with those of Ethernet, AWS and gRPC.

Cargo features

Feature Default Effect
cli yes Builds the eb command-line tool. Library users can turn it off with default-features = false.
simple_logger no Makes the eb tool log each retry. Implies cli.
tokio no Makes the library wait between async attempts with Tokio's timer, so no sleep function is needed.

License

eb: A command executor exercising exponential backoff
Copyright (C) 2019-2021 Kristofer J. Rye

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.

About

♻️ Run commands with exponential backoff 📈

Topics

Resources

Stars

94 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages