🏗️ Architecture

Circuit Breaker

Circuit Breaker Pattern

A core pattern for preventing failure propagation in microservice architectures. When consecutive failures reach a threshold, requests are blocked immediately, and traffic automatically resumes after the system recovers.

📖 Detailed Explanation

Circuit Breaker is a distributed system pattern inspired by electrical circuit breakers. Just as a breaker cuts the circuit to prevent a fire when excess current flows, when service calls fail repeatedly it automatically blocks requests to prevent Cascading Failure across the entire system.

It operates in three states. In the Closed state, it passes requests through normally while monitoring the failure rate. When failures exceed the threshold, it switches to the Open state and fails all requests immediately (Fail Fast). After a certain period of time, it enters the Half-Open state and uses a limited number of requests to check whether the service has recovered.

Key parameters include the Failure Threshold, Timeout, Wait Duration, and Permitted Calls in Half-Open. These values must be tuned to the characteristics of the service and its SLA.

It is used together with a Fallback strategy. When the circuit is in the Open state, graceful degradation can be implemented, such as returning cached data, providing default values, or calling an alternative service. This protects the system while maintaining the user experience.

Key implementations include Resilience4j for Java, Netflix Hystrix (currently in maintenance mode), pybreaker for Python, and opossum for Node.js. In Kubernetes environments, service meshes such as Istio and Envoy provide circuit breakers at the infrastructure level.

💻 Code Example

# Circuit Breaker 패턴 - Python + pybreaker
import pybreaker
import requests
from functools import wraps

# 서킷 브레이커 설정
payment_breaker = pybreaker.CircuitBreaker(
    fail_max=5,              # 5번 실패 시 Open
    reset_timeout=30,        # 30초 후 Half-Open
    exclude=[ValueError]     # ValueError는 실패로 카운트 안함
)

# 상태 변경 리스너
class BreakerListener(pybreaker.CircuitBreakerListener):
    def state_change(self, cb, old_state, new_state):
        print(f"🔄 Circuit Breaker 상태 변경: {old_state.name} → {new_state.name}")
        if new_state.name == "open":
            # 알림 발송 (Slack, PagerDuty 등)
            send_alert(f"결제 서비스 서킷 Open! 즉시 확인 필요")

    def failure(self, cb, exc):
        print(f"❌ 실패 감지: {exc}, 현재 실패 횟수: {cb.fail_counter}")

    def success(self, cb):
        print(f"✅ 성공, 실패 카운터 리셋")

payment_breaker.add_listener(BreakerListener())


class PaymentService:
    """결제 서비스 - Circuit Breaker 적용"""

    def __init__(self, base_url: str):
        self.base_url = base_url
        self.cache = {}  # 폴백용 캐시

    @payment_breaker
    def process_payment(self, order_id: str, amount: int) -> dict:
        """
        결제 처리 - 서킷 브레이커로 보호됨
        """
        response = requests.post(
            f"{self.base_url}/payments",
            json={"order_id": order_id, "amount": amount},
            timeout=5
        )
        response.raise_for_status()
        return response.json()

    def process_payment_with_fallback(self, order_id: str, amount: int) -> dict:
        """
        폴백이 있는 결제 처리
        """
        try:
            result = self.process_payment(order_id, amount)
            # 성공 시 캐시 갱신
            self.cache[order_id] = result
            return result

        except pybreaker.CircuitBreakerError:
            # 서킷 Open 상태 - 즉시 폴백
            print(f"⚡ 서킷 Open 상태, 폴백 실행")
            return self._fallback_payment(order_id, amount)

        except requests.exceptions.RequestException as e:
            # 네트워크 에러 - 실패로 카운트됨
            print(f"🌐 네트워크 에러: {e}")
            raise

    def _fallback_payment(self, order_id: str, amount: int) -> dict:
        """
        폴백: 결제를 큐에 저장하고 나중에 처리
        """
        pending_payment = {
            "order_id": order_id,
            "amount": amount,
            "status": "pending",
            "message": "결제 서비스 일시 불가. 잠시 후 자동 처리됩니다."
        }
        # 메시지 큐에 저장 (실제로는 Redis, RabbitMQ 등)
        self._save_to_queue(pending_payment)
        return pending_payment

    def _save_to_queue(self, payment: dict):
        print(f"📥 결제 대기열에 저장: {payment['order_id']}")


# 수동 서킷 제어 (점검 모드 등)
def maintenance_mode():
    """점검 모드 - 수동으로 서킷 열기"""
    payment_breaker.open()
    print("🔧 점검 모드: 서킷을 수동으로 열었습니다")

def resume_service():
    """서비스 재개 - 서킷 닫기"""
    payment_breaker.close()
    print("✅ 서비스 재개: 서킷을 닫았습니다")


# 사용 예시
if __name__ == "__main__":
    service = PaymentService("http://payment-api.internal")

    # 정상 결제 처리
    result = service.process_payment_with_fallback("ORDER-001", 50000)
    print(f"결제 결과: {result}")

    # 서킷 상태 확인
    print(f"현재 상태: {payment_breaker.current_state}")
    print(f"실패 횟수: {payment_breaker.fail_counter}")
// Circuit Breaker 패턴 - Node.js + opossum
const CircuitBreaker = require('opossum');
const axios = require('axios');

// 외부 서비스 호출 함수
async function callPaymentService(orderId, amount) {
    const response = await axios.post('http://payment-api/payments', {
        orderId,
        amount
    }, { timeout: 5000 });
    return response.data;
}

// Circuit Breaker 옵션 설정
const circuitOptions = {
    timeout: 5000,           // 5초 타임아웃
    errorThresholdPercentage: 50,  // 50% 실패 시 Open
    resetTimeout: 30000,     // 30초 후 Half-Open
    volumeThreshold: 10,     // 최소 10개 요청 후 판단
    rollingCountTimeout: 10000,    // 10초 윈도우
    rollingCountBuckets: 10        // 통계 버킷 수
};

// Circuit Breaker 생성
const paymentBreaker = new CircuitBreaker(callPaymentService, circuitOptions);

// 폴백 함수 등록
paymentBreaker.fallback((orderId, amount) => {
    console.log(`⚡ 폴백 실행: 결제 ${orderId}를 대기열에 저장`);
    return {
        orderId,
        amount,
        status: 'pending',
        message: '결제 서비스 일시 불가. 잠시 후 자동 처리됩니다.'
    };
});

// 이벤트 리스너
paymentBreaker.on('open', () => {
    console.log('🔴 Circuit OPEN - 결제 서비스 차단');
    // 알림 발송
    sendSlackAlert('결제 서비스 Circuit Breaker OPEN!');
});

paymentBreaker.on('halfOpen', () => {
    console.log('🟡 Circuit HALF-OPEN - 복구 테스트 중');
});

paymentBreaker.on('close', () => {
    console.log('🟢 Circuit CLOSED - 정상 운영');
});

paymentBreaker.on('fallback', (result) => {
    console.log('📥 폴백 결과:', result);
});

paymentBreaker.on('timeout', () => {
    console.log('⏰ 타임아웃 발생');
});

// 통계 모니터링
paymentBreaker.on('snapshot', (stats) => {
    console.log('📊 통계:', {
        failures: stats.failures,
        successes: stats.successes,
        fallbacks: stats.fallbacks,
        latencyMean: stats.latencyMean
    });
});


// 결제 서비스 클래스
class PaymentService {
    /**
     * 결제 처리 (Circuit Breaker 적용)
     */
    async processPayment(orderId, amount) {
        try {
            const result = await paymentBreaker.fire(orderId, amount);
            console.log(`✅ 결제 성공: ${orderId}`);
            return result;
        } catch (error) {
            console.error(`❌ 결제 실패: ${error.message}`);
            throw error;
        }
    }

    /**
     * 서킷 상태 확인
     */
    getStatus() {
        return {
            state: paymentBreaker.opened ? 'OPEN' :
                   paymentBreaker.halfOpen ? 'HALF-OPEN' : 'CLOSED',
            stats: paymentBreaker.stats
        };
    }

    /**
     * 헬스체크 엔드포인트용
     */
    isHealthy() {
        return !paymentBreaker.opened;
    }
}

// Express 라우터 예시
const express = require('express');
const router = express.Router();
const paymentService = new PaymentService();

router.post('/payments', async (req, res) => {
    const { orderId, amount } = req.body;

    try {
        const result = await paymentService.processPayment(orderId, amount);
        res.json(result);
    } catch (error) {
        res.status(503).json({
            error: 'Service temporarily unavailable',
            message: error.message
        });
    }
});

// 서킷 상태 모니터링 엔드포인트
router.get('/health/circuit', (req, res) => {
    res.json(paymentService.getStatus());
});

module.exports = { PaymentService, paymentBreaker };
// Circuit Breaker 패턴 - Java + Resilience4j
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig;
import io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry;
import io.github.resilience4j.circuitbreaker.event.CircuitBreakerOnStateTransitionEvent;
import io.vavr.control.Try;

import java.time.Duration;
import java.util.concurrent.TimeoutException;
import java.util.function.Supplier;

public class PaymentServiceWithCircuitBreaker {

    private final CircuitBreaker circuitBreaker;
    private final PaymentClient paymentClient;

    public PaymentServiceWithCircuitBreaker() {
        // Circuit Breaker 설정
        CircuitBreakerConfig config = CircuitBreakerConfig.custom()
            .failureRateThreshold(50)           // 50% 실패 시 Open
            .slowCallRateThreshold(50)          // 50% 느린 호출 시 Open
            .slowCallDurationThreshold(Duration.ofSeconds(2))  // 2초 이상 = 느린 호출
            .waitDurationInOpenState(Duration.ofSeconds(30))   // 30초 후 Half-Open
            .permittedNumberOfCallsInHalfOpenState(5)          // Half-Open에서 5개 테스트
            .minimumNumberOfCalls(10)           // 최소 10개 호출 후 판단
            .slidingWindowType(CircuitBreakerConfig.SlidingWindowType.COUNT_BASED)
            .slidingWindowSize(20)              // 최근 20개 요청 기준
            .recordExceptions(IOException.class, TimeoutException.class)  // 실패로 기록할 예외
            .ignoreExceptions(BusinessException.class)  // 무시할 예외
            .build();

        // Registry에서 Circuit Breaker 생성
        CircuitBreakerRegistry registry = CircuitBreakerRegistry.of(config);
        this.circuitBreaker = registry.circuitBreaker("paymentService");
        this.paymentClient = new PaymentClient();

        // 상태 변경 이벤트 리스너
        circuitBreaker.getEventPublisher()
            .onStateTransition(this::handleStateTransition)
            .onError(event -> log.error("Circuit Breaker 에러: {}", event.getThrowable().getMessage()))
            .onSuccess(event -> log.debug("호출 성공, 응답시간: {}ms", event.getElapsedDuration().toMillis()));
    }

    private void handleStateTransition(CircuitBreakerOnStateTransitionEvent event) {
        log.warn("🔄 Circuit Breaker 상태 변경: {} → {}",
            event.getStateTransition().getFromState(),
            event.getStateTransition().getToState());

        if (event.getStateTransition().getToState() == CircuitBreaker.State.OPEN) {
            // 알림 발송
            alertService.sendAlert("결제 서비스 Circuit Breaker OPEN!");
        }
    }

    /**
     * 결제 처리 - Circuit Breaker + 폴백
     */
    public PaymentResult processPayment(String orderId, BigDecimal amount) {
        // Circuit Breaker로 감싼 Supplier
        Supplier decoratedSupplier = CircuitBreaker
            .decorateSupplier(circuitBreaker,
                () -> paymentClient.processPayment(orderId, amount));

        // 실행 + 폴백
        return Try.ofSupplier(decoratedSupplier)
            .recover(CallNotPermittedException.class,
                ex -> fallbackPayment(orderId, amount, "Circuit Open"))
            .recover(TimeoutException.class,
                ex -> fallbackPayment(orderId, amount, "Timeout"))
            .recover(IOException.class,
                ex -> fallbackPayment(orderId, amount, "Network Error"))
            .get();
    }

    /**
     * 폴백: 결제를 큐에 저장
     */
    private PaymentResult fallbackPayment(String orderId, BigDecimal amount, String reason) {
        log.info("⚡ 폴백 실행 ({}): 결제 {}를 대기열에 저장", reason, orderId);

        // 메시지 큐에 저장
        PendingPayment pending = new PendingPayment(orderId, amount);
        messageQueue.send("pending-payments", pending);

        return PaymentResult.pending(orderId,
            "결제가 대기열에 저장되었습니다. 잠시 후 자동 처리됩니다.");
    }

    /**
     * 서킷 상태 확인
     */
    public CircuitBreakerStatus getStatus() {
        CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics();
        return new CircuitBreakerStatus(
            circuitBreaker.getState().name(),
            metrics.getFailureRate(),
            metrics.getNumberOfFailedCalls(),
            metrics.getNumberOfSuccessfulCalls(),
            metrics.getSlowCallRate()
        );
    }

    /**
     * 수동 서킷 제어 (점검 모드)
     */
    public void enableMaintenanceMode() {
        circuitBreaker.transitionToOpenState();
        log.info("🔧 점검 모드: 서킷을 수동으로 열었습니다");
    }

    public void disableMaintenanceMode() {
        circuitBreaker.transitionToClosedState();
        log.info("✅ 서비스 재개: 서킷을 닫았습니다");
    }
}

// Spring Boot 설정 (application.yml)
/*
resilience4j:
  circuitbreaker:
    instances:
      paymentService:
        register-health-indicator: true
        sliding-window-size: 20
        failure-rate-threshold: 50
        wait-duration-in-open-state: 30s
        permitted-number-of-calls-in-half-open-state: 5
        automatic-transition-from-open-to-half-open-enabled: true
*/

🗣️ Say It Like This in Practice

💬 In an incident response meeting
"We had a payment service delay, and it affected even the order service. If we apply a Circuit Breaker, when the payment service slows down, it switches to the fallback immediately, which can prevent a cascading failure in the order service. Let's configure it so that the circuit opens for 30 seconds when the failure rate is 50% or higher."
💬 In an Architecture Review
"There's no circuit breaker on the external API integration. If the third-party service becomes unstable, our entire service could slow down. Let's apply Resilience4j and add a fallback that returns cached data when the circuit is Open."
💬 In a monitoring discussion
"I've added the circuit breaker state to the Grafana dashboard. When it switches to Open, a Slack alert comes in immediately, and the success rate in Half-Open is tracked as well. We can use these metrics to measure the stability SLA of the external service."

⚠️ Cautions & Best Practices

❌
Setting an Appropriate Threshold Is Essential

If the threshold is too low, the circuit opens even on transient errors, and if it is too high, it fails to prevent failure propagation. Tune the failure rate, timeout, and sliding window to the characteristics of the service.

❌
Do Not Use a Circuit Breaker Without a Fallback

If you only return a simple error when the circuit is open, the user experience gets worse. Be sure to implement a meaningful fallback strategy, such as cached data, default values, or an alternative service.

❌
Monitoring/Alerting Integration Is Essential

If you do not monitor circuit state changes, it is hard to identify the cause of failures. Integrate Open/Close state changes, failure rate, and response time with your dashboard and alerting system.

✅
Circuit Breaker Best Practices

Configure an independent circuit per service, use it together with timeouts, provide a manual control API for maintenance mode, combine it with the Bulkhead pattern to isolate resources, and review and adjust thresholds periodically.

🔗 Related Terms

📚 Learn More