벌크헤드 패턴
느린 의존성 하나가 다른 호출의 자원까지 다 쓰지 않도록 동시 실행 칸, 연결 풀 같은 자원을 의존성마다 나누는 안정성 패턴.
· 마지막 업데이트: 2026-11-05 · 16 min read
개요
주문 서버 하나가 결제 서비스와 상품 카탈로그 서비스를 둘 다 부르는데, 외부 동시 호출 상한을 통틀어 2칸으로만 묶어 두었다고 해 보자. 어느 날 결제 서비스가 먹통이 되어 결제 요청 두 개가 그 두 칸을 붙잡고 놔주지 않으면, 뒤이어 들어온 카탈로그 조회는 정작 카탈로그 서버가 멀쩡한데도 빈칸을 얻지 못해 catalog: rejected by shared로 튕겨 나가며 결제 장애 하나에 상품 목록 화면까지 동반 침몰한다.
벌크헤드(bulkhead) 패턴은 이런 실행 자원을 의존성마다 별도 칸막이로 쪼개 놓는다. 선박 밑바닥이 뚫려도 침수를 그 구획 안에만 가두는 선체 격벽(bulkhead)에서 따온 이름으로, 결제용 2칸과 카탈로그용 2칸을 따로 갈라 두면 결제 서버가 멈춰 결제 칸이 다 차더라도 카탈로그 호출은 자기 전용 칸을 써서 평소처럼 응답한다.
이 글의 예제에서 나누는 자원은 동시 실행 칸(slot)이다. 칸 하나가 현재 진행 중인 외부 호출 하나를 뜻하고, 남은 칸 수를 세는 세마포어(semaphore)가 호출 시작 때 카운터를 하나 깎았다가 호출이 끝나면 하나를 돌려놓는데, 특정 의존성 하나에 배정된 세마포어와 대기 한도를 묶은 단위가 곧 하나의 구획(bulkhead)이다.
칸이 꽉 찼을 때 뒤따라온 호출을 어떻게 대할지도 정해야 한다. 기다리지 않고 그 자리에서 쳐내면 호출자가 즉시 실패를 인지하고 대체 화면이나 캐시 응답으로 우회할 수 있는데 이를 빠른 실패(fail fast)라 부르며, 반대로 정해진 길이의 대기열(queue)을 앞에 두면 잠깐 몰리는 요청 몇 개는 빈칸이 날 때까지 줄 서 기다리다가 대기열마저 찼을 때부터 거절당한다.
칸 대신 연결 풀(connection pool), 스레드 풀, 메시지 큐, 서비스 인스턴스를 나누기도 하고, 의존성 대신 고객(테넌트)별로 나누기도 한다. 어느 쪽이든 한 의존성이나 한 고객에게 문제가 생겨도 바닥나는 것은 그 몫의 자원뿐이다.1
구조
위 다이어그램은 확장 예제에 등장하는 타입 관계를 보여 준다. Program이 결제용과 카탈로그용 Bulkhead 인스턴스를 따로 생성하면, 각 Bulkhead는 SemaphoreSlim으로 동시 실행 칸을 세고 admitted 카운터로 실행 중·대기 중 호출의 합계를 추적하다가 두 한도가 모두 찼을 때 기다리지 않고 즉시 Rejected를 돌려준다.
역사
이름의 유래는 선박 공학이다. Microsoft Azure 아키텍처 센터는 선체가 뚫려도 물이 손상된 격벽(bulkhead) 칸에만 차올라 배 전체가 침몰하지 않는 원리에서 이름을 가져왔다고 설명하며, 애플리케이션 요소를 독립된 풀로 격리해 한쪽이 무너져도 나머지가 정상 동작하게 하는 이 구성을 셀 기반 아키텍처(cell-based architecture)라고도 부른다.2
이 패턴을 백엔드 운영 설계의 핵심으로 널리 알린 책은 Michael Nygard가 2007년 Pragmatic Bookshelf에서 펴낸 Release It!으로, 초판 5장 Stability Patterns와 2018년 1월 출간된 2판 모두 Timeouts, Circuit Breaker 바로 다음에 Bulkheads를 나란히 배치했다.34
이후 Netflix의 Hystrix가 의존성마다 별도 스레드 풀이나 세마포어를 할당해 장애 전파를 막는 방식을 채택했다.5
.NET의 Polly 역시 v7의 Policy.Bulkhead(maxParallelization, maxQueuingActions)를 거쳐 v8에서는 System.Threading.RateLimiting.ConcurrencyLimiter 기반의 AddConcurrencyLimiter(permitLimit, queueLimit) 전략(Polly.RateLimiting 패키지)으로 동시 접근 제어를 이어받았다.678 도구 이름은 바뀌어도 본질은 같다.
왜 사용하는가?
벌크헤드의 핵심 가치는 느려진 의존성 하나가 서버 전체를 끌고 들어가는 연쇄 장애(cascading failure)를 차단하는 데 있다. Microsoft Azure 아키텍처 문서는 장애를 해당 구획 안에 가두는 것, 일부 기능이 죽어도 나머지 서비스를 살려 두는 것, 그리고 중요 고객이나 핵심 경로에 전용 자원을 따로 떼어 주는 것을 주요 이점으로 꼽는다.9
빈칸이 없을 때 곧바로 거절(fail fast)하면 호출 스레드가 가망 없는 응답을 기다리며 덩달아 묶이는 일을 막고, 기본값 응답을 내줄지 나중에 재시도할지를 즉시 결정할 수 있다.
다만 벌크헤드 혼자서는 ‘이미 칸에 들어가 멈춰 있는 느린 호출’을 끌어내지 못한다! 결제 칸을 차지한 호출은 결제 서버가 답을 주거나 강제로 취소될 때까지 칸을 놓지 않으므로, 칸이 언제까지고 묶여 있지 않게 상한을 걸려면 반드시 타임아웃 패턴을 함께 물려야 하며(Hystrix 문서 역시 세마포어 격리만으로는 멈춘 호출을 시간 초과로 끊어내지 못한다고 짚는다10), 아예 죽어버린 의존성으로 호출을 보내지 않는 일은 서킷 브레이커 패턴이 맡아야 한다.11
격벽을 치면 자원을 서로 융통해 쓸 수는 없다. 결제 칸 두 개가 텅 비어 놀고 있어도 카탈로그 요청이 한꺼번에 몰리면 카탈로그 구획은 자기 칸이 모자라 요청을 거절하게 되니, 구획을 잘게 쪼갤수록 유휴 자원과 감시해야 할 설정값이 함께 늘어난다는 점을 감안해야 한다.12
프로세스 안의 세마포어는 그 프로세스 안의 호출만 나눈다. 서버 인스턴스가 여러 대면 한도는 인스턴스마다 따로 적용되고, CPU나 메모리처럼 프로세스 전체가 함께 쓰는 자원은 나뉘지 않는다. 이런 자원까지 격리하려면 서비스를 별도 가상 머신, 컨테이너, 프로세스로 나눠 배포한다.11
칸 크기와 대기열
구획 하나를 설계할 때 정할 숫자는 결국 두 개다. 동시에 돌릴 최대 호출 수(실행 칸)와 칸이 다 찼을 때 줄 세울 대기열 크기인데, 대기열을 0으로 두면 즉시 거절하고 대기열을 조금 열어 두면 짧은 순간 폭주를 흡수하는 대신 줄 서 있는 동안에도 메모리와 호출자의 응답 시간(latency)이 깎여 나가며, 만약 대기열을 무제한으로 풀어놓으면 먹통이 된 의존성 앞에 대기 작업이 끝없이 쌓여 격벽을 세운 의미가 완전히 사라진다.
칸 크기는 어떻게 정할까? 의존성이 평소에 동시에 처리하는 호출 수와 응답 시간 분포를 측정해 산정하고, 운영 중에는 구획별 점유 칸 수와 거절 횟수를 지표로 남기며(Azure 문서 역시 구획별 성능·SLA 감시와 함께 API 게이트웨이 제한이나 컨테이너 자원 한도 같은 플랫폼 격리 장치가 이미 있다면 앱 코드로 중복 구현하지 말라고 권한다),1113 참고로 Polly v8의 rate limiter 전략은 별도 리미터를 넘기지 않으면 PermitLimit = 1000, QueueLimit = 0을 기본값으로 삼아 한도 초과 시 RateLimiterRejectedException을 던진다.14
또한 ‘내 구획이 꽉 차서 들여보내지 않은 거절(Rejected)’과 ‘구획 안으로 들어가 호출했으나 상대 서버가 낸 실패(Failed)’는 반환 타입에서 분명히 갈라 주어야 한다. 전자는 호출 측 서버가 자기 자원을 지키려고 내린 로컬 결정이고 후자는 원격 서비스의 오류여서, 아래 확장 예제는 두 결과를 별도 상태로 구분해 호출자가 각기 다르게 대응할 수 있게 했다.
예제
응답을 멈춘 결제 서비스를 재현하기 위해 실제 시간 대기 대신 SetResult를 부를 때까지 완료되지 않는 TaskCompletionSource 게이트를 세우고, 칸이 없을 때 기다리지 않고 즉시 false를 반환하는 Wait(0)을 사용해 공유 구획과 분리 구획 두 시나리오에 똑같은 호출 순서를 흘려보낸다.15
using System;
using System.Threading;
using System.Threading.Tasks;
var shared = new Bulkhead("shared", 2);
await Scenario("one shared bulkhead", payments: shared, catalog: shared);
await Scenario("separate bulkheads", payments: new Bulkhead("payments", 2), catalog: new Bulkhead("catalog", 2));
static async Task Scenario(string title, Bulkhead payments, Bulkhead catalog)
{
Console.WriteLine($"== {title} ==");
// 결제 서비스가 멈춘 상황: 게이트를 열기 전까지 결제 호출은 끝나지 않는다.
var paymentGate = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);
var pay1 = payments.RunAsync(() => paymentGate.Task);
var pay2 = payments.RunAsync(() => paymentGate.Task);
Console.WriteLine("payment 3: " + await payments.RunAsync(() => paymentGate.Task));
Console.WriteLine("catalog: " + await catalog.RunAsync(() => Task.FromResult("ok")));
paymentGate.SetResult("ok");
Console.WriteLine("payment 1: " + await pay1);
Console.WriteLine("payment 2: " + await pay2);
}
sealed class Bulkhead(string name, int slots)
{
private readonly SemaphoreSlim semaphore = new(slots, slots);
public async Task<string> RunAsync(Func<Task<string>> call)
{
// 빈 칸이 없으면 기다리지 않고 바로 거절한다. 칸을 얻지 못했으니 반납할 것도 없다.
if (!semaphore.Wait(0)) return "rejected by " + name;
try
{
return await call();
}
finally
{
semaphore.Release();
}
}
}== one shared bulkhead ==
payment 3: rejected by shared
catalog: rejected by shared
payment 1: ok
payment 2: ok
== separate bulkheads ==
payment 3: rejected by payments
catalog: ok
payment 1: ok
payment 2: ok결과는 극명하다: 구획 하나를 같이 쓰면 멀쩡한 카탈로그 호출까지 거절되지만, 구획을 나누면 세 번째 결제 호출만 거절될 뿐 카탈로그는 정상 통과한다.
확장 예제
이번에는 결제 구획에 실행 칸 2개·대기열 1개를, 카탈로그 구획에 실행 칸 2개·대기열 0개를 배정해 결제 호출 네 개를 연달아 던져 보자. 처음 두 개는 즉시 실행되고 세 번째는 대기열에 들어가며 네 번째는 곧바로 Rejected를 받는데, 이어서 pay-2가 예외를 던지며 끝나면 finally 블록이 실행 칸을 반납해 대기하던 pay-3이 그 칸을 이어받아 실행된다(SemaphoreSlim은 Wait와 Release의 짝을 맞추는 책임을 개발자에게 맡기므로 실패 경로에서 반납을 빼먹으면 칸이 영구 증발해 구획 전체가 먹통이 된다).16
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
var payments = new Bulkhead("payments", maxConcurrent: 2, maxQueue: 1);
var catalog = new Bulkhead("catalog", maxConcurrent: 2, maxQueue: 0);
// 가짜 결제 게이트웨이: 호출마다 게이트가 하나 있고, 프로그램이 직접 열거나 실패시킨다.
var gates = new Dictionary<string, TaskCompletionSource<string>>();
foreach (var id in new[] { "pay-1", "pay-2", "pay-3", "pay-4", "pay-5" })
gates[id] = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);
Task<string> Pay(string id) => gates[id].Task;
var pay1 = payments.RunAsync(() => Pay("pay-1"));
var pay2 = payments.RunAsync(() => Pay("pay-2"));
var pay3 = payments.RunAsync(() => Pay("pay-3")); // 칸이 없어 대기열에서 기다린다.
var pay4 = payments.RunAsync(() => Pay("pay-4")); // 대기열도 차서 바로 거절된다.
Console.WriteLine("after 4 payment calls: " + payments.Describe());
Console.WriteLine("pay-4: " + Describe(await pay4));
Console.WriteLine("catalog-1: " + Describe(await catalog.RunAsync(() => Task.FromResult("item list"))));
gates["pay-2"].SetException(new InvalidOperationException("gateway reset"));
Console.WriteLine("pay-2: " + Describe(await pay2));
gates["pay-3"].SetResult("charged pay-3"); // pay-2가 반납한 칸으로 실행된다.
Console.WriteLine("pay-3: " + Describe(await pay3));
gates["pay-1"].SetResult("charged pay-1");
Console.WriteLine("pay-1: " + Describe(await pay1));
Console.WriteLine("after all calls: " + payments.Describe());
gates["pay-5"].SetResult("charged pay-5");
Console.WriteLine("pay-5: " + Describe(await payments.RunAsync(() => Pay("pay-5"))));
static string Describe(BulkheadResult<string> result) => result switch
{
BulkheadResult<string>.Ok ok => "ok: " + ok.Value,
BulkheadResult<string>.Rejected r => $"rejected: {r.Bulkhead} full (running {r.Running}, queued {r.Queued})",
BulkheadResult<string>.Failed f => "failed: " + f.Error.Message,
_ => "unknown result",
};
abstract record BulkheadResult<T>
{
public sealed record Ok(T Value) : BulkheadResult<T>;
public sealed record Rejected(string Bulkhead, int Running, int Queued) : BulkheadResult<T>;
public sealed record Failed(Exception Error) : BulkheadResult<T>;
}
sealed class Bulkhead(string name, int maxConcurrent, int maxQueue)
{
private readonly SemaphoreSlim slots = new(maxConcurrent, maxConcurrent);
private int admitted; // 실행 중 + 대기 중인 호출 수
public int Running => maxConcurrent - slots.CurrentCount;
public int Queued => Volatile.Read(ref admitted) - Running;
public string Describe() => $"{name} running={Running} queued={Queued}";
public async Task<BulkheadResult<T>> RunAsync<T>(Func<Task<T>> call)
{
// 실행 칸과 대기열이 모두 찼으면 기다리지 않고 거절 결과를 돌려준다.
if (Interlocked.Increment(ref admitted) > maxConcurrent + maxQueue)
{
Interlocked.Decrement(ref admitted);
return new BulkheadResult<T>.Rejected(name, Running, Queued);
}
var acquired = false;
try
{
// 칸이 없으면 대기열에서 기다린다. 대기 중 예외가 나도 아래 finally가 계수를 되돌린다.
await slots.WaitAsync();
acquired = true;
return new BulkheadResult<T>.Ok(await call());
}
catch (Exception ex)
{
// 의존성 경계: 예외를 실패 결과로 바꾼다. 형식과 스택을 잃지 않도록 예외를 그대로 담는다.
return new BulkheadResult<T>.Failed(ex);
}
finally
{
// admitted는 항상 줄이고, 칸은 실제로 얻었을 때만 반납한다.
Interlocked.Decrement(ref admitted);
if (acquired) slots.Release();
}
}
}after 4 payment calls: payments running=2 queued=1
pay-4: rejected: payments full (running 2, queued 1)
catalog-1: ok: item list
pay-2: failed: gateway reset
pay-3: ok: charged pay-3
pay-1: ok: charged pay-1
after all calls: payments running=0 queued=0
pay-5: ok: charged pay-5이 확장 예제 코드를 실제 운영에 옮길 때는 몇 가지 경계 조건을 더 챙겨야 한다. 여기서는 대기열 대기 시간에 상한이 없어 pay-3이 빈칸이 날 때까지 무기한 기다리지만, 실무에서는 WaitAsync(timeout, cancellationToken)가 돌려주는 bool을 acquired에 담아 시간 초과 시 Rejected로 빠지게 하고, finally에서는 admitted 카운터는 항상 줄이되 실제 세마포어 Release()는 acquired == true일 때만 호출해야 대기 중 취소 예외가 터져도 카운터가 새지 않는다. 또한 실행 중인 호출 자체의 타임아웃과 FIFO 대기 순서(기본 SemaphoreSlim은 순서를 보장하지 않는다17), 동시 트래픽 아래에서 근사치로 읽히는 Running/Queued 값, 그리고 단일 프로세스 내부로만 국한되는 격리 범위와 메트릭 수집까지 함께 설계해야 한다.
TypeScript 예제
첫 C# 예제와 같은 상황을 TypeScript로 옮겼다. 이 예제는 하나의 JavaScript 실행 환경 안에서 호출을 받으므로, 남은 칸 수를 담은 숫자로 동시 호출을 제한한다. async 함수는 첫 await 전까지 동기적으로 실행되므로, run이 불린 순간 칸 확인과 차감이 끝난다. 게이트는 open을 부를 때까지 끝나지 않는 Promise다.
type CallResult =
| { ok: true; value: string }
| { ok: false; error: "BULKHEAD_FULL"; bulkhead: string };
// 남은 칸 수만 세는 작은 세마포어. 기다리지 않고 바로 성공 여부를 알려 준다.
class Semaphore {
#available: number;
constructor(slots: number) { this.#available = slots; }
tryAcquire(): boolean {
if (this.#available === 0) return false;
this.#available -= 1;
return true;
}
release(): void { this.#available += 1; }
}
class Bulkhead {
readonly #slots: Semaphore;
constructor(readonly name: string, slots: number) { this.#slots = new Semaphore(slots); }
async run(call: () => Promise<string>): Promise<CallResult> {
// 칸을 얻지 못하면 거절한다. 얻지 못한 칸은 반납하지 않는다.
if (!this.#slots.tryAcquire()) return { ok: false, error: "BULKHEAD_FULL", bulkhead: this.name };
try {
return { ok: true, value: await call() };
} finally {
this.#slots.release();
}
}
}
// 직접 열 때까지 끝나지 않는 게이트. 멈춘 결제 서비스를 흉내 낸다.
function gate(): { promise: Promise<string>; open: (value: string) => void } {
let open: (value: string) => void = () => {};
const promise = new Promise<string>((resolve) => { open = resolve; });
return { promise, open };
}
function describe(result: CallResult): string {
return result.ok ? result.value : "rejected by " + result.bulkhead;
}
async function scenario(title: string, payments: Bulkhead, catalog: Bulkhead): Promise<void> {
console.log(`== ${title} ==`);
const paymentGate = gate();
const pay1 = payments.run(() => paymentGate.promise);
const pay2 = payments.run(() => paymentGate.promise);
console.log("payment 3: " + describe(await payments.run(() => paymentGate.promise)));
console.log("catalog: " + describe(await catalog.run(() => Promise.resolve("ok"))));
paymentGate.open("ok");
console.log("payment 1: " + describe(await pay1));
console.log("payment 2: " + describe(await pay2));
}
async function main(): Promise<void> {
const shared = new Bulkhead("shared", 2);
await scenario("one shared bulkhead", shared, shared);
await scenario("separate bulkheads", new Bulkhead("payments", 2), new Bulkhead("catalog", 2));
}
void main();== one shared bulkhead ==
payment 3: rejected by shared
catalog: rejected by shared
payment 1: ok
payment 2: ok
== separate bulkheads ==
payment 3: rejected by payments
catalog: ok
payment 1: ok
payment 2: ok칸을 얻지 못한 호출은 try에 들어가기 전에 돌아가므로 반납할 칸도 없다. 이 세마포어에는 대기열이 없고, 칸을 차지한 호출이 끝나지 않으면 칸도 돌아오지 않는다.
같이 보기
각주
- Microsoft Learn. Bulkhead pattern. Azure Architecture Center. Solution 절의 의존성별 연결 풀 예, Problems and considerations 절의 프로세스·스레드 풀·세마포어·큐·테넌트 분할. ↩
- Microsoft Learn. Bulkhead pattern. Azure Architecture Center. 도입부와 Tip. ↩
- Michael T. Nygard. Release It! Design and Deploy Production-Ready Software. Pragmatic Bookshelf, 2007. 출판사 목차 PDF (P3.0 인쇄본, 2009년 2월), 5.3 Bulkheads, 121쪽. ↩
- Michael Nygard. Release It! Second Edition: Design and Deploy Production-Ready Software. Pragmatic Bookshelf, 2018. 출판사 목차, Create Stability > Stability Patterns. ↩
- Netflix. How it Works. Hystrix Wiki. ↩
- Polly. Migration guide from v7 to v8. Bulkhead 절. ↩
- Polly. Rate limiter resilience strategy. ↩
- Microsoft Learn. ConcurrencyLimiter Class. ↩
- Microsoft Learn. Bulkhead pattern. Azure Architecture Center. Solution 절의 benefits 목록. ↩
- Netflix. How it Works. Hystrix Wiki. 세마포어 격리 설명. ↩
- Microsoft Learn. Bulkhead pattern. Azure Architecture Center. Problems and considerations 절. ↩
- Microsoft Learn. Bulkhead pattern. Azure Architecture Center. When to use this pattern 절. ↩
- Microsoft Learn. Bulkhead pattern. Azure Architecture Center. Problems and considerations 절의 built-in platform controls 항목. ↩
- Polly. Rate limiter resilience strategy. Defaults 표와 예외 목록. ↩
- Microsoft Learn. SemaphoreSlim.Wait Method. Wait(Int32) Remarks. ↩
- Microsoft Learn. SemaphoreSlim Class. Remarks. ↩
- Microsoft Learn. SemaphoreSlim Class. Remarks: 여러 스레드가 기다릴 때 FIFO나 LIFO 같은 순서를 보장하지 않는다. ↩