0Pricing
Microservices Communication Patterns (Saga, Circuit Breaker) · 강의

회로 차단기와 벌크헤드

리소스 장애를 격리하고 연쇄적인 문제를 방지하도록 회로 차단기와 벌크헤드 패턴을 결합하는 방법을 학습합니다.

회로 차단기와 벌크헤드은(는) CoddyKit의 무료 Microservices Communication Patterns (Saga, Circuit Breaker) 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Microservices Communication Patterns (Saga, Circuit Breaker) 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Microservices Communication Patterns (Saga, Circuit Breaker) 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Patterns Work Better Together

Resilience patterns like Circuit Breaker and Bulkhead are powerful on their own. But in complex microservices, combining them offers even stronger protection.

Think of it like different layers of security for your application. Each layer catches different types of threats, creating a more robust defense.

Circuit Breaker Refresher

Remember the Circuit Breaker pattern? It's like an electrical circuit for your service calls.

  • It monitors calls to a service.
  • If failures exceed a threshold, it 'opens' the circuit.
  • Once open, further calls fail immediately, preventing overload to the failing service and saving resources.
  • After a timeout, it 'half-opens' to test if the service has recovered.

Bulkhead Pattern Refresher

The Bulkhead pattern isolates resources. Imagine a ship with watertight compartments (bulkheads).

  • If one compartment floods, the others remain safe.
  • In microservices, this means separating resource pools (e.g., thread pools, connections) for different services.
  • A failure in one service's resource pool won't exhaust resources needed by other services.

Synergy: CB + Bulkhead

Why use both? They tackle different problems but complement each other perfectly.

  • Circuit Breaker: Focuses on stopping requests to a failing service.
  • Bulkhead: Focuses on isolating resources to prevent cascading failures due to resource exhaustion.

Together, they provide a comprehensive defense against various failure modes.

Bulkhead Helps Circuit Breaker

How does Bulkhead make Circuit Breaker better?

A Circuit Breaker needs to detect failures. If a service is overwhelmed (e.g., due to resource exhaustion) and all calls to it start failing slowly, it can take time for the Circuit Breaker to open.

By isolating resources, Bulkhead ensures that only a limited set of resources is consumed by a misbehaving service, preventing total exhaustion and allowing the Circuit Breaker to react more quickly and cleanly to actual service failures, rather than just resource starvation.

Circuit Breaker Helps Bulkhead

And how does Circuit Breaker enhance Bulkhead?

If a service is known to be failing (Circuit Breaker is OPEN), the Circuit Breaker will intercept requests and fail them immediately, before they even try to acquire a resource from the Bulkhead's pool.

This means the Bulkhead's limited resources are not wasted on calls destined to fail anyway, preserving them for other, potentially healthy, operations or for when the service recovers.

Real-World: Thread Pools

A common way to implement the Bulkhead pattern is using thread pools.

  • Assign a dedicated, limited thread pool to calls for a specific external service.
  • If that service is slow or unresponsive, only its dedicated threads get tied up.
  • Other services, with their own thread pools, remain unaffected.

When combined with a Circuit Breaker, the CB stops calls before they even enter the thread pool if the service is down.

Code: CB & BH in Action

This example shows how a Circuit Breaker (CB) check happens before a Bulkhead (BH) resource acquisition. If the CB is open, the call fails immediately, saving BH resources.

import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicBoolean;

public class Main {
    private static AtomicBoolean circuitOpen = new AtomicBoolean(false);
    private static long lastFailureTime = 0;
    private static final long RESET_TIMEOUT_MS = 5000;

    private static final Semaphore serviceBulkhead = new Semaphore(2);

    public static void callProtectedService(String callerId) {
        // 1. Circuit Breaker check (Fail Fast)
        if (circuitOpen.get()) {
            if (System.currentTimeMillis() - lastFailureTime > RESET_TIMEOUT_MS) {
                System.out.println(callerId + ": Circuit Half-Open. Testing service...");
                circuitOpen.set(false); // Simple reset for demo
            } else {
                System.out.println(callerId + ": CB OPEN. REJECTED!");
                return;
            }
        }

        // 2. Bulkhead check (Resource Isolation)
        boolean acquiredBulkhead = false;
        try {
            if (serviceBulkhead.tryAcquire()) {
                acquiredBulkhead = true;
                System.out.println(callerId + ": BH slot ACQUIRED. Calling...");
                Thread.sleep(200); // Simulate work

                if (callerId.equals("Call-3") || callerId.equals("Call-4")) {
                    System.out.println(callerId + ": Simulating FAILURE!");
                    circuitOpen.set(true);
                    lastFailureTime = System.currentTimeMillis();
                } else {
                    System.out.println(callerId + ": Call SUCCESS.");
                }
            } else {
                System.out.println(callerId + ": BH FULL. REJECTED!");
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            System.out.println(callerId + ": Call interrupted.");
        } finally {
            if (acquiredBulkhead) {
                serviceBulkhead.release();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        System.out.println("--- First calls (CB CLOSED) ---");
        for (int i = 1; i <= 5; i++) {
            final int callNum = i;
            new Thread(() -> callProtectedService("Call-" + callNum)).start();
            Thread.sleep(50);
        }
        Thread.sleep(1500);

        System.out.println("\n--- Second calls (CB potentially OPEN) ---");
        for (int i = 6; i <= 10; i++) {
            final int callNum = i;
            new Thread(() -> callProtectedService("Call-" + callNum)).start();
            Thread.sleep(50);
        }
        Thread.sleep(6000);

        System.out.println("\n--- Third calls (after reset) ---");
        for (int i = 11; i <= 13; i++) {
            final int callNum = i;
            new Thread(() -> callProtectedService("Call-" + callNum)).start();
            Thread.sleep(50);
        }
    }
}

Combined Benefits

Using Circuit Breaker and Bulkhead together provides:

  • Enhanced Fault Isolation: Prevents a single failing service from taking down others, both by stopping calls and by limiting resource usage.
  • Improved Resource Management: Efficiently uses available resources, rejecting calls early if a service is known to be unhealthy.
  • Faster Recovery: Allows healthy parts of the system to continue functioning, aiding overall system stability and recovery.
  • Predictable Behavior: Helps maintain predictable response times and throughput under stress.

Quick Check

Which of the following statements accurately describe the benefits of combining the Circuit Breaker and Bulkhead patterns?

Recap: Stronger Together

In this lesson, we explored the powerful combination of the Circuit Breaker and Bulkhead patterns.

  • We saw how Circuit Breaker prevents calls to failing services.
  • We revisited how Bulkhead isolates resources.
  • Most importantly, we learned how they mutually enhance each other to create a more resilient and stable microservices architecture.

Next, we'll see how Circuit Breakers can be combined with Retry Logic for even more robust error handling!

자주 묻는 질문

“회로 차단기와 벌크헤드” 강의는 무료인가요?

네 — “회로 차단기와 벌크헤드” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Microservices Communication Patterns (Saga, Circuit Breaker) 강의 전체를 잠금 해제할 수 있습니다. Microservices Communication Patterns (Saga, Circuit Breaker) 강의에는 총 4개의 강의가 포함되어 있습니다.

“회로 차단기와 벌크헤드”에서 뭘 배우나요?

리소스 장애를 격리하고 연쇄적인 문제를 방지하도록 회로 차단기와 벌크헤드 패턴을 결합하는 방법을 학습합니다. 브라우저에서 직접 실행하는 실습 코드로 Microservices Communication Patterns (Saga, Circuit Breaker)을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Microservices Communication Patterns (Saga, Circuit Breaker)을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Microservices Communication Patterns (Saga, Circuit Breaker)은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“회로 차단기와 벌크헤드” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Microservices Communication Patterns (Saga, Circuit Breaker) 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Microservices Communication Patterns (Saga, Circuit Breaker) 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 회로 차단기와 벌크헤드
  2. 재시도 로직을 적용한 회로 차단기
  3. 요청 빈도 제한 통합
  4. 복원력 데코레이터의 순서
← Microservices Communication Patterns (Saga, Circuit Breaker)(으)로 돌아가기