Async Barrier Gates Staged Startup

Gate a staged startup behind a one-shot barrier: each service connects at its own speed and every continuation resumes only after all parties arrive.

TypescriptResilience

Code

typescriptsnippet
37 lines
// One-shot async barrier: parties wait at the gate until all have
// arrived, then every waiter is released together
function createBarrier(parties: number) {
  let arrived = 0;
  const gate = Promise.withResolvers<void>();
  return {
    async wait(): Promise<void> {
      arrived += 1;
      if (arrived === parties) gate.resolve();
      await gate.promise;
    },
  };
}

async function connectService(
  name: string,
  ms: number,
  barrier: { wait(): Promise<void> },
) {
  await new Promise((resolve) => setTimeout(resolve, ms));
  console.log(name, 'ready, waiting at the barrier');
  await barrier.wait();
  console.log(name, 'passed the barrier together');
}

async function main() {
  // Staged startup: stage 1 finishes only when every service is connected
  const stage = createBarrier(3);
  await Promise.all([
    connectService('auth', 20, stage),
    connectService('orders', 35, stage),
    connectService('search', 10, stage),
  ]);
  console.log('stage complete, starting next phase');
}

main();

Output

Captured from a sandboxed run of this snippet in the build pipeline.

search ready, waiting at the barrier
auth ready, waiting at the barrier
orders ready, waiting at the barrier
search passed the barrier together
auth passed the barrier together
orders passed the barrier together
stage complete, starting next phase

How it works

Everything happens inside the functions createBarrier, connectService and main.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

What comes back is a new object, not a reference to anything passed in.

Using it

Signature: function createBarrier(parties: number)

The demo output is labeled (stage complete, starting next phase); each label names the call that printed it.

The entry point wires createBarrier and connectService together — run it once and the whole demo flows.

Key statements

await new Promise((resolve) => setTimeout(resolve, ms));
await Promise.all([
  connectService('auth', 20, stage),
  connectService('orders', 35, stage),
  connectService('search', 10, stage),
]);
const gate = Promise.withResolvers<void>();

Interactive Tools for This Topic

FAQ

Does `createBarrier` modify its input?
It does not. Inputs are only read; the return value is freshly built.
What does Async Barrier Gates Staged Startup print when run?
The script runs standalone; its 1 labeled outputs include `stage complete, starting next phase`.