Skip to content

Circuit Breaking

Stop hammering a failing downstream: open the circuit, fail fast, and probe before resuming.

Retries are the right response to a transient failure. They are the wrong response to a downstream that is overloaded or down. When every caller retries against a struggling service, they amplify the load at exactly the wrong moment.

A circuit breaker tracks failure rate and stops sending requests entirely once a threshold is crossed. Callers get an immediate error instead of waiting for a timeout. The downstream gets breathing room to recover.

States

         failures ≥ threshold
  CLOSED ──────────────────────► OPEN
    ▲                               │
    │ probe succeeds         timeout│
    │                               ▼
    └────────────────────── HALF-OPEN
         probe fails ──────────────► OPEN
State Behavior
Closed Requests flow normally; failures are counted
Open All requests are rejected immediately; no calls reach downstream
Half-open One probe request is allowed through to test recovery

When the circuit opens, a timer starts. After the timeout, it moves to half-open and lets one request through. If that request succeeds, the circuit closes. If it fails, the circuit opens again and the timer resets.

Go

gobreaker is the most widely used circuit breaker library in the Go ecosystem:

go get github.com/sony/gobreaker/v2
import (
    "github.com/sony/gobreaker/v2"
    "net/http"
    "time"
)

var userServiceCB = gobreaker.NewCircuitBreaker[*http.Response](gobreaker.Settings{
    Name:        "user-service",
    MaxRequests: 1,                // probe requests allowed in half-open state
    Interval:    10 * time.Second, // sliding window for failure counts
    Timeout:     30 * time.Second, // time to stay open before moving to half-open

    ReadyToTrip: func(counts gobreaker.Counts) bool {
        return counts.ConsecutiveFailures >= 5
    },
    OnStateChange: func(name string, from, to gobreaker.State) {
        slog.Warn("circuit state changed",
            "circuit", name,
            "from", from.String(),
            "to", to.String(),
        )
    },
})

Wrap any downstream call with Execute:

func getUser(ctx context.Context, id string) (*User, error) {
    resp, err := userServiceCB.Execute(func() (*http.Response, error) {
        req, err := http.NewRequestWithContext(ctx, http.MethodGet,
            "https://users.internal/users/"+id, nil)
        if err != nil {
            return nil, err
        }
        r, err := httpClient.Do(req)
        if err != nil {
            return nil, err
        }
        if r.StatusCode >= 500 {
            r.Body.Close()
            return nil, fmt.Errorf("user service returned %d", r.StatusCode)
        }
        return r, nil
    })

    if err != nil {
        if errors.Is(err, gobreaker.ErrOpenState) {
            return nil, fmt.Errorf("user service unavailable: circuit open")
        }
        return nil, err
    }
    defer resp.Body.Close()

    var u User
    if err := json.NewDecoder(resp.Body).Decode(&u); err != nil {
        return nil, fmt.Errorf("decode user: %w", err)
    }
    return &u, nil
}

The 5xx check inside the closure matters: httpClient.Do returns a nil error for any HTTP status, so without it the breaker counts a downstream returning 500 on every request as a success and never opens.

gobreaker.ErrOpenState is the signal that the circuit is open and the call was rejected without ever reaching the network. Distinguish it from a real downstream error; it warrants a different log level and metric label.

Rust

There is no dominant circuit breaker crate for Rust. A state machine backed by an Arc<Mutex<_>> covers most use cases without adding a dependency:

use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

#[derive(Clone)]
pub struct CircuitBreaker {
    inner: Arc<Mutex<State>>,
    threshold: u32,
    open_duration: Duration,
}

struct State {
    consecutive_failures: u32,
    status: Status,
}

enum Status {
    Closed,
    Open { until: Instant },
    HalfOpen,
}

impl CircuitBreaker {
    pub fn new(threshold: u32, open_duration: Duration) -> Self {
        Self {
            inner: Arc::new(Mutex::new(State {
                consecutive_failures: 0,
                status: Status::Closed,
            })),
            threshold,
            open_duration,
        }
    }

    pub async fn call<F, Fut, T, E>(&self, f: F) -> Result<T, CircuitError<E>>
    where
        F: FnOnce() -> Fut,
        Fut: std::future::Future<Output = Result<T, E>>,
    {
        {
            let mut state = self.inner.lock().unwrap();
            match &state.status {
                Status::Open { until } => {
                    if Instant::now() < *until {
                        return Err(CircuitError::Open);
                    }
                    state.status = Status::HalfOpen;
                }
                _ => {}
            }
        }

        match f().await {
            Ok(val) => {
                let mut state = self.inner.lock().unwrap();
                state.consecutive_failures = 0;
                state.status = Status::Closed;
                Ok(val)
            }
            Err(e) => {
                let mut state = self.inner.lock().unwrap();
                state.consecutive_failures += 1;
                if state.consecutive_failures >= self.threshold
                    || matches!(state.status, Status::HalfOpen)
                {
                    state.status = Status::Open {
                        until: Instant::now() + self.open_duration,
                    };
                }
                Err(CircuitError::Inner(e))
            }
        }
    }
}

#[derive(Debug)]
pub enum CircuitError<E> {
    Open,
    Inner(E),
}

Usage:

let cb = CircuitBreaker::new(5, Duration::from_secs(30));

match cb.call(|| client.get("https://users.internal/users/42").send()).await {
    Ok(resp) => { /* handle response */ }
    Err(CircuitError::Open) => { /* fail fast: circuit is open */ }
    Err(CircuitError::Inner(e)) => { /* real downstream error */ }
}

Tuning

Parameter Starting point Notes
Failure threshold 5 consecutive Count-based is simpler than percentage-based
Open timeout 30 s Long enough to matter; short enough to self-heal
Half-open probes 1 One probe is enough to confirm recovery
Sliding window 10 s Prevents stale failures from keeping the circuit open

Type to search…

↑↓ navigate↵ selectEsc close