go
50 lines · 8 steps
Retry with exponential backoff in Go
A retry loop that re-runs an operation with capped exponential backoff, jitter, and context-aware cancellation.
Explained by
highlit
1package retry
2
3import (
4 "context"
5 "errors"
6 "math"
7 "math/rand"
8 "time"
9)
10
11type Operation func(ctx context.Context) error
12
13type Config struct {
14 MaxAttempts int
15 BaseDelay time.Duration
16 MaxDelay time.Duration
17}
18
19func Do(ctx context.Context, cfg Config, op Operation) error {
20 var lastErr error
21
22 for attempt := 0; attempt < cfg.MaxAttempts; attempt++ {
23 if err := op(ctx); err != nil {
24 lastErr = err
25 if errors.Is(err, context.Canceled) {
26 return err
27 }
28 } else {
29 return nil
30 }
31
32 if attempt == cfg.MaxAttempts-1 {
33 break
34 }
35
36 backoff := float64(cfg.BaseDelay) * math.Pow(2, float64(attempt))
37 if backoff > float64(cfg.MaxDelay) {
38 backoff = float64(cfg.MaxDelay)
39 }
40 jitter := time.Duration(rand.Int63n(int64(backoff)))
41
42 select {
43 case <-time.After(jitter):
44 case <-ctx.Done():
45 return ctx.Err()
46 }
47 }
48
49 return lastErr
50}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Exponential backoff spaces out retries so a struggling dependency gets room to recover instead of being hammered.
- 2Adding jitter and a max-delay cap prevents synchronized retry storms and unbounded waits.
- 3Threading context through every retry lets cancellation interrupt both the operation and the sleep between attempts.
Related explainers
rust
use axum::{extract::{Path, State}, http::StatusCode, Json}; use dashmap::DashMap; use serde::Serialize; use std::sync::Arc;
Request coalescing in an Axum handler
caching
concurrency
request-coalescing
Advanced
8 steps
go
package handlers import ( "net/http"
Serving embedded static meta files in Gin
embedding
static assets
http caching
Intermediate
6 steps
go
package config import ( "fmt"
A thread-safe config singleton in Go
singleton
concurrency
environment-variables
Intermediate
7 steps
go
package scheduler import ( "container/heap"
A priority job queue with Go's container/heap
priority-queue
heap
interfaces
Intermediate
9 steps
go
func UploadChunk(c *gin.Context) { uploadID := c.Param("uploadID") if !validUploadID.MatchString(uploadID) { c.JSON(http.StatusBadRequest, gin.H{"error": "invalid upload id"})
Resumable chunked uploads in Gin
file-upload
content-range
streaming
Advanced
9 steps
go
func (h *ArticleHandler) Create(c *gin.Context) { var req struct { Title string `json:"title" binding:"required"` Body string `json:"body" binding:"required"`
Handling a POST request in Gin
request binding
validation
http status codes
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/retry-with-exponential-backoff-in-go-explained-go-db41/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.