One Slow API Occupied All Workers: Testing the Bulkhead
A training model shows how a shared semaphore delays an independent fast route and how separate concurrency pools preserve space for it. We examine the mechanism, result verification, and integration boundaries for a store.

In this article
Если медленная внешняя система делит один пул конкурентных запросов с быстрым маршрутом, она может занять все места и задержать даже независимую операцию. Шаблон bulkhead — «переборка» — разделяет лимиты конкурентности: сбой или пауза в одном пуле не съедает ёмкость другого.
В учебной модели три медленные задачи занимают общий семафор на три места, поэтому быстрый вызов не завершается. После разделения на два места для медленного сервиса и одно для быстрого быстрый вызов заканчивается, пока медленные задачи ещё ждут.
Что именно изолирует bulkhead
В описании шаблона Bulkhead Microsoft предлагает отделять ресурсы зависимостей: тогда отказ одной службы не истощает общий пул и не вызывает каскадный сбой. В асинхронном коде границей может быть отдельный семафор, пул соединений или очередь воркеров.
Переборка ограничивает не число запросов за минуту, а число одновременно выполняемых операций в конкретном отсеке. Поэтому она решает другую задачу, чем ограничитель скорости, повторы и circuit breaker.
Условия безопасного примера
- Среда: CPython 3.12.14 и только стандартная библиотека.
- Один процесс и один цикл событий asyncio; Semaphore здесь не разделяется между процессами.
- Сетевых запросов, файлов, базы данных и рабочих сервисов нет.
- Три медленные корутины ждут локальный Event, поэтому пауза полностью управляется тестом.
- Сначала используется общий Semaphore(3), затем отдельные Semaphore(2) и Semaphore(1).
- После проверки код вызывает release_slow.set(), все задачи завершаются, временных данных не остаётся.
Поведение семафора сверено с документацией asyncio для Python 3.12: внутренний счётчик уменьшается при acquire, а при нуле следующая корутина ждёт освобождения. Объект не предназначен для синхронизации потоков ОС.
Полный воспроизводимый сценарий
import asyncio
async def shared_pool() -> None:
pool = asyncio.Semaphore(3)
release_slow = asyncio.Event()
slow_started: list[str] = []
async def slow(name: str) -> str:
async with pool:
slow_started.append(name)
await release_slow.wait()
return f"{name}-ok"
async def fast() -> str:
async with pool:
return "fast-ok"
slow_tasks = [
asyncio.create_task(slow(f"slow-{number}"))
for number in range(1, 4)
]
await asyncio.sleep(0)
assert slow_started == ["slow-1", "slow-2", "slow-3"]
fast_task = asyncio.create_task(fast())
await asyncio.sleep(0)
assert fast_task.done() is False
print(
"shared: "
f"slow_started={len(slow_started)} "
f"fast_done={fast_task.done()}"
)
release_slow.set()
await asyncio.gather(*slow_tasks)
assert await fast_task == "fast-ok"
async def isolated_pools() -> None:
slow_pool = asyncio.Semaphore(2)
fast_pool = asyncio.Semaphore(1)
release_slow = asyncio.Event()
slow_started: list[str] = []
async def slow(name: str) -> str:
async with slow_pool:
slow_started.append(name)
await release_slow.wait()
return f"{name}-ok"
async def fast() -> str:
async with fast_pool:
return "fast-ok"
slow_tasks = [
asyncio.create_task(slow(f"slow-{number}"))
for number in range(1, 4)
]
fast_task = asyncio.create_task(fast())
await asyncio.sleep(0)
await asyncio.sleep(0)
assert slow_started == ["slow-1", "slow-2"]
assert fast_task.done() is True
assert fast_task.result() == "fast-ok"
print(
"isolated: "
f"slow_started={len(slow_started)} "
f"fast_done={fast_task.done()} "
f"fast_result={fast_task.result()}"
)
release_slow.set()
assert await asyncio.gather(*slow_tasks) == [
"slow-1-ok",
"slow-2-ok",
"slow-3-ok",
]
async def main() -> None:
await shared_pool()
await isolated_pools()
asyncio.run(main())
Сохраните код в новом пустом каталоге как bulkhead_lab.py. Скрипт ничего не записывает и не удаляет; для запуска достаточно Python 3.12.
python3 bulkhead_lab.py
Наблюдаемый вывод двух последовательных запусков совпал:
shared: slow_started=3 fast_done=False
isolated: slow_started=2 fast_done=True fast_result=fast-ok
Оба запуска завершились с кодом 0. SHA-256 проверенного файла: 8c9d0a276e94e02014fb7cf5d280bebf4c30fe0736f21ada04b6fab770adbf4d.
Почему общий пул задерживает быстрый маршрут
В shared_pool все три медленные корутины успевают войти в один Semaphore(3) и останавливаются на Event. Счётчик становится равен нулю. Быстрая корутина исправна, но войти в тот же пул не может: проверка fast_done=False фиксирует именно ожидание свободного места.
В isolated_pools медленная зависимость получает два места. Третья медленная задача ждёт, зато быстрый маршрут использует собственное место и возвращает fast-ok. Это учебная проверка механизма, а не измерение производительности реального магазина.
- Общий пул на 3 места: начали работу 3 медленные задачи; быстрый маршрут остаётся незавершённым, пока код не освободит медленные задачи.
- Изолированные пулы 2 + 1: начали работу 2 медленные задачи; быстрый маршрут завершён с fast-ok.
Тут есть подвох: отдельный пул не ставит тайм-аут
Если медленная операция никогда не завершится, её отсек останется занятым. asyncio.Semaphore сам по себе не задаёт срок ожидания. Тайм-аут, отмену и обработку отказа нужно проектировать отдельно; конструкция async with освобождает место при штатном выходе и исключении из блока.
- Слишком маленький пул создаст очередь даже при исправной зависимости.
- Слишком большой пул ослабит изоляцию и может перегрузить внешний API.
- Локальный Semaphore ограничивает только один процесс; несколько процессов потребуют согласованного лимита на уровне архитектуры.
- Разделение пулов не заменяет тайм-ауты, повтор с бюджетом, circuit breaker, rate limiter и идемпотентность.
- Если два маршрута всё равно упираются в один общий лимит базы или CPU, отдельные семафоры не создадут дополнительный ресурс.
Для сравнения ролей полезны отдельные разборы: circuit breaker останавливает вызовы после серии отказов, а общий token bucket распределяет допустимую скорость между воркерами. Переборка отвечает на вопрос, кому достанутся одновременные места.
Как перенести модель в интеграцию магазина
В собственном модуле интеграции для 1С-Битрикс: Управление сайтом можно отдельно ограничить обращения, например, к расчёту доставки, ценовому сервису и CRM, если у них разные риски и бизнес-приоритеты. Это проектное решение для своей интеграции, а не заявление о встроенной функции платформы.
- Зафиксируйте редакцию и версию 1С-Битрикс, направление обмена и место выполнения кода: веб-запрос, агент, очередь или отдельный воркер.
- Для каталога различайте товар и торговое предложение, а также поля цены и остатка: их нельзя молча считать одной операцией.
- Проверьте права технического пользователя и контракт каждого внешнего API.
- На копии проекта задайте отдельные лимиты и воспроизведите медленный ответ, отказ и повторную доставку.
- Критерий результата: отказ одного внешнего сервиса не задерживает независимый маршрут сверх его собственного тайм-аута, а повтор не создаёт дубль операции.
Размеры пулов нельзя честно выбрать по одному примеру. Нужны лимиты поставщика, доступные соединения, длительность операций, допустимая очередь и наблюдение за отказами. Сначала изолируйте критичные маршруты на тестовой среде, затем меняйте значения небольшими шагами и проверяйте оба отсека — иначе перегородка получится декоративной.
If a slow external system shares a single pool of concurrent requests with a fast route, it can occupy all slots and delay even independent operations. The bulkhead pattern separates concurrency limits: a failure or pause in one pool does not consume the capacity of another.
In the training model, three slow tasks occupy a shared semaphore with three slots, so the fast call does not complete. After splitting into two slots for the slow service and one for the fast route, the fast call finishes while the slow tasks are still waiting.
What Exactly the Bulkhead Isolates
In the description of the Bulkhead template, Microsoft recommends isolating dependency resources: then a failure of one service will not exhaust the shared pool or trigger a cascade failure. In asynchronous code, the boundary can be a separate semaphore, connection pool, or worker queue.
Bulkhead limits not the number of requests per minute, but the number of operations executed simultaneously in a specific compartment. Therefore, it solves a different problem than rate limiters, retries, and circuit breakers.
Conditions for a Safe Example
- Environment: CPython 3.12.14 and the standard library only.
- One process and one asyncio event loop; the Semaphore is not shared between processes.
- There are no network requests, file operations, database access, or worker services.
- Three slow coroutines wait for a local Event, so the pause is fully controlled by the test.
- First, a shared Semaphore(3) is used, followed by individual Semaphores(2) and Semaphore(1).
- After the check, the code calls release_slow.set(), all tasks complete, and no temporary data remains.
Semaphore behavior aligns with asyncio documentation for Python 3.12: the internal counter decreases on acquire, and when it reaches zero, the next coroutine waits for release. The object is not intended for operating system thread synchronization.
Full reproducible scenario
import asyncio
async def shared_pool() -> None:
pool = asyncio.Semaphore(3)
release_slow = asyncio.Event()
slow_started: list[str] = []
async def slow(name: str) -> str:
async with pool:
slow_started.append(name)
await release_slow.wait()
return f"{name}-ok"
async def fast() -> str:
async with pool:
return "fast-ok"
slow_tasks = [
asyncio.create_task(slow(f"slow-{number}"))
for number in range(1, 4)
]
await asyncio.sleep(0)
assert slow_started == ["slow-1", "slow-2", "slow-3"]
fast_task = asyncio.create_task(fast())
await asyncio.sleep(0)
assert fast_task.done() is False
print(
"shared: "
f"slow_started={len(slow_started)} "
f"fast_done={fast_task.done()}"
)
release_slow.set()
await asyncio.gather(*slow_tasks)
assert await fast_task == "fast-ok"
async def isolated_pools() -> None:
slow_pool = asyncio.Semaphore(2)
fast_pool = asyncio.Semaphore(1)
release_slow = asyncio.Event()
slow_started: list[str] = []
async def slow(name: str) -> str:
async with slow_pool:
slow_started.append(name)
await release_slow.wait()
return f"{name}-ok"
async def fast() -> str:
async with fast_pool:
return "fast-ok"
slow_tasks = [
asyncio.create_task(slow(f"slow-{number}"))
for number in range(1, 4)
]
fast_task = asyncio.create_task(fast())
await asyncio.sleep(0)
await asyncio.sleep(0)
assert slow_started == ["slow-1", "slow-2"]
assert fast_task.done() is True
assert fast_task.result() == "fast-ok"
print(
"isolated: "
f"slow_started={len(slow_started)} "
f"fast_done={fast_task.done()} "
f"fast_result={fast_task.result()}"
)
release_slow.set()
assert await asyncio.gather(*slow_tasks) == [
"slow-1-ok",
"slow-2-ok",
"slow-3-ok",
]
async def main() -> None:
await shared_pool()
await isolated_pools()
asyncio.run(main())
Save the code in a new empty directory as bulkhead_lab.py. The script writes nothing and deletes nothing; running it requires only Python 3.12.
python3 bulkhead_lab.py
The observed output from two consecutive runs matched:
shared: slow_started=3 fast_done=False
isolated: slow_started=2 fast_done=True fast_result=fast-ok
Both runs completed with exit code 0. The SHA-256 hash of the verified file: 8c9d0a276e94e02014fb7cf5d280bebf4c30fe0736f21ada04b6fab770adbf4d.
Why a shared pool delays the fast route
In shared_pool, all three slow coroutines enter the same Semaphore(3) and stop at the Event. The counter drops to zero. The fast coroutine is functional but cannot enter the same pool: the fast_done=False check confirms it is waiting for available space.
In isolated_pools, the slow dependency gets two slots. The third slow task waits, while the fast route uses its own slot and returns fast-ok. This is a learning check of the mechanism, not a performance measurement of a real store.
- Shared pool for 3 slots: 3 slow tasks started; the fast route remains incomplete until the code releases the slow tasks.
- Isolated pools 2 + 1: 2 slow tasks started; the fast route completes with fast-ok.
There is a catch here: a separate pool does not set a timeout.
If a slow operation never completes, its section remains occupied. asyncio.Semaphore alone does not set a wait duration. Timeouts, cancellation, and failure handling must be designed separately; the async with construct releases the slot upon normal exit or when an exception occurs within the block.
- A pool that is too small creates a queue even when the dependency is healthy.
- A pool that is too large weakens isolation and may overload the external API.
- A local Semaphore limits only one process; multiple processes require a coordinated limit at the architecture level.
- Separating pools does not replace timeouts, retries with a budget, circuit breakers, rate limiters, and idempotency.
- If two routes still hit a shared database or CPU limit, separate semaphores will not create additional resources.
For comparing roles, separate analyses are useful: circuit breaker stops calls after a series of failures, while a general token bucket distributes the allowed rate among workers. Bulkhead answers the question of who gets simultaneous slots.
How to migrate the model to a store integration
In a custom integration module for 1C-Bitrix: Site Management, you can separately limit requests, for example, to delivery calculation, the pricing service, and CRM, if they have different risks and business priorities. This is a design decision for your own integration, not a statement about a built-in platform feature.
- Fix the 1C-Bitrix edition and version, the exchange direction, and the code execution location: web request, agent, queue, or separate worker.
- For the catalog, distinguish between the product and the product variant, as well as price and stock fields: they must not be silently treated as a single operation.
- Verify the technical user's permissions and the contract for each external API.
- On a project copy, set separate limits and reproduce slow responses, failures, and redelivery.
- Result criterion: a failure of one external service must not delay an independent route beyond its own timeout, and a retry must not create a duplicate operation.
Pool sizes cannot be reliably determined based on a single example. You need supplier limits, available connections, operation duration, acceptable queue depth, and failure monitoring. First, isolate critical routes in the test environment, then adjust values in small steps and verify both compartments; otherwise, the partition will be merely decorative.





Discussion 0
Share your experience and ask questions. Comments without links appear after editorial review.
No comments yet. Start the discussion.