cenkalti/backoff: exponential backoff for Go, and how to stop retrying the wrong errors
⏱ The exponential backoff algorithm in Go
At a glance
- What is it?
- cenkalti/backoff is a Go port of the exponential backoff algorithm from Google's HTTP Client Library for Java. Its v7 API centers on a generic Retry function that retries until success, a Permanent error, or a limit, and the interesting part is how it separates transient failures from ones that will never fix themselves.
- Who is it for?
- Adopt cenkalti/backoff if you are writing Go and want a small, MIT-licensed retry loop with exponential backoff, a Permanent error escape hatch, and explicit try and elapsed-time budgets. Do not adopt it if you need jitter, circuit breaking, or a retry policy shared across languages; the README does not document jitter, and the author states he wants to keep the library as small as possible.
- Can I use it commercially?
- Yes. MIT is a permissive licence: you can use, modify and sell software built on it, as long as you keep its copyright and licence notices.
- Is it still maintained?
- Yes. The repository last received commits 8 days ago.
- What is it written in?
- Mainly Go, according to GitHub's language statistics.
Answers come from the project's GitHub data, last synced on November 15, 2026, and from our analysis. They are not legal advice.
Star history
- cenkalti/backoff4,097 ★ · +13
| Repository | 2026-09-24 | 2026-11-15 |
|---|---|---|
| cenkalti/backoff | 4.1k | 4.1k |
13 Stars in the last 52 days, measured from the daily GitHub snapshot. Compare with other projects
Editorial analysis
What cenkalti/backoff actually solves, and for whom
Retrying a failed network call is easy to write badly. The naive loop hammers a struggling server, and the naive fix, a fixed sleep, either waits too long on a fast recovery or too little on a slow one. cenkalti/backoff is a Go library that implements the exponential backoff algorithm: the README describes it as using feedback to multiplicatively decrease the rate of some process, so retries increase exponentially and stop increasing once a threshold is met. The project is a Go port of the algorithm from Google's HTTP Client Library for Java, and the repository is small by design: backoff.go, error.go, exponential.go, retry.go, ticker.go and timer.go, plus their tests, are the whole implementation. It is aimed at Go developers who are already comfortable with contexts and errors and want a retry loop they can read in one sitting. If you want a retry framework with pluggable policies, metrics hooks and a configuration file, this is not that, and the contributing notes say so directly: the author wants to keep the library as small as possible and asks for an issue before a pull request.
The Retry loop, Permanent errors, and the two independent time limits
The core mechanism is a generic function. Retry takes a context and an operation that returns a value and an error, runs the operation at least once, and keeps retrying with exponential backoff until it succeeds, returns a Permanent error, or a limit is reached. The return type is generic, so the operation can hand back a string, a response, or anything else alongside its error.
Error classification is the part worth understanding before you write the operation. Any ordinary error is treated as transient and retried. Wrapping an error in backoff.Permanent marks it non-retriable: Retry stops immediately and returns a *RetryError whose Cause is ErrPermanent and whose LastErr is the original error. The README's HTTP example uses exactly this split, retrying 5xx responses and stopping on 4xx with the comment that client errors won't fix themselves.
On failure, Retry always returns a *RetryError, which carries LastErr and Cause. You can branch on it with errors.Is against ErrPermanent, context.Canceled, context.DeadlineExceeded, ErrMaxElapsedTime and ErrExhausted, or reach the struct with AsRetryError to log LastErr regardless of the cause.
Bounding total time is where the design has a sharp edge. Two limits exist and they behave differently. A context deadline is reactive: it interrupts the wait between attempts and, if your operation observes the context, can abort an in-flight attempt; Retry reports it as context.DeadlineExceeded. WithMaxElapsedTime bounds only retry scheduling, is checked between attempts, never interrupts a running operation, and is reported as ErrMaxElapsedTime. It defaults to 15 minutes, so both limits are active unless you override the default. That default is easy to forget, and an operation that blocks for an hour will not be stopped by it.
Installing cenkalti/backoff v7 and a first retry loop
The module path carries the major version, and the README is explicit that the /v7 suffix is part of the import path. The go.mod in the repository declares module github.com/cenkalti/backoff/v7 and requires Go 1.23.
go get github.com/cenkalti/backoff/v7After that command, the import path in your source is the same string. The README notes the /v7 at the end, and it is the most common way to get this wrong, since a plain github.com/cenkalti/backoff resolves to an older major version.
The smallest useful program wraps an operation in Retry and caps the number of attempts with WithMaxTries. The README gives this shape, retrying an HTTP GET and stopping on 4xx:
result, err := backoff.Retry(ctx, func() (string, error) {
resp, err := http.Get("https://www.example.com")
if err != nil {
return "", err // transient: Retry will try again
}
defer resp.Body.Close()
switch {
case resp.StatusCode >= 500:
return "", fmt.Errorf("server error: %s", resp.Status) // retried
case resp.StatusCode >= 400:
return "", backoff.Permanent(fmt.Errorf("client error: %s", resp.Status))
}
return "ok", nil
}, backoff.WithMaxTries(5))Run it against an endpoint that returns 200 and you get "ok" with a nil error on the first attempt. Point it at something returning 404 and the Permanent wrapper stops the loop at once; branch on errors.Is(err, backoff.ErrPermanent) to tell that apart from a budget running out. The package docs list the available options as WithBackOff, WithMaxTries, WithMaxElapsedTime and WithNotify, and example_test.go in the repository holds a fuller example. If Retry does not fit, the README suggests copying it from retry.go and adapting it, which is a reasonable invitation given the file is small and MIT-licensed.
Where the library stops: no jitter, no circuit breaker, no retry budget shared across services
The clearest limitation is the one the README leaves open. It does not document jitter. Multiple clients that start failing at the same moment and back off on the same schedule will retry in step, and nothing in the described API spreads those attempts out. If you need randomized backoff, you are either supplying your own BackOff implementation through WithBackOff or copying retry.go and adapting it.
The second limit is scope. This is a retry loop, not a resilience layer. There is no circuit breaker, no bulkhead, no fallback chain, and no cross-process coordination. A service that is genuinely down will still receive attempts from every caller until each one exhausts its own budget.
The third is the interaction between the two time limits. Because WithMaxElapsedTime is checked between attempts and never interrupts a running operation, a single attempt that hangs can outlive the budget. The context deadline is the only one of the two that can cut an in-flight attempt short, and only if the operation actually observes the context. If your operation ignores ctx, neither limit protects you from a blocked call.
Finally, the maintenance posture is deliberate rather than accidental. The last push to the repository was on 2026-06-30. The contributing section states that changes which are not a common use case will probably not be accepted. That is a reasonable stance for a library this size, but it means a feature you need may have to live in your own copy of retry.go rather than upstream.
How it compares to a general retry library
The obvious alternative in the Go ecosystem is a general-purpose retry library, of which avast/retry-go is the usual comparison. The difference is in what each one considers its job. retry-go is built around configurable retry policies: you assemble delays, attempt counts, jitter and callbacks as options on a single call, and the package is designed to be extended. cenkalti/backoff is a port of one specific algorithm from a specific Java client library, and the README frames the API around that algorithm plus a small set of bounding options.
That shows up in the error model. cenkalti/backoff asks you to classify each error as transient or Permanent at the point where it is produced, and returns a *RetryError carrying both LastErr and Cause so the caller can distinguish an exhausted budget from a context cancellation. A policy-heavy library tends to expose retry decisions as configuration rather than as an error type you inspect. Neither approach is wrong; the first keeps the decision close to the code that knows whether a 404 is fixable, the second keeps it in one place for the whole program.
Outside Go, the comparison is even starker. The Python backoff package and the equivalent npm packages are separate ecosystems with their own APIs, and nothing here is shared with them. If your architecture spans languages, this library solves the Go side only, and you will be reimplementing the same policy elsewhere.
Maintenance, versioning and the MIT licence
The repository is not archived, and the last push was on 2026-06-30. The repository has no published GitHub releases, so version discovery goes through the module path rather than release notes. The /v7 suffix is Go's semantic import versioning at work: v7 is a distinct module, and upgrading from an earlier major version means changing the import path in every file that uses it, not just bumping a version in go.mod. That is the real upgrade cost here, and it is a one-time mechanical edit rather than a behavioural migration.
The licence is MIT, which is permissive and imposes essentially no conditions beyond keeping the copyright notice. That matters if you take the README's advice and copy retry.go into your own tree to adapt it; the licence permits it. This is not legal advice, and if your organisation has a policy on vendored code or attribution, check it against the LICENSE file in the repository rather than against this paragraph.
The go.mod requires Go 1.23, so the practical floor for adoption is a toolchain at or above that version. On a codebase pinned to an older Go release, that requirement, not the retry logic, is what will block you.
Editorial conclusion
Adopt cenkalti/backoff if you are writing Go and want a small, MIT-licensed retry loop with exponential backoff, a Permanent error escape hatch, and explicit try and elapsed-time budgets. Do not adopt it if you need jitter, circuit breaking, or a retry policy shared across languages; the README does not document jitter, and the author states he wants to keep the library as small as possible. Before wiring it in, verify two things in your own code: that your operation observes the context you pass to Retry, since WithMaxElapsedTime is only checked between attempts, and that you have decided whether the 15-minute default budget is right for your call site or whether you need backoff.WithMaxElapsedTime(0).
Frequently asked questions
What does "retry with backoff" mean in cenkalti/backoff?
It means the operation is run again after a delay that grows exponentially, so retries increase and stop increasing once a threshold is met, as the README describes the algorithm. In this library, Retry runs the operation at least once and keeps retrying until it succeeds, returns a Permanent error, or a limit is reached.
Does cenkalti/backoff support jitter?
The README does not document jitter. The available options it lists are WithBackOff, WithMaxTries, WithMaxElapsedTime and WithNotify, so randomized delays would have to come from your own BackOff implementation passed through WithBackOff.
How do I install cenkalti/backoff in a Go project?
Run go get github.com/cenkalti/backoff/v7. The README notes the /v7 at the end of the import path, and the module's go.mod requires Go 1.23.
How do I stop cenkalti/backoff from retrying an error?
Wrap the error in backoff.Permanent before returning it from your operation. Retry then stops immediately and returns a *RetryError whose Cause is ErrPermanent and whose LastErr is the error you wrapped.
What is the difference between a context deadline and WithMaxElapsedTime in cenkalti/backoff?
A context deadline is reactive: it interrupts the wait between attempts and can abort an in-flight attempt if the operation observes the context, and it is reported as context.DeadlineExceeded. WithMaxElapsedTime bounds only retry scheduling, is checked between attempts, never interrupts a running operation, and is reported as ErrMaxElapsedTime.
Does cenkalti/backoff have a default time limit?
Yes. WithMaxElapsedTime defaults to 15 minutes, so both the context deadline and the elapsed-time budget are active unless you override it. Pass backoff.WithMaxElapsedTime(0) to rely solely on the context.
Official sources
Add this badge to your README
If you maintain this project, the badge below links readers to this analysis and shows its maintenance status from the daily GitHub snapshot. Paste the markdown into your README; add ?metric=license or ?metric=stars to the image URL for a different field.
[](https://hysenlabs.com/projects/cenkalti-backoff)Star history chart for your README
[](https://hysenlabs.com/projects/cenkalti-backoff)Was this useful?