Reference

Programming languages

Choose TypeScript, Go, Rust or C++ and find syntax, everyday APIs, standard libraries and tools in one place.

Scope and conventions

TypeScript/Node, Go 1.23+, Rust 2024 and C++23: from a first CLI to files, JSON, HTTP, concurrency and testing. Complete programs are labeled; other examples identify their surrounding code/imports. Optional libraries and version requirements are named in each entry.

Errors & cleanup

Recognize results and ignored values

Rust

Result has Ok/Err; Option has Some/None. ? propagates an error from a compatible function. unwrap/expect extract success or panic. _ matches or ignores a value.

Fragment

Fragment inside a function.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
match "24".parse::<i32>() {
    Ok(n) => println!("{n}"),
    Err(error) => eprintln!("{error}"),
}

Return or propagate a failure

Rust

Result<T, E> makes success/failure part of the type. ? returns early on Err from a compatible function, with supported error conversion. It does not catch panics. Option also supports ? in compatible Option-returning functions.

Fragment

Fragment: imports and type/function declarations at file scope; usage statements inside a function.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
fn parse_count(text: &str)
    -> Result<i32, std::num::ParseIntError>
{
    let value = text.parse::<i32>()?;
    Ok(value)
}

Recognize resource cleanup

Rust

Values with Drop run cleanup when dropped; scope exit is a common trigger. std::mem::drop consumes a value to drop it earlier. Some process termination paths do not unwind/drop values, and panicking behavior depends on the panic strategy.

Fragment

Fragment: imports and type/function declarations at file scope; usage statements inside a function.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
let text = String::from("north");
drop(text);

// text has been consumed and cannot be used again.

Choose an error-handling strategy: exceptions, error values, Result, error codes, optional, panics

Rust

Rust's idiomatic strategy is Result<T, E>: failure is part of the return type, the compiler warns if a Result is ignored (#[must_use]), and ? propagates an Err to the caller in one character. Option<T> is the separate type for absence, which is not an error. For bugs and broken invariants there is panic!, usually through unwrap, expect or an assert, which unwinds the thread (or aborts the process if configured). Rust has no exceptions; std::io::Error exposes OS error codes through kind() and raw_os_error() rather than as a separate mechanism.

Complete program

Complete program.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
use std::collections::HashMap;
use std::error::Error;
use std::num::ParseIntError;

#[derive(Debug)]
enum PortError {
    NotANumber(ParseIntError),
    OutOfRange(u32),
}

// 1. Result (idiomatic): failure is part of the signature, and ? propagates it.
fn parse_port(text: &str) -> Result<u16, PortError> {
    let n: u32 = text.parse().map_err(PortError::NotANumber)?;
    u16::try_from(n)
        .ok()
        .filter(|&p| p != 0)
        .ok_or(PortError::OutOfRange(n))
}

// Quick start: main can return Result. ? then converts any error type into
// Box<dyn Error>, and an Err from main prints its Debug form and exits with status 1.
fn main() -> Result<(), Box<dyn Error>> {
    for text in ["8080", "99999", "eighty"] {
        match parse_port(text) {
            Ok(port) => println!("parsed: {port}"),
            Err(PortError::OutOfRange(n)) => println!("error: {n} is out of range"),
            Err(PortError::NotANumber(e)) => println!("error: {text:?} is not a number ({e})"),
        }
    }

    // 2. Option for absence: a missing key is an expected outcome, not an error.
    let well_known = HashMap::from([("http", 80u16), ("https", 443)]);
    match well_known.get("ssh") {
        Some(port) => println!("ssh port: {port}"),
        None => println!("ssh port: unknown"),
    }

    // Alternative: .ok() turns a Result into an Option when the reason does not matter.
    let fallback = parse_port("eighty").ok().unwrap_or(80);
    println!("fallback port: {fallback}");

    // 3. Panic for bugs: expect documents why this cannot fail.
    let https = well_known.get("https").expect("https is always in the table");
    println!("https port: {https}");

    let configured: u16 = "8443".parse()?; // a ParseIntError would end main here
    println!("configured port: {configured}");
    Ok(())
}

Trade-offs: Result is explicit and cheap (an ordinary return value, no unwinding), and combinators make it composable, but every fallible function needs an error type and a conversion story.

In practice: return Result for anything the caller might handle, Option for "nothing there", and panic only for programming errors. Use .ok() to drop an error you truly do not care about, and expect("why this cannot fail") rather than bare unwrap when a panic is intended. For scripts and small tools, fn main() -> Result<(), Box<dyn Error>> lets ? propagate any error out of main.

? works on Option too, but only in a function that returns Option; it does not convert between Option and Result. Use ok_or or .ok() to cross over.

Libraries usually define an error enum (thiserror 2.0.21 derives the boilerplate); applications often use anyhow 1.0.104 for a single boxed error type with context.

Define a custom error type: Error subclasses, error structs, error enums, exception hierarchies

Rust

A custom error is usually an enum with one variant per failure, each carrying the data a caller needs. Implement Display for the human-readable message and std::error::Error so it works with ?, Box<dyn Error> and error reporters; override source() to expose an underlying cause. Callers match on the variants, and the match is exhaustive. Box<dyn Error> erases the type when you only need to report; downcast_ref recovers it.

Complete program

Complete program.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
use std::error::Error;
use std::fmt;
use std::num::ParseIntError;

// One enum lists every way this module can fail; callers match on it.
#[derive(Debug)]
enum OrderError {
    NotFound { id: String },
    InvalidQuantity { text: String, source: ParseIntError },
    OutOfStock { requested: u32, available: u32 },
}

// Display is the human-readable message. Keep it lowercase and without the cause.
impl fmt::Display for OrderError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            OrderError::NotFound { id } => write!(f, "order {id} not found"),
            OrderError::InvalidQuantity { text, .. } => write!(f, "invalid quantity {text:?}"),
            OrderError::OutOfStock { requested, available } => {
                write!(f, "requested {requested}, only {available} in stock")
            }
        }
    }
}

// std::error::Error marks it as an error type; source() exposes the underlying cause.
impl Error for OrderError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            OrderError::InvalidQuantity { source, .. } => Some(source),
            _ => None,
        }
    }
}

fn reserve(id: &str, quantity: &str) -> Result<u32, OrderError> {
    if id != "o1" {
        return Err(OrderError::NotFound { id: id.to_string() });
    }
    let requested: u32 = quantity.parse().map_err(|source| OrderError::InvalidQuantity {
        text: quantity.to_string(),
        source,
    })?;
    let available = 5;
    if requested > available {
        return Err(OrderError::OutOfStock { requested, available });
    }
    Ok(available - requested)
}

fn main() {
    for (id, qty) in [("o1", "2"), ("o9", "1"), ("o1", "two"), ("o1", "8")] {
        match reserve(id, qty) {
            Ok(left) => println!("reserved, {left} left"),
            Err(e @ OrderError::OutOfStock { .. }) => println!("retry later: {e}"),
            Err(e) => match e.source() {
                Some(cause) => println!("error: {e} (caused by: {cause})"),
                None => println!("error: {e}"),
            },
        }
    }

    // Box<dyn Error> can hold any error; downcast_ref recovers the concrete type.
    let boxed: Box<dyn Error> = Box::new(reserve("o9", "1").unwrap_err());
    if let Some(OrderError::NotFound { id }) = boxed.downcast_ref::<OrderError>() {
        println!("downcast found missing id {id}");
    }
}

In practice: one error enum per module or library boundary is the usual granularity. Keep Display lowercase and without the cause (reporters print the source chain themselves). Implement From<OtherError> for variants that wrap another error so ? converts automatically. In libraries, derive the impls with thiserror instead of writing them by hand.

thiserror 2.0.21 generates Display, Error and From impls with #[derive(Error)], #[error("...")], #[source] and #[from]; it adds nothing to your public API that hand-written impls would not.

Add #[non_exhaustive] to a public error enum if you may add variants later; downstream matches then need a wildcard arm, so adding one is not a breaking change.

Error requires Debug + Display. Derive Debug; it is what unwrap and expect print.

Add context to an error: cause, %w, source chains, nested exceptions

Rust

An error exposes its cause through std::error::Error::source(), and following source() repeatedly gives the chain. The standard library has no context wrapper, so most code uses two crates. In libraries, thiserror (2.x) derives Display and Error for an error enum, and #[source] or #[from] on a field makes it the cause. In applications, anyhow (1.x) provides anyhow::Result, which holds any error, plus .context("...") and .with_context(|| ...) to add a layer; chain() walks the causes and downcast_ref finds a concrete type such as io::Error in them.

Complete program

Complete program.

Before you use this

Not in the standard library: cargo add anyhow@1 thiserror@2 (checked with anyhow 1.0.104 and thiserror 2.0.21).

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
use std::{fs, io};

use anyhow::{Context, Result};
use thiserror::Error;

// Library code: a typed error enum. thiserror derives Display and Error;
// #[source] makes source() return the io::Error.
#[derive(Debug, Error)]
enum SettingsError {
    #[error("read settings from {path}")]
    Read {
        path: String,
        #[source]
        source: io::Error,
    },
    #[error("settings file {path} is empty")]
    Empty { path: String },
}

fn read_settings(path: &str) -> Result<String, SettingsError> {
    let text = fs::read_to_string(path).map_err(|source| SettingsError::Read {
        path: path.to_string(),
        source,
    })?;
    if text.trim().is_empty() {
        return Err(SettingsError::Empty { path: path.to_string() });
    }
    Ok(text)
}

// Application code: anyhow::Result holds any error, and .context() adds a layer.
fn load_config(path: &str) -> Result<String> {
    read_settings(path).context("load config")
}

fn main() -> Result<()> {
    let err = load_config("/no/such/dir/settings.json").unwrap_err();

    // {:#} prints the chain on one line; chain() walks it outermost first.
    println!("{err:#}");
    for cause in err.chain().skip(1) {
        println!("  caused by: {cause}");
    }

    // downcast_ref finds a concrete type anywhere in the chain.
    let io_kind = err.chain().find_map(|e| e.downcast_ref::<io::Error>()).map(io::Error::kind);
    println!("root io kind: {io_kind:?}");

    // with_context builds the message only on the error path. ? returns it from main,
    // which prints the error with its causes and exits with status 1.
    let text = "8080";
    let port: u16 = text.parse().with_context(|| format!("parse port {text:?}"))?;
    println!("port: {port}");
    Ok(())
}

In practice: return typed errors from libraries so callers can match, and use anyhow with .context() in binaries, where errors are only reported. Keep each Display message to its own layer and let the reporter print the "caused by" lines: {:#} prints the chain on one line, {:?} on several.

Without dependencies, write the wrapper yourself: a struct with a context: String and a source: Box<dyn Error + Send + Sync>, whose Display prints only the context and whose source() returns the box. map_err(|e| ContextError { context: "load config".into(), source: Box::new(e) }) adds a layer, and std::iter::successors(Some(err), |e| e.source()) walks the chain.

If Display includes the cause and source() also returns it, reporters print the cause twice. Pick one: the convention is source().

Returning anyhow::Result from main prints the error and its causes in Debug form and exits with status 1.

Return typed errors: Result, (T, error), Result<T, E>, std::expected

Rust

Result<T, E> is an enum with Ok(T) and Err(E), and E is usually your own enum, so the error itself is a discriminated union. ? returns early with the Err (converting via From if needed). Combinators chain steps without a match: map transforms the value, and_then runs another fallible step, map_err changes the error, ok_or turns an Option into a Result, and unwrap_or_else supplies a fallback computed from the error. match on the error enum is exhaustive, so a new variant breaks every handler that forgot it.

Complete program

Complete program.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#[derive(Debug, PartialEq)]
enum UsernameError {
    Empty,
    TooLong { max: usize, actual: usize },
    BadChar(char),
    Reserved,
}

fn parse_username(input: &str) -> Result<String, UsernameError> {
    let name = input.trim().to_lowercase();
    if name.is_empty() {
        return Err(UsernameError::Empty);
    }
    let actual = name.chars().count();
    if actual > 16 {
        return Err(UsernameError::TooLong { max: 16, actual });
    }
    if let Some(c) = name.chars().find(|c| !(c.is_ascii_alphanumeric() || *c == '_')) {
        return Err(UsernameError::BadChar(c));
    }
    Ok(name)
}

fn not_reserved(name: String) -> Result<String, UsernameError> {
    if ["admin", "root"].contains(&name.as_str()) { Err(UsernameError::Reserved) } else { Ok(name) }
}

// ? returns early with the Err; the happy path reads top to bottom.
fn signup(line: &str) -> Result<String, UsernameError> {
    // ok_or turns an Option into a Result with the given error.
    let word = line.split_whitespace().next().ok_or(UsernameError::Empty)?;
    let name = parse_username(word)?;
    not_reserved(name)
}

// match on the enum is exhaustive: adding a variant breaks this until it is handled.
fn message(e: &UsernameError) -> String {
    match e {
        UsernameError::Empty => "enter a username".into(),
        UsernameError::TooLong { max, actual } => {
            format!("use at most {max} characters (got {actual})")
        }
        UsernameError::BadChar(c) => format!("{c:?} is not allowed"),
        UsernameError::Reserved => "that name is reserved".into(),
    }
}

fn main() {
    for input in ["  Ada_L ", "", "grace hopper", &"x".repeat(20), "Admin"] {
        // Combinators: and_then chains another fallible step, map transforms the value.
        let r = parse_username(input).and_then(not_reserved).map(|n| n.len());
        match r {
            Ok(len) => println!("{input:?} -> ok, {len} chars"),
            Err(e) => println!("{input:?} -> error: {}", message(&e)),
        }
    }

    assert_eq!(signup("Ada_L joined"), Ok("ada_l".to_string()));
    assert_eq!(signup("   "), Err(UsernameError::Empty));
    assert_eq!(signup("root now"), Err(UsernameError::Reserved));

    // unwrap_or_else gives a fallback computed from the error.
    let shown = parse_username("!").unwrap_or_else(|e| format!("<{}>", message(&e)));
    println!("shown: {shown}");
}

In practice: write the happy path with ?, use combinators for short pipelines, and match on the error only where you decide what to do. Derive PartialEq on error enums so tests can assert_eq! on them.

ok_or evaluates its argument eagerly; use ok_or_else(|| ...) when building the error allocates or does work.

Result is #[must_use]: dropping one without handling it is a warning. let _ = f(); silences it explicitly.

Crash on a bug (panic): uncaught exceptions, panic/recover, panic!, std::terminate

Rust

panic! signals a bug or an unrecoverable state. By default it unwinds the current thread, dropping values on the way, and prints a message through the panic hook; a panic in main ends the process with status 101. unwrap and expect panic on Err or None, and assert!, index out of bounds and integer overflow in debug builds panic too. A thread is a panic boundary: JoinHandle::join returns Err if the thread panicked. std::panic::catch_unwind stops unwinding at a boundary, for example around an FFI callback or a task in a runtime, but it is not a try/catch for errors.

Complete program

Complete program.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
use std::panic;
use std::thread;

fn apply_discount(cents: u32, percent: u32) -> u32 {
    // assert! checks an invariant in every build; debug_assert! only in debug builds.
    assert!(percent <= 100, "percent out of range: {percent}");
    cents * (100 - percent) / 100
}

fn main() {
    // Replace the default panic message with a single line, to keep the output short.
    panic::set_hook(Box::new(|info| {
        eprintln!("panic: {}", info.payload_as_str().unwrap_or("non-string payload"))
    }));

    println!("discounted: {}", apply_discount(1_000, 15));

    // expect documents why a failure would be a bug; unwrap does the same without a reason.
    let port: u16 = "8080".parse().expect("port literal is valid");
    println!("port: {port}");

    // A thread is a panic boundary: join returns Err if the thread panicked.
    let worker = thread::spawn(|| apply_discount(1_000, 150));
    match worker.join() {
        Ok(v) => println!("worker returned {v}"),
        Err(payload) => {
            let msg = payload
                .downcast_ref::<String>()
                .map(String::as_str)
                .or_else(|| payload.downcast_ref::<&str>().copied())
                .unwrap_or("non-string panic");
            println!("worker panicked: {msg}");
        }
    }

    // catch_unwind exists for boundaries such as FFI callbacks or a task runner,
    // not for ordinary error handling. It does nothing if panic = "abort".
    let caught = panic::catch_unwind(|| {
        let empty: Vec<u32> = Vec::new();
        empty[0]
    });
    println!("catch_unwind caught a panic: {}", caught.is_err());
}

In practice: return Result for anything a caller could handle, and panic when continuing would be wrong. Prefer expect("reason") to unwrap in code that ships. Applications that want a crash to be immediate can set panic = "abort" in the Cargo profile, which also makes catch_unwind useless.

catch_unwind requires the closure to be UnwindSafe; wrap shared references in AssertUnwindSafe only when you have checked that a half-finished update cannot be observed.

A panic while already panicking (for example inside Drop during unwinding) aborts the process.

Panicking across an extern "C" boundary aborts; catch it with catch_unwind on the Rust side of an FFI callback.

Collect several errors: AggregateError, errors.Join, partition, a vector of errors

Rust

An iterator of Result values can be collected into Result<Vec<T>, E>: it stops at the first Err and returns it, which is the fail-fast option. To gather every error, partition(Result::is_ok) splits the results into two vectors, or a fold builds both in one pass without unwrap. There is no standard multi-error type; return Vec<E> or wrap it in your own error type with a Display that lists the parts.

Complete program

Complete program.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
use std::num::ParseIntError;

#[derive(Debug)]
struct LineError {
    line: usize,
    source: ParseIntError,
}

fn parse_line(line: usize, text: &str) -> Result<u32, LineError> {
    text.trim().parse().map_err(|source| LineError { line, source })
}

fn main() {
    let input = ["12", "x", "30", "-4", "7"];

    // 1. Fail fast: collecting into Result<Vec<_>, _> stops at the first Err.
    let first: Result<Vec<u32>, LineError> =
        input.iter().enumerate().map(|(i, t)| parse_line(i + 1, t)).collect();
    match &first {
        Ok(values) => println!("all parsed: {values:?}"),
        Err(e) => println!("fail fast: line {} ({})", e.line, e.source),
    }

    // 2. Collect everything: partition the results into successes and failures.
    let (oks, errs): (Vec<_>, Vec<_>) = input
        .iter()
        .enumerate()
        .map(|(i, t)| parse_line(i + 1, t))
        .partition(Result::is_ok);
    let values: Vec<u32> = oks.into_iter().map(Result::unwrap).collect(); // safe: all Ok
    let errors: Vec<LineError> = errs.into_iter().map(Result::unwrap_err).collect();

    println!("parsed {values:?}");
    for e in &errors {
        println!("  line {}: {}", e.line, e.source);
    }

    // 3. The same split without unwrap: fold into two vectors in one pass.
    let (sum, bad) = input.iter().enumerate().fold((0, Vec::new()), |(sum, mut bad), (i, t)| {
        match parse_line(i + 1, t) {
            Ok(v) => (sum + v, bad),
            Err(e) => {
                bad.push(e.line);
                (sum, bad)
            }
        }
    });
    println!("sum of valid lines: {sum}, bad lines: {bad:?}");
}

In practice: collect into Result<Vec<_>, _> when one bad item invalidates the batch, and partition or fold when you want to process the good items and report the bad ones. For parallel tasks, join each handle (or use a JoinSet in Tokio) and push the errors into a Vec.

The collect form short-circuits: items after the first error are not processed, so side effects in the map closure stop there too.

The unwraps after partition cannot fail (each vector holds only one variant), but a fold or a plain loop with match avoids them entirely.

Decide where to handle an error: translate at boundaries, log once, retry with backoff

Rust

In Rust the boundary is usually a type: each layer has its own error enum, and a From impl translates the layer below into it, so ? performs the translation automatically. Variants callers act on (EmailTaken) are explicit; everything else is kept whole (Storage(DbError)) for logging. The top level (an HTTP handler, main) matches on the error to pick a status and a user message, and logs the detail once. Retry logic wraps the low-level call and matches the low-level error type, before translation hides it.

Complete program

Complete program.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
use std::error::Error;
use std::fmt;
use std::thread::sleep;
use std::time::Duration;

// --- storage layer -----------------------------------------------------------
#[derive(Debug)]
enum DbError {
    ConnectionReset,
    UniqueViolation(&'static str),
}

impl fmt::Display for DbError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            DbError::ConnectionReset => f.write_str("connection reset by peer"),
            DbError::UniqueViolation(key) => write!(f, "duplicate key {key}"),
        }
    }
}

impl Error for DbError {}

// attempt counts from 1; the first attempt always hits a transient failure.
fn insert_user(email: &str, attempt: u32) -> Result<u32, DbError> {
    match (attempt, email) {
        (1, _) | (_, "down@example.com") => Err(DbError::ConnectionReset),
        (_, "ada@example.com") => Err(DbError::UniqueViolation("users_email_key")),
        _ => Ok(42),
    }
}

// Retry transient errors only, with capped exponential backoff (10, 20, 40 ms ... 200 ms).
// Real code adds full jitter, sleeping a random time in 0..delay (for example with rand).
fn with_retry<T>(attempts: u32, mut f: impl FnMut(u32) -> Result<T, DbError>) -> Result<T, DbError> {
    let (mut attempt, mut delay) = (1, Duration::from_millis(10));
    loop {
        match f(attempt) {
            Err(DbError::ConnectionReset) if attempt < attempts => {
                sleep(delay);
                (attempt, delay) = (attempt + 1, (delay * 2).min(Duration::from_millis(200)));
            }
            result => return result,
        }
    }
}

// --- service layer: its own error type, so callers never see DbError ---------
#[derive(Debug)]
enum SignupError {
    EmailTaken,
    Storage(DbError), // kept for the log
}

// The translation lives in one From impl, so ? converts at the boundary.
impl From<DbError> for SignupError {
    fn from(e: DbError) -> Self {
        match e {
            DbError::UniqueViolation(_) => SignupError::EmailTaken,
            other => SignupError::Storage(other),
        }
    }
}

fn register_user(email: &str) -> Result<u32, SignupError> {
    Ok(with_retry(3, |attempt| insert_user(email, attempt))?)
}

// --- handler: status code, user message, and the single log line ----------
fn handle_signup(email: &str) -> (u16, String) {
    match register_user(email) {
        Ok(id) => (201, format!("user {id} created")),
        Err(SignupError::EmailTaken) => (409, "That email is already registered.".into()),
        Err(SignupError::Storage(e)) => {
            eprintln!("[req-7f3a] signup failed: storage: {e}");
            (500, "Something went wrong (reference req-7f3a).".into())
        }
    }
}

fn main() {
    println!("{:?}", handle_signup("grace@example.com")); // retried once
    println!("{:?}", handle_signup("ada@example.com"));
    println!("{:?}", handle_signup("down@example.com")); // transient every time
}

In practice: a library's public error type is part of its API, so do not expose a dependency's error type in a variant unless you are willing to break callers when the dependency changes. A public error type also implements Display and Error (or derives them with thiserror) so its source chain can be logged. Retry only transient variants, with a capped backoff.

Ok(with_retry(...)?) is the idiom for "convert the error with From and return"; .map_err(SignupError::from) does the same without the ?.

tracing 0.1.44 records errors as structured fields at the boundary; log the error with its source chain once rather than at each layer.

Async code sleeps with tokio::time::sleep instead of thread::sleep, and the backon crate packages retry policies with jitter (the older backoff crate is unmaintained, RUSTSEC-2025-0012).