Circuit Breaker en C#: Guía Completa

Introducción: Protección ante fallos

Circuit Breaker evita que un servicio fallido siga recibiendo llamadas y provoque cascadas de errores.

Cuando detecta fallos repetidos, “abre el circuito” y bloquea llamadas por un tiempo.

Luego entra en estado half-open para probar si el servicio se recuperó.

Circuit Breaker
Prompt: Circuit breaker states open closed half-open, clean minimal style.

1. Naturaleza: Fusibles

Un fusible se rompe para proteger el sistema eléctrico cuando hay sobrecarga.

El Circuit Breaker cumple el mismo rol: corta el flujo para evitar daños mayores.

Fusible
Prompt: Electrical fuse breaking, soft illustration.

2. Mundo Real: Telefonía saturada

Cuando una central telefónica está saturada, bloquea nuevas llamadas y devuelve un mensaje automático.

Eso evita que el sistema colapse por completo y da tiempo para recuperarse.

Telefonía
Prompt: Telephone overload protection, clean flat style.

3. Implementación en C#: Código Paso a Paso

public class CircuitBreaker
{
    private int _failures = 0;
    private bool _open = false;

    public T Execute(Func action)
    {
        if (_open) throw new Exception("Circuit open");
        try { var result = action(); _failures = 0; return result; }
        catch { _failures++; if (_failures >= 3) _open = true; throw; }
    }
}

En producción, se manejan tiempos de espera y un estado half-open para probar recuperación.

Se combina frecuentemente con Retry para balancear resiliencia y estabilidad.

4. Circuit Breaker vs Retry

Retry intenta repetir una operación; Circuit Breaker corta cuando hay demasiados fallos.

Usa Retry para fallos transitorios y Circuit Breaker para fallos persistentes.

5. Diagrama UML

UML Circuit Breaker
Prompt: UML diagram of circuit breaker, clean vector layout.
Flujo Circuit Breaker
Prompt: Circuit breaker state transition diagram, minimal infographic style.

⚠️ Cuándo NO Usar Circuit Breaker

  • Si el servicio es local y muy estable.
  • Si la latencia de recuperación no es relevante.
  • Si no hay métricas para ajustar umbrales correctamente.

💪 Ejercicio

Implementa un Circuit Breaker con estados open, half-open y closed.

Conclusión

Circuit Breaker protege sistemas distribuidos de fallos en cascada.

Bien configurado, aumenta resiliencia sin sacrificar disponibilidad.