---
title: "Circuit Breaking"
description: "Stop hammering a failing downstream: open the circuit, fail fast, and probe before resuming."
---

> Documentation Index
> Fetch the complete documentation index at: https://codex.mirio.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Circuit Breaking

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`](https://github.com/sony/gobreaker) is the most widely used
circuit breaker library in the Go ecosystem:

```bash
go get github.com/sony/gobreaker/v2
```

```go
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`:

```go
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.

:::tip
Wrap the circuit breaker with your [retry logic](https://codex.mirio.dev/reliability/retries/), not inside it.
The retry loop should see `ErrOpenState` as non-retryable and bail immediately,
using the `permanent` marker from the retry helper:

```go
err := withRetry(ctx, 3, func() error {
  _, err := getUser(ctx, id)
  if errors.Is(err, gobreaker.ErrOpenState) {
      return permanent(err) // signal: do not retry
  }
  return err
})
```

:::

## 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:

```rust
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:

```rust
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 */ }
}
```

:::note
This implementation allows all concurrent requests through while in half-open state, not just one
probe. For a single-probe half-open guarantee under concurrency, add an `in_flight` flag to the
`HalfOpen` variant and reject additional requests until the probe resolves.
:::

## 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 |

:::note
Each downstream service gets its own circuit breaker instance. A shared breaker across unrelated
services means a failure in one trips the breaker for all of them.
:::

Source: https://codex.mirio.dev/reliability/circuit-breaking/index.mdx
