Bulkhead
Bulkhead Pattern, Bulkhead Pattern
A resilience pattern for distributed systems that, like a ship's bulkhead, isolates system resources so that a failure in one part does not spread to the entire system.
Bulkhead Pattern, Bulkhead Pattern
A resilience pattern for distributed systems that, like a ship's bulkhead, isolates system resources so that a failure in one part does not spread to the entire system.
The name of the Bulkhead pattern comes from ship design. A ship is divided into multiple compartments by bulkheads so that even if one compartment fills with water, flooding does not spread to the other compartments. In software, the same principle is applied to isolate resources (thread pools, connection pools, memory, etc.).
There are two main types of implementation approaches. First, thread pool isolation allocates a separate thread pool to each service call. Even if external API A slows down, the threads used for calling API B are not affected. Second, semaphore isolation limits the number of concurrent executions. It is lighter, but timeout control is difficult.
Taking an application scenario as an example, suppose a payment service calls three external systems (PG company A, PG company B, and a points system). If PG company A causes response delays, only its thread pool is affected, and calls to PG company B and the points system operate normally.
The difference from Circuit Breaker is as follows. Bulkhead focuses on "resource isolation," while Circuit Breaker focuses on "failure detection and fail-fast." In practice, the two patterns are used together to achieve stronger resilience.
Netflix's Hystrix popularized the Bulkhead pattern, and Resilience4j is now the standard in the Java ecosystem. Spring Cloud, Kubernetes, Istio, and others also support Bulkhead in various forms.
// Bulkhead 패턴 예제 - Java + Resilience4j
import io.github.resilience4j.bulkhead.*;
import io.github.resilience4j.bulkhead.ThreadPoolBulkhead;
import java.util.concurrent.CompletableFuture;
import java.time.Duration;
public class PaymentService {
// 스레드 풀 Bulkhead - PG사 A 전용
private final ThreadPoolBulkhead pgABulkhead = ThreadPoolBulkhead.of(
"pgA-bulkhead",
ThreadPoolBulkheadConfig.custom()
.maxThreadPoolSize(10) // 최대 10개 스레드
.coreThreadPoolSize(5) // 기본 5개 스레드
.queueCapacity(20) // 대기열 20개
.keepAliveDuration(Duration.ofSeconds(30))
.build()
);
// 스레드 풀 Bulkhead - PG사 B 전용
private final ThreadPoolBulkhead pgBBulkhead = ThreadPoolBulkhead.of(
"pgB-bulkhead",
ThreadPoolBulkheadConfig.custom()
.maxThreadPoolSize(10)
.coreThreadPoolSize(5)
.queueCapacity(20)
.build()
);
// 세마포어 Bulkhead - 포인트 시스템 전용
private final Bulkhead pointsBulkhead = Bulkhead.of(
"points-bulkhead",
BulkheadConfig.custom()
.maxConcurrentCalls(15) // 동시 15개 호출 제한
.maxWaitDuration(Duration.ofMillis(500)) // 500ms 대기
.build()
);
/**
* PG사 A 결제 - 스레드 풀 격리
* PG사 A가 느려져도 다른 결제 수단에 영향 없음
*/
public CompletableFuture payWithPgA(PaymentRequest request) {
return pgABulkhead.executeSupplier(() -> {
// PG사 A API 호출
return callPgAApi(request);
});
}
/**
* PG사 B 결제 - 별도 스레드 풀
*/
public CompletableFuture payWithPgB(PaymentRequest request) {
return pgBBulkhead.executeSupplier(() -> {
return callPgBApi(request);
});
}
/**
* 포인트 사용 - 세마포어 격리
* 더 가볍고 빠르지만 타임아웃 제어 어려움
*/
public PointResult usePoints(String userId, int points) {
return Bulkhead.decorateSupplier(pointsBulkhead, () -> {
return callPointsApi(userId, points);
}).get();
}
/**
* 모니터링 - Bulkhead 상태 확인
*/
public void printBulkheadMetrics() {
// 스레드 풀 Bulkhead 메트릭
ThreadPoolBulkhead.Metrics tpMetrics = pgABulkhead.getMetrics();
System.out.println("PG-A Bulkhead:");
System.out.println(" - Available: " + tpMetrics.getRemainingQueueCapacity());
System.out.println(" - Active: " + tpMetrics.getActiveThreadCount());
// 세마포어 Bulkhead 메트릭
Bulkhead.Metrics semMetrics = pointsBulkhead.getMetrics();
System.out.println("Points Bulkhead:");
System.out.println(" - Available: " + semMetrics.getAvailableConcurrentCalls());
System.out.println(" - Max: " + semMetrics.getMaxAllowedConcurrentCalls());
}
private PaymentResult callPgAApi(PaymentRequest req) { /* API 호출 */ }
private PaymentResult callPgBApi(PaymentRequest req) { /* API 호출 */ }
private PointResult callPointsApi(String userId, int points) { /* API 호출 */ }
}
// Spring Boot + Resilience4j 어노테이션 방식
@Service
public class OrderService {
@Bulkhead(name = "inventory", type = Bulkhead.Type.THREADPOOL)
public CompletableFuture checkInventory(String productId) {
return CompletableFuture.supplyAsync(() -> {
return inventoryClient.getStock(productId);
});
}
@Bulkhead(name = "shipping", type = Bulkhead.Type.SEMAPHORE,
fallbackMethod = "shippingFallback")
public ShippingCost calculateShipping(Address address) {
return shippingClient.calculate(address);
}
// Bulkhead 가득 찼을 때 fallback
public ShippingCost shippingFallback(Address address, BulkheadFullException e) {
return ShippingCost.estimated(); // 예상 배송비 반환
}
}
# Bulkhead 패턴 예제 - Python + asyncio
import asyncio
from asyncio import Semaphore
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from typing import Callable, TypeVar, Generic
from functools import wraps
import time
T = TypeVar('T')
class BulkheadFullError(Exception):
"""Bulkhead 용량 초과 에러"""
pass
@dataclass
class BulkheadConfig:
"""Bulkhead 설정"""
max_concurrent_calls: int = 10
max_wait_time: float = 0.5 # seconds
class SemaphoreBulkhead:
"""세마포어 기반 Bulkhead"""
def __init__(self, name: str, config: BulkheadConfig = None):
self.name = name
self.config = config or BulkheadConfig()
self._semaphore = Semaphore(self.config.max_concurrent_calls)
self._active_calls = 0
async def execute(self, func: Callable, *args, **kwargs):
"""Bulkhead로 보호된 함수 실행"""
try:
# 대기 시간 내에 세마포어 획득 시도
acquired = await asyncio.wait_for(
self._semaphore.acquire(),
timeout=self.config.max_wait_time
)
except asyncio.TimeoutError:
raise BulkheadFullError(
f"Bulkhead '{self.name}' full. "
f"Max concurrent: {self.config.max_concurrent_calls}"
)
self._active_calls += 1
try:
if asyncio.iscoroutinefunction(func):
return await func(*args, **kwargs)
else:
return func(*args, **kwargs)
finally:
self._active_calls -= 1
self._semaphore.release()
@property
def metrics(self):
return {
"active_calls": self._active_calls,
"available": self.config.max_concurrent_calls - self._active_calls,
"max_concurrent": self.config.max_concurrent_calls
}
class ThreadPoolBulkhead:
"""스레드 풀 기반 Bulkhead"""
def __init__(self, name: str, max_workers: int = 10, queue_size: int = 20):
self.name = name
self.max_workers = max_workers
self.queue_size = queue_size
self._executor = ThreadPoolExecutor(
max_workers=max_workers,
thread_name_prefix=f"bulkhead-{name}"
)
self._queue_semaphore = Semaphore(queue_size)
async def execute(self, func: Callable, *args, **kwargs):
"""스레드 풀에서 함수 실행"""
if not self._queue_semaphore.locked() or self._queue_semaphore._value > 0:
await self._queue_semaphore.acquire()
try:
loop = asyncio.get_event_loop()
return await loop.run_in_executor(
self._executor,
lambda: func(*args, **kwargs)
)
finally:
self._queue_semaphore.release()
else:
raise BulkheadFullError(f"Bulkhead '{self.name}' queue full")
def bulkhead(bulkhead_instance):
"""Bulkhead 데코레이터"""
def decorator(func):
@wraps(func)
async def wrapper(*args, **kwargs):
return await bulkhead_instance.execute(func, *args, **kwargs)
return wrapper
return decorator
# 사용 예시
class PaymentService:
"""결제 서비스 - 외부 시스템별 Bulkhead 적용"""
def __init__(self):
# PG사별 격리된 Bulkhead
self.pg_a_bulkhead = SemaphoreBulkhead(
"pg-a",
BulkheadConfig(max_concurrent_calls=10, max_wait_time=0.5)
)
self.pg_b_bulkhead = SemaphoreBulkhead(
"pg-b",
BulkheadConfig(max_concurrent_calls=10, max_wait_time=0.5)
)
self.points_bulkhead = SemaphoreBulkhead(
"points",
BulkheadConfig(max_concurrent_calls=15, max_wait_time=0.3)
)
async def pay_with_pg_a(self, order_id: str, amount: int):
"""PG사 A 결제 - 별도 Bulkhead"""
return await self.pg_a_bulkhead.execute(
self._call_pg_a_api, order_id, amount
)
async def pay_with_pg_b(self, order_id: str, amount: int):
"""PG사 B 결제 - 별도 Bulkhead"""
return await self.pg_b_bulkhead.execute(
self._call_pg_b_api, order_id, amount
)
async def use_points(self, user_id: str, points: int):
"""포인트 사용 - 별도 Bulkhead"""
try:
return await self.points_bulkhead.execute(
self._call_points_api, user_id, points
)
except BulkheadFullError:
# Fallback: 포인트 사용 실패해도 결제는 진행
print(f"Points bulkhead full, skipping points for {user_id}")
return {"success": False, "reason": "bulkhead_full"}
async def _call_pg_a_api(self, order_id: str, amount: int):
await asyncio.sleep(0.1) # API 호출 시뮬레이션
return {"pg": "A", "order_id": order_id, "status": "success"}
async def _call_pg_b_api(self, order_id: str, amount: int):
await asyncio.sleep(0.1)
return {"pg": "B", "order_id": order_id, "status": "success"}
async def _call_points_api(self, user_id: str, points: int):
await asyncio.sleep(0.05)
return {"user_id": user_id, "points_used": points}
def print_metrics(self):
"""Bulkhead 메트릭 출력"""
print(f"PG-A: {self.pg_a_bulkhead.metrics}")
print(f"PG-B: {self.pg_b_bulkhead.metrics}")
print(f"Points: {self.points_bulkhead.metrics}")
# 테스트
async def main():
service = PaymentService()
# 동시에 여러 결제 요청 (PG-A만 과부하)
tasks = []
for i in range(20):
tasks.append(service.pay_with_pg_a(f"order-{i}", 10000))
# PG-A가 느려져도 PG-B는 정상 동작
tasks.append(service.pay_with_pg_b("order-special", 50000))
results = await asyncio.gather(*tasks, return_exceptions=True)
# 결과 확인
success = sum(1 for r in results if not isinstance(r, Exception))
failed = sum(1 for r in results if isinstance(r, BulkheadFullError))
print(f"Success: {success}, Bulkhead Full: {failed}")
service.print_metrics()
if __name__ == "__main__":
asyncio.run(main())
// Bulkhead 패턴 예제 - Go
package main
import (
"context"
"errors"
"fmt"
"sync"
"sync/atomic"
"time"
)
var ErrBulkheadFull = errors.New("bulkhead is full")
// BulkheadConfig 설정
type BulkheadConfig struct {
MaxConcurrent int
MaxWaitTime time.Duration
}
// Bulkhead 세마포어 기반 격벽
type Bulkhead struct {
name string
config BulkheadConfig
semaphore chan struct{}
activeCalls int64
}
// NewBulkhead 생성자
func NewBulkhead(name string, config BulkheadConfig) *Bulkhead {
return &Bulkhead{
name: name,
config: config,
semaphore: make(chan struct{}, config.MaxConcurrent),
}
}
// Execute Bulkhead로 보호된 함수 실행
func (b *Bulkhead) Execute(ctx context.Context, fn func() (interface{}, error)) (interface{}, error) {
// 타임아웃 컨텍스트
waitCtx, cancel := context.WithTimeout(ctx, b.config.MaxWaitTime)
defer cancel()
// 세마포어 획득 시도
select {
case b.semaphore <- struct{}{}:
// 획득 성공
atomic.AddInt64(&b.activeCalls, 1)
defer func() {
atomic.AddInt64(&b.activeCalls, -1)
<-b.semaphore
}()
return fn()
case <-waitCtx.Done():
// 타임아웃 - Bulkhead 가득 참
return nil, fmt.Errorf("%w: %s (max: %d)",
ErrBulkheadFull, b.name, b.config.MaxConcurrent)
}
}
// Metrics 현재 상태
func (b *Bulkhead) Metrics() map[string]int64 {
active := atomic.LoadInt64(&b.activeCalls)
return map[string]int64{
"active": active,
"available": int64(b.config.MaxConcurrent) - active,
"max": int64(b.config.MaxConcurrent),
}
}
// PaymentService 결제 서비스
type PaymentService struct {
pgABulkhead *Bulkhead
pgBBulkhead *Bulkhead
pointsBulkhead *Bulkhead
}
// NewPaymentService 생성자
func NewPaymentService() *PaymentService {
return &PaymentService{
pgABulkhead: NewBulkhead("pg-a", BulkheadConfig{
MaxConcurrent: 10,
MaxWaitTime: 500 * time.Millisecond,
}),
pgBBulkhead: NewBulkhead("pg-b", BulkheadConfig{
MaxConcurrent: 10,
MaxWaitTime: 500 * time.Millisecond,
}),
pointsBulkhead: NewBulkhead("points", BulkheadConfig{
MaxConcurrent: 15,
MaxWaitTime: 300 * time.Millisecond,
}),
}
}
// PayWithPgA PG사 A 결제
func (s *PaymentService) PayWithPgA(ctx context.Context, orderID string, amount int) (string, error) {
result, err := s.pgABulkhead.Execute(ctx, func() (interface{}, error) {
// PG사 A API 호출 시뮬레이션
time.Sleep(100 * time.Millisecond)
return fmt.Sprintf("PG-A: %s paid %d", orderID, amount), nil
})
if err != nil {
return "", err
}
return result.(string), nil
}
// PayWithPgB PG사 B 결제
func (s *PaymentService) PayWithPgB(ctx context.Context, orderID string, amount int) (string, error) {
result, err := s.pgBBulkhead.Execute(ctx, func() (interface{}, error) {
time.Sleep(100 * time.Millisecond)
return fmt.Sprintf("PG-B: %s paid %d", orderID, amount), nil
})
if err != nil {
return "", err
}
return result.(string), nil
}
// UsePoints 포인트 사용
func (s *PaymentService) UsePoints(ctx context.Context, userID string, points int) (string, error) {
result, err := s.pointsBulkhead.Execute(ctx, func() (interface{}, error) {
time.Sleep(50 * time.Millisecond)
return fmt.Sprintf("Points: %s used %d", userID, points), nil
})
if err != nil {
// Fallback: 포인트 실패해도 계속 진행
if errors.Is(err, ErrBulkheadFull) {
return "points_skipped", nil
}
return "", err
}
return result.(string), nil
}
// PrintMetrics 메트릭 출력
func (s *PaymentService) PrintMetrics() {
fmt.Printf("PG-A Bulkhead: %v\n", s.pgABulkhead.Metrics())
fmt.Printf("PG-B Bulkhead: %v\n", s.pgBBulkhead.Metrics())
fmt.Printf("Points Bulkhead: %v\n", s.pointsBulkhead.Metrics())
}
func main() {
service := NewPaymentService()
ctx := context.Background()
var wg sync.WaitGroup
var successCount, failCount int64
// PG-A에 20개 동시 요청 (Max 10개이므로 일부 실패)
for i := 0; i < 20; i++ {
wg.Add(1)
go func(orderNum int) {
defer wg.Done()
orderID := fmt.Sprintf("order-%d", orderNum)
_, err := service.PayWithPgA(ctx, orderID, 10000)
if err != nil {
atomic.AddInt64(&failCount, 1)
fmt.Printf("Failed: %s - %v\n", orderID, err)
} else {
atomic.AddInt64(&successCount, 1)
}
}(i)
}
// PG-B는 별도 Bulkhead이므로 영향 없음
wg.Add(1)
go func() {
defer wg.Done()
result, _ := service.PayWithPgB(ctx, "special-order", 50000)
fmt.Printf("PG-B Result: %s\n", result)
}()
wg.Wait()
fmt.Printf("\n=== Results ===\n")
fmt.Printf("Success: %d, Failed: %d\n", successCount, failCount)
service.PrintMetrics()
}
"The reason our entire payment system stopped during yesterday's PG company A outage is that we had no Bulkhead. All external calls shared the same thread pool, so as PG company A requests piled up, other payment methods were affected too. We need to apply the Bulkhead pattern, which separates the thread pool for each PG company."
"Circuit Breaker alone is not enough. Until the circuit opens, the slow service keeps occupying threads. We need a combination: isolate resources with Bulkhead, and detect failures with Circuit Breaker to fail fast. You can easily apply both in Resilience4j."
"Bulkhead size configuration is important. If it is too small, even normal traffic gets rejected, and if it is too large, there is no isolation effect. You need to apply Little's Law based on each service's average response time and expected traffic to calculate an appropriate pool size."
If the Bulkhead capacity is too small, even normal traffic is rejected. Set it by considering the expected number of concurrent calls, the average response time, and peak traffic.
If you do not monitor Bulkhead metrics, you will not notice a capacity shortage. Display the number of active calls, the rejection rate, and the wait time on a dashboard.
If you create a thread pool for every service, the total number of threads explodes. Group them by importance and SLA, and also consider the semaphore approach.
Use together with Circuit Breaker, implement an appropriate Fallback, adjust dynamically based on metrics, and choose between thread pool and semaphore approaches to suit the situation.