or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

backoff-policies.mdindex.mdretry-operations.mdticker.md
tile.json

index.mddocs/

Backoff

Backoff provides exponential backoff algorithms for retrying operations that may fail. It offers multiple backoff strategies including exponential backoff (which multiplicatively increases wait times between retries), constant backoff, zero backoff (immediate retry), and stop backoff (no retry), with configurable parameters like initial interval, randomization factor, multiplier, and maximum interval.

Package Information

  • Package Name: github.com/cenkalti/backoff/v4
  • Package Type: golang
  • Language: Go
  • Installation: go get github.com/cenkalti/backoff/v4

Core Imports

import "github.com/cenkalti/backoff/v4"

Basic Usage

Simple Retry with Exponential Backoff

import (
    "errors"
    "log"
    "github.com/cenkalti/backoff/v4"
)

func main() {
    operation := func() error {
        // Your operation that may fail
        return nil // or return an error
    }

    err := backoff.Retry(operation, backoff.NewExponentialBackOff())
    if err != nil {
        log.Fatal(err)
    }
}

Retry with Context Support

import (
    "context"
    "time"
    "github.com/cenkalti/backoff/v4"
)

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
    defer cancel()

    operation := func() error {
        // Your operation
        return nil
    }

    b := backoff.WithContext(backoff.NewExponentialBackOff(), ctx)
    err := backoff.Retry(operation, b)
    if err != nil {
        // Handle error
    }
}

Custom Exponential Backoff Configuration

import (
    "time"
    "github.com/cenkalti/backoff/v4"
)

func main() {
    b := backoff.NewExponentialBackOff(
        backoff.WithInitialInterval(1*time.Second),
        backoff.WithMaxInterval(30*time.Second),
        backoff.WithMaxElapsedTime(5*time.Minute),
        backoff.WithMultiplier(2.0),
        backoff.WithRandomizationFactor(0.5),
    )

    operation := func() error {
        // Your operation
        return nil
    }

    err := backoff.Retry(operation, b)
    if err != nil {
        // Handle error
    }
}

Capabilities

Retry Operations

Execute operations with automatic retry logic using various backoff policies. Supports simple retry, retry with data return, retry with notifications, and retry with custom timers. All retry functions guarantee at least one execution attempt and handle permanent errors that should not be retried.

// Retry the operation until it succeeds or backoff stops
func Retry(o Operation, b BackOff) error

// Retry and return data along with error
func RetryWithData[T any](o OperationWithData[T], b BackOff) (T, error)
// Function type for operations executed by Retry()
type Operation func() error

// Generic function type for operations that return data
type OperationWithData[T any] func() (T, error)

Retry Operations

Backoff Policies

Different strategies for calculating wait times between retry attempts. Includes exponential backoff (multiplicatively increasing intervals with jitter), constant backoff (fixed delay), zero backoff (immediate retry), and stop backoff (never retry). Policies can be wrapped with context support or maximum retry limits.

// Core backoff interface
type BackOff interface {
    NextBackOff() time.Duration
    Reset()
}

// Create exponential backoff with optional configuration
func NewExponentialBackOff(opts ...ExponentialBackOffOpts) *ExponentialBackOff

// Create constant backoff with fixed interval
func NewConstantBackOff(d time.Duration) *ConstantBackOff
// ExponentialBackOff configuration options
type ExponentialBackOffOpts func(*ExponentialBackOff)

func WithInitialInterval(duration time.Duration) ExponentialBackOffOpts
func WithMaxInterval(duration time.Duration) ExponentialBackOffOpts
func WithMaxElapsedTime(duration time.Duration) ExponentialBackOffOpts
func WithMultiplier(multiplier float64) ExponentialBackOffOpts
func WithRandomizationFactor(randomizationFactor float64) ExponentialBackOffOpts

Backoff Policies

Ticker-Based Retries

Channel-based retry mechanism using Go channels for backoff timing. Provides a ticker that sends time values at intervals determined by a backoff policy, allowing integration with channel-based workflows and select statements.

// Ticker holds a channel that delivers ticks at backoff intervals
type Ticker struct {
    C <-chan time.Time
    // Has unexported fields
}

// Create ticker with specified backoff policy
func NewTicker(b BackOff) *Ticker

// Stop the ticker
func (t *Ticker) Stop()

Ticker-Based Retries

Context Integration

Wrap any backoff policy to automatically stop retrying when a context is canceled or times out. Essential for implementing timeouts and cancellation in retry logic.

// BackOff with context cancellation support
// This interface embeds BackOff, so it includes NextBackOff() and Reset() methods
// plus the Context() method for accessing the associated context
type BackOffContext interface {
    BackOff
    Context() context.Context
}

// Wrap backoff to stop on context cancellation
func WithContext(b BackOff, ctx context.Context) BackOffContext

Retry Limiting

Limit the maximum number of retry attempts by wrapping any backoff policy. Useful for preventing infinite retry loops and implementing circuit breaker patterns.

// Wrap backoff to limit maximum retry attempts
func WithMaxRetries(b BackOff, max uint64) BackOff

Permanent Errors

Signal that an operation should not be retried by wrapping errors. When a permanent error is returned, all retry functions immediately stop retrying and return the wrapped error.

// Error type signaling no retry should be attempted
type PermanentError struct {
    Err error
}

// Wrap error to prevent retries
func Permanent(err error) error

Constants and Stop Signal

// Constant returned by NextBackOff() to indicate no more retries
const Stop time.Duration = -1

// Default configuration for ExponentialBackOff
const (
    DefaultInitialInterval     = 500 * time.Millisecond
    DefaultRandomizationFactor = 0.5
    DefaultMultiplier          = 1.5
    DefaultMaxInterval         = 60 * time.Second
    DefaultMaxElapsedTime      = 15 * time.Minute
)

Important Notes

  • Thread Safety: ExponentialBackOff and backoff wrappers are NOT thread-safe
  • Minimum Execution: All retry functions guarantee at least one execution attempt
  • Context Handling: BackOffContext automatically stops retrying when context is canceled
  • Generic Support: RetryWithData functions support Go generics (requires Go 1.18+)
  • Permanent Errors: Use Permanent() to wrap errors that should not trigger retries