Socket
Book a DemoInstallSign in
Socket

mz.attahri.com/code/backoff

Package Overview
Dependencies
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

mz.attahri.com/code/backoff

Go Modules
Version
v1.0.0
Version published
Created
Source

GoDoc reference Lint Test

Backoff

Package backoff implements backoff logic for retry loops.

It provides a Generator that produces a sequence of time.Duration values using configurable step functions: Fixed, Linear, Incremental, Exponential, and Jitter.

Usage

Exponential Backoff

gen := backoff.New(time.Second, 30*time.Second, backoff.Exponential(2))

for attempt := range gen.Values() {
    if err := doSomething(); err == nil {
        break
    }
    time.Sleep(attempt)
}
// Produces: 1s, 2s, 4s, 8s, 16s, 30s, 30s, ...

With Jitter

Jitter is useful in distributed systems to avoid thundering herd problems.

gen := backoff.New(
    time.Second,
    30*time.Second,
    backoff.Jitter(backoff.Exponential(2), 0.5),
)

for i := 0; i < maxRetries; i++ {
    if err := doSomething(); err == nil {
        break
    }
    time.Sleep(gen.Next())
}
// Produces values in range: [0.5s-1s], [1s-2s], [2s-4s], ...

Linear Backoff

gen := backoff.New(time.Second, 10*time.Second, backoff.Linear(2*time.Second))
// Produces: 1s, 3s, 5s, 7s, 9s, 10s, 10s, ...

Fixed Backoff

gen := backoff.New(time.Second, 0, backoff.Fixed(5*time.Second))
// Produces: 5s, 5s, 5s, ...

Step Functions

FunctionDescription
Fixed(d)Always returns d
Linear(d)Adds d each iteration: base, base+d, base+2d, ...
Incremental(m)Multiplies base by count: base, base*m, base*2m, ...
Exponential(f)Exponential growth: base, base*f, base*f^2, ...
Jitter(fn, factor)Wraps any step function with randomized jitter in [d-factor*d, d]

Contributions

Contributions are welcome via Pull Requests.

FAQs

Package last updated on 01 Dec 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts