18 releases (5 stable)

1.2.0 Sep 2, 2024
0.5.0 Aug 22, 2024
0.4.4 Apr 8, 2024
0.4.3 Mar 8, 2024
0.0.2 Apr 14, 2022

#43 in Rust patterns

Download history 40076/week @ 2024-07-27 45602/week @ 2024-08-03 41511/week @ 2024-08-10 48964/week @ 2024-08-17 50582/week @ 2024-08-24 49820/week @ 2024-08-31 76102/week @ 2024-09-07 89566/week @ 2024-09-14 92163/week @ 2024-09-21 99394/week @ 2024-09-28 94724/week @ 2024-10-05 98767/week @ 2024-10-12 78142/week @ 2024-10-19 66221/week @ 2024-10-26 66709/week @ 2024-11-02 56364/week @ 2024-11-09

279,789 downloads per month
Used in 203 crates (23 directly)

Apache-2.0

85KB
1.5K SLoC

BackON   Build Status Latest Version

BackON

Make retry like a built-in feature provided by Rust.

  • Simple: Just like a built-in feature: your_fn.retry(ExponentialBuilder::default()).await.
  • Flexible: Supports both blocking and async functions.
  • Powerful: Allows control over retry behavior such as when and notify.
  • Customizable: Supports custom retry strategies like exponential, constant, etc.

Quick Start

Retry an async function.

use anyhow::Result;
use backon::ExponentialBuilder;
use backon::Retryable;

async fn fetch() -> Result<String> {
    Ok("hello, world!".to_string())
}

#[tokio::main]
async fn main() -> Result<()> {
    let content = fetch
        // Retry with exponential backoff
        .retry(ExponentialBuilder::default())
        // Sleep implementation, required if no feature has been enabled
        .sleep(tokio::time::sleep)
        // When to retry
        .when(|e| e.to_string() == "EOF")
        // Notify when retrying
        .notify(|err: &anyhow::Error, dur: Duration| {
            println!("retrying {:?} after {:?}", err, dur);
        })
        .await?;
    println!("fetch succeeded: {}", content);

    Ok(())
}

Retry a blocking function.

use anyhow::Result;
use backon::BlockingRetryable;
use backon::ExponentialBuilder;

fn fetch() -> Result<String> {
    Ok("hello, world!".to_string())
}

fn main() -> Result<()> {
    let content = fetch
        // Retry with exponential backoff
        .retry(ExponentialBuilder::default())
        // When to retry
        .when(|e| e.to_string() == "EOF")
        // Notify when retrying
        .notify(|err: &anyhow::Error, dur: Duration| {
            println!("retrying {:?} after {:?}", err, dur);
        })
        .call()?;
    println!("fetch succeeded: {}", content);

    Ok(())
}

Contributing

Check out the CONTRIBUTING.md guide for more details on getting started with contributing to this project.

Getting help

Submit issues for bug report or asking questions in discussion.

License

Licensed under Apache License, Version 2.0.

Dependencies

~0–5.5MB
~24K SLoC