Subscribe

Designing for failure: timeouts, retries with jitter, circuit breakers and bulkheads

Why retries turn a small outage into a big one, and how to stop it in Go: per-attempt timeouts, full-jitter backoff, a retry budget, a small circuit breaker and a bulkhead, with tests that count the calls.

Designing for failure: timeouts, retries with jitter, circuit breakers and bulkheads

Every service you call will be slow or down at some point. The question is what your service does in that minute. Without care it waits forever, retries in lockstep with every other client, and turns a small blip downstream into an outage of its own. In this blog we will look at timeouts, retries with jitter, retry budgets, circuit breakers and bulkheads, and build each one in Go with a test that counts what really happens.

Level: intermediate. I used Go 1.27.3 and only the standard library. I wrote about plain exponential backoff in Go a while back in Exponential backoff in go; this post is the bigger picture around it. The running example is shorty from Designing a URL shortener from requirements to scale.

Requirements

shorty doesn't call many other services. For this post I gave its create path one outbound call: before storing a link, ask a URL scanning service if the long URL is safe. It's a made-up dependency but a very normal one, and it's a good place to practise. What I want:

  • A slow scanner must never make POST /links hang. One second total, at most.
  • A short blip (one failed request) should be retried and invisible to the user.
  • A long outage should fail fast and not add load to the scanner while it recovers.
  • A slow scanner must not use up all goroutines and connections, redirects have to keep working.

Estimates

From the estimates post, shorty peaks at about 20 creates a second. Say the scanner takes 50 ms normally. By Little's law that is 20 * 0.05 = 1 call in flight. If the scanner hangs and we wait 30 seconds per call, it's 20 * 30 = 600 goroutines stuck, each with a connection. That one multiplication is the whole case for timeouts.

Now retries. 3 retries means up to 4 calls per request. If shorty sits behind an API gateway that retries 3 times too, and the scanner retries 3 times to its own database, a single user click can become 4 * 4 * 4 = 64 calls at the bottom. During an outage. This is how retries make outages longer.

High-level picture

   POST /links
       |
       v
  +---------+   +----------+   +-----------+   +-----------+   one attempt,   +----------+
  | handler |-->| bulkhead |-->|   retry   |-->|  breaker  |--100ms timeout-->| scanner  |
  +---------+   | 10 slots |   | 3 tries,  |   | opens on  |                  | service  |
                | reject if|   | jitter,   |   | 5 fails,  |                  +----------+
                | full     |   | budget    |   | 1 probe   |
                +----------+   +-----------+   +-----------+

The order matters. The bulkhead is outermost so a request that can't get a slot fails before it does anything. The breaker sits inside the retry loop, so every attempt is counted, and when it opens the retry loop stops straight away.

Timeouts first

A Go http.Client with no Timeout waits forever. That is the default, and it bites everyone once. I set two limits: one per attempt with a context, and one on the client as a last line of defence.

func (c *Checker) attempt(ctx context.Context, longURL string) error {
    ctx, cancel := context.WithTimeout(ctx, c.PerAttempt)
    defer cancel()
    req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.Endpoint+"?url="+url.QueryEscape(longURL), nil)
    if err != nil {
        return Permanent{err}
    }
    resp, err := c.HTTP.Do(req)
    if err != nil {
        return err // timeouts and connection errors are worth a retry
    }
    resp.Body.Close()
    switch {
    case resp.StatusCode == http.StatusOK:
        return nil
    case resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode >= 500:
        return fmt.Errorf("scanner: %s", resp.Status)
    default:
        return Permanent{fmt.Errorf("scanner: %s", resp.Status)} // 4xx: retrying won't fix it
    }
}

The Permanent wrapper is how the rest of the code knows not to retry. A 422 will be a 422 next time also.

shorty already does the same for Redis, by the way. Its client sets a 2 second dial timeout and 500 ms read and write timeouts, with a comment saying redirects must stay fast even when Redis is slow. A hung Redis just means a miss and a trip to Postgres.

Retries with full jitter

Plain exponential backoff (100 ms, 200 ms, 400 ms) has a problem when many clients fail at the same moment: they all wait exactly the same and come back together. Full jitter picks a random sleep between zero and the backoff.

type Retry struct {
    Attempts int           // total tries, including the first
    Base     time.Duration // first backoff, e.g. 100ms
    Max      time.Duration // cap per sleep, e.g. 2s
    Budget   *Budget       // nil means no budget
}

func (r Retry) backoff(n int) time.Duration {
    d := r.Base << n
    if d <= 0 || d > r.Max {
        d = r.Max
    }
    return rand.N(d + 1)
}

func (r Retry) Do(ctx context.Context, fn func(context.Context) error) error {
    if r.Budget != nil {
        r.Budget.request()
    }
    var err error
    for n := range r.Attempts {
        if err = fn(ctx); err == nil {
            return nil
        }
        if !retryable(err) || n == r.Attempts-1 {
            return err
        }
        if r.Budget != nil && !r.Budget.allowRetry() {
            return err // the downstream is struggling; don't pile on
        }
        t := time.NewTimer(r.backoff(n))
        select {
        case <-ctx.Done():
            t.Stop()
            return errors.Join(err, ctx.Err())
        case <-t.C:
        }
    }
    return err
}

func retryable(err error) bool {
    var p Permanent
    return !errors.As(err, &p) && !errors.Is(err, ErrOpen) && !errors.Is(err, ErrBulkheadFull)
}

The test makes 100 clients fail at same instant and puts their third retry sleep into 100 ms buckets:

no jitter:   map[400ms:100]
full jitter: map[0s:27 100ms:28 200ms:24 300ms:21]

All hundred at 400 ms, or spread over the whole window. The second one is what you want a recovering service to see.

Retry budgets

Jitter only spreads retries in time. It doesn't reduce them. During a real outage every request fails and every request retries, so the broken service gets four times the normal traffic right when it can least take it. A retry budget caps retries at a share of requests, here 10%.

type Budget struct {
    Ratio  float64
    Window time.Duration

    mu       sync.Mutex
    start    time.Time
    requests float64
    retries  float64
}

func (b *Budget) allowRetry() bool {
    b.mu.Lock()
    defer b.mu.Unlock()
    b.roll() // halves both counts every Window so old traffic fades out
    if b.retries+1 > b.requests*b.Ratio {
        return false
    }
    b.retries++
    return true
}

Circuit breaker

The breaker counts failures in a row. After Threshold it opens and every call fails at once with ErrOpen, without touching the network. After Cooldown it lets exactly one probe through (half-open). If the probe works it closes, if not it opens again.

func (b *Breaker) before() error {
    b.mu.Lock()
    defer b.mu.Unlock()
    switch b.state {
    case open:
        if time.Since(b.openedAt) < b.Cooldown {
            return ErrOpen
        }
        b.set(halfOpen)
        fallthrough
    case halfOpen:
        if b.probing {
            return ErrOpen // one probe at a time
        }
        b.probing = true
    }
    return nil
}

The after half (in the full code) counts a failure only for real failures. A Permanent error like a 404 means the scanner is healthy and we sent something silly, so it must not open the breaker. There is a test for exactly that, ten 404s in a row and the breaker stays closed.

The state test logs the transitions:

state changes: [closed->open open->half-open half-open->closed]

Counting the calls

This was the test I actually wrote the post for. The scanner is fully down, 1000 requests come in, and we count how many calls reach it.

no retries                    1000 calls to the broken service
4 attempts                    4000 calls to the broken service
4 attempts + 10% budget       1100 calls to the broken service
4 attempts + breaker             5 calls to the broken service

Four times the load from retries, cut back to 1.1 times by the budget (so 2,900 less calls), and to five calls by the breaker. Five looks too small at first glance. It's right. Five failures open it, and with a one minute cooldown in the test the rest fail fast with ErrOpen, which the retry loop doesn't retry.

Bulkheads

The last piece keeps one slow dependency from using up the whole service. It's a channel used as a semaphore, and it rejects instead of queueing.

func (b *Bulkhead) Do(ctx context.Context, fn func(context.Context) error) error {
    select {
    case b.slots <- struct{}{}:
    default:
        return ErrBulkheadFull // reject now instead of queueing behind a slow call
    }
    defer func() { <-b.slots }()
    return fn(ctx)
}

Against a test server that hangs for 2 seconds:

one check against a hanging scanner: Get "http://127.0.0.1:53277?url=https%3A%2F%2Fexample.com%2Fa": context deadline exceeded after 350ms (3 attempts)
50 concurrent checks, bulkhead of 10: 40 rejected straight away

Three attempts of 100 ms plus two short jittered sleeps, 350 ms total, well under the one second budget from the requirements. And 40 of 50 rejected in microseconds, while the other 10 waited for their timeouts. Redirects never go through this bulkhead at all, so they don't notice.

Running it

go vet ./...
go test -race -v ./...

Trade-offs

Failing open or failing closed is the real design decision here, and it's a product one. When the scanner is down, do we refuse new links or store them unchecked and scan later? I'd store them and re-check in a background job, but a bank would make the other choice.

A breaker per process sees only its own traffic, so with four instances each one finds out on its own. That's normally fine. Don't keep the threshold too low either, one bad deploy of yours plus a low threshold and you open the breaker on a healthy service.

And retries need idempotency. Retrying a GET is safe. Retrying a POST that timed out may run it twice, so writes need an idempotency key before you put them behind Retry.Do.