Retry - Efficient for-loop retries in Go

retry

Package retry implements an efficient loop-based retry mechanism that allows the retry policy to be specified independently of the control structure. It supports exponential (with jitter) and linear retry policies.

Although syntactically lightweight, it's also flexible - for example, it can be used to run a backoff loop while waiting for other concurrent events, or with mocked-out time.

Types

type Iter

type Iter struct { ... }

Iter represents a particular retry iteration loop using some strategy.

func (*Iter) Count

func (i *Iter) Count() int

Count returns the number of iterations so far. Specifically, this returns the number of times that Next or NextTime have returned true.

func (*Iter) Next

func (i *Iter) Next(stop <-chan struct{ ... }) bool

Next sleeps until the next iteration is to be made and reports whether there are any more iterations remaining.

If a value is received on the stop channel, it immediately stops waiting for the next iteration and returns false. i.WasStopped can be called to determine if that happened.

func (*Iter) NextTime

func (i *Iter) NextTime() (time.Time, bool)

NextTime is similar to Next except that it instead returns immediately with the time that the next iteration should begin. The caller is responsible for actually waiting until that time.

func (*Iter) Reset

func (i *Iter) Reset(strategy *Strategy, now func() time.Time)

Reset is like Strategy.Start but initializes an existing Iter value which can save the allocation of the underlying time.Timer used when Next is called with a non-nil stop channel.

It also accepts a function that is used to get the current time. If that's nil, time.Now will be used.

It's OK to call this on the zero Iter value.

func (*Iter) StartTime

func (i *Iter) StartTime() time.Time

StartTime returns the time that the iterator was created or last reset.

func (*Iter) TryTime

func (i *Iter) TryTime() (time.Time, bool)

TryTime returns the time that the current try iteration should be made at, if there should be one. If iteration has finished, it returns (time.Time{}, false).

The returned time can be in the past (after Start or Reset or Next have been called) or in the future (after NextTime has been called, TryTime returns the same values that NextTime returned).

Calling TryTime repeatedly will return the same values until Next or NextTime or Reset have been called.

func (*Iter) WasStopped

func (i *Iter) WasStopped() bool

WasStopped reports whether the most recent call to Next was stopped because a value was received on its stop channel.

type Strategy

type Strategy struct { ... }

Strategy represents a retry strategy. This specifies how a set of retries should be made and can be reused for any number of loops (it's treated as immutable by this package).

If an iteration takes longer than the delay for that iteration, the next iteration will be moved accordingly. For example, if the strategy has a delay of 1ms and the first two tries take 1s and 0.5ms respectively, then the second try will start immediately after the first (at 1s), but the third will start at 1.1s.

All strategies will loop for at least one iteration. The only time a loop might terminate immediately is when a value is received on the stop channel.

func ParseStrategy

func ParseStrategy(s string) (*Strategy, error)

ParseStrategy parses a string representation of a strategy. It takes the form of space-separated attribute=value pairs, where the available attributes are the lower-cased field names from the Strategy type. Values of time.Duration type are parsed with time.ParseDuration; floats are parsed with strconv.ParseFloat and boolean values must be either "true" or "false".

Fields may be in any order but must not be repeated.

For example:

delay=1ms maxdelay=1s regular=true factor=1.5 maxcount=10 maxduration=5m

The delay field is mandatory.

func (*Strategy) Start

func (s *Strategy) Start() *Iter

Start starts a retry loop using s as a retry strategy and returns an Iter that can be used to wait for each retry in turn. Note: the first try should be made immediately after calling Start without calling Next.

func (*Strategy) String

func (s *Strategy) String() string

String returns the strategy in the format understood by ParseStrategy.


Readme created from Go doc with goreadme

Similar Resources

Go library that makes it easy to add automatic retries to your projects, including support for context.Context.

go-retry Go library that makes it easy to add automatic retries to your projects, including support for context.Context. Example with context.Context

Aug 15, 2022

go HTTP client that makes it plain simple to configure TLS, basic auth, retries on specific errors, keep-alive connections, logging, timeouts etc.

goat Goat, is an HTTP client built on top of a standard Go http package, that is extremely easy to configure; no googling required. The idea is simila

Jun 25, 2022

retryablehttp package provides a familiar HTTP client interface with automatic retries and exponential backoff.

retryablehttp package provides a familiar HTTP client interface with automatic retries and exponential backoff.

Jan 4, 2023

Resilient wrapper around Go http.Client that uses exponential backoff and jitter for retries.

Hardy Hardy is a very simple wrapper around http.Client that enables you to add more resilience and reliability for your HTTP calls through retries. A

Dec 29, 2022

Hunch provides functions like: All, First, Retry, Waterfall etc., that makes asynchronous flow control more intuitive.

Hunch provides functions like: All, First, Retry, Waterfall etc., that makes asynchronous flow control more intuitive.

Hunch Hunch provides functions like: All, First, Retry, Waterfall etc., that makes asynchronous flow control more intuitive. About Hunch Go have sever

Dec 8, 2022

Enriches the standard go http client with retry functionality.

httpRetry Enriches the standard go http client with retry functionality using a wrapper around the Roundtripper interface. The advantage of this libra

Dec 10, 2022

Retry, Race, All, Some, etc strategies for http.Client calls

reqstrategy Package reqstrategy provides functions for coordinating http.Client calls. It wraps typical call strategies like making simultaneous reque

Apr 30, 2021

A lightweight job scheduler based on priority queue with timeout, retry, replica, context cancellation and easy semantics for job chaining. Build for golang web apps.

Table of Contents Introduction What is RIO? Concern An asynchronous job processor Easy management of these goroutines and chaining them Introduction W

Dec 9, 2022

Retry tests with go.

Go Retry Test go get -u github.com/cateiru/go-retry Example import ( "testing" "github.com/cateiru/go-retry" ) func Tes

Dec 11, 2021

Retry a function execution with specific intervals with panic recovery

Retry Retry a function execution with specific intervals with panic recovery Make sure to read the docs to understand how this package works and what

Jun 8, 2020

Fast, secure and efficient secure cookie encoder/decoder

Encode and Decode secure cookies This package provides functions to encode and decode secure cookie values. A secure cookie has its value ciphered and

Dec 9, 2022

Fast, secure, efficient backup program

Fast, secure, efficient backup program

Introduction restic is a backup program that is fast, efficient and secure. It supports the three major operating systems (Linux, macOS, Windows) and

Dec 31, 2022

A Go library for an efficient implementation of a skip list: https://godoc.org/github.com/MauriceGit/skiplist

A Go library for an efficient implementation of a skip list: https://godoc.org/github.com/MauriceGit/skiplist

Fast Skiplist Implementation This Go-library implements a very fast and efficient Skiplist that can be used as direct substitute for a balanced tree o

Dec 30, 2022

Efficient cache for gigabytes of data written in Go.

BigCache Fast, concurrent, evicting in-memory cache written to keep big number of entries without impact on performance. BigCache keeps entries on hea

Jan 4, 2023

Fast, efficient, and scalable distributed map/reduce system, DAG execution, in memory or on disk, written in pure Go, runs standalone or distributedly.

Gleam Gleam is a high performance and efficient distributed execution system, and also simple, generic, flexible and easy to customize. Gleam is built

Jan 1, 2023

Conception was an experimental project, looking for ways to make software development more efficient.

Conception was an experimental project, looking for ways to make software development more efficient.

Conception Note: All future development is done in the Go version. Conception is an experimental research project, meant to become a modern IDE/Langua

Jul 21, 2022

Package geom implements efficient geometry types for geospatial applications.

go-geom Package geom implements efficient geometry types for geospatial applications. Key features OpenGeo Consortium-style geometries. Support for 2D

Jan 6, 2023

Efficient moving window for high-speed data processing.

Moving Window Data Structure Copyright (c) 2012. Jake Brukhman. ([email protected]). All rights reserved. See the LICENSE file for BSD-style license. I

Sep 4, 2022

Fast, efficient, and scalable distributed map/reduce system, DAG execution, in memory or on disk, written in pure Go, runs standalone or distributedly.

Gleam Gleam is a high performance and efficient distributed execution system, and also simple, generic, flexible and easy to customize. Gleam is built

Jan 5, 2023
Comments
  • use do-while loop style

    use do-while loop style

    The HasMore method has always seemed a bit odd, and also the need to guarantee that a loop will run at least once. Instead, change the idiomatic loop style from:

    for i := strategy.Start(nil); i.Next(); {
    	doSomething()
    }
    

    to:

    i := strategy.Start()
    for {
    	doSomething()
    	if !i.Next(nil) {
    		break
    	}
    }
    

    This means that it's obvious by inspection that at least one try will be made; there's no need for HasMore because the variables associated with the try are all in scope when the test is made, and if we return inside the if !i.Next() body, the there's no need for a panic("unreachable") because the compiler can see that there's no way for the loop to terminate any other way.

    The down side is that it's a bit more verbose, but I think that the other points outweigh that consideration.

    Also pass the stop channel to Next rather than to Start so it's a bit clearer that Next is the only method that blocks and therefore needs a way to ask it to stop.

Related tags
Go library that makes it easy to add automatic retries to your projects, including support for context.Context.

go-retry Go library that makes it easy to add automatic retries to your projects, including support for context.Context. Example with context.Context

Aug 15, 2022
retryablehttp package provides a familiar HTTP client interface with automatic retries and exponential backoff.

retryablehttp package provides a familiar HTTP client interface with automatic retries and exponential backoff.

Jan 4, 2023
Enriches the standard go http client with retry functionality.

httpRetry Enriches the standard go http client with retry functionality using a wrapper around the Roundtripper interface. The advantage of this libra

Dec 10, 2022
Retry, Race, All, Some, etc strategies for http.Client calls

reqstrategy Package reqstrategy provides functions for coordinating http.Client calls. It wraps typical call strategies like making simultaneous reque

Apr 30, 2021
Retry tests with go.

Go Retry Test go get -u github.com/cateiru/go-retry Example import ( "testing" "github.com/cateiru/go-retry" ) func Tes

Dec 11, 2021
Retry a function execution with specific intervals with panic recovery

Retry Retry a function execution with specific intervals with panic recovery Make sure to read the docs to understand how this package works and what

Jun 8, 2020
Fast event-loop networking for Go
Fast event-loop networking for Go

evio is an event loop networking framework that is fast and small. It makes direct epoll and kqueue syscalls rather than using the standard Go net pac

Dec 31, 2022
Go library to create resilient feedback loop/control controllers.

Gontroller A Go library to create feedback loop/control controllers, or in other words... a Go library to create controllers without Kubernetes resour

Jan 1, 2023
Go (golang) http calls with retries and backoff

pester pester wraps Go's standard lib http client to provide several options to increase resiliency in your request. If you experience poor network co

Dec 28, 2022
Golang gRPC Middlewares: interceptor chaining, auth, logging, retries and more.

Golang gRPC Middlewares: interceptor chaining, auth, logging, retries and more.

Jan 7, 2023