Skip to content

Concurrency limits

An event is subscribed by 800 targets. Promise.all(targets.map(send)) opens 800 connections in the same tick. The process runs out of sockets, the three slow targets get 800 requests’ worth of retries, and the fast ones time out waiting for a free connection. Nothing is wrong with any single call. The count is the bug.

The fix is a cap on how many calls are in flight. This lesson builds the cap two ways: a semaphore, and a pool that applies it to a list. Then one more for the case where each target needs its own limit.

map plus Promise.all starts everything at once, because starting a promise does not wait for the previous one:

declare const targets: readonly string[]
declare function send(target: string): Promise<number>
async function fanOut() {
return Promise.all(targets.map((t) => send(t))) // all calls start now
}
async function sequential() {
const out: number[] = []
for (const t of targets) out.push(await send(t)) // one at a time: safe, and slow
return out
}

Both ends are wrong for Relay. You want something in between: a few at a time, and a new one the moment one finishes.

A semaphore holds limit slots. acquire takes one, waiting if none is free, and gives back a function that frees it. Waiters are served in order:

class Semaphore {
#active = 0
readonly #queue: (() => void)[] = []
constructor(readonly limit: number) {}
async acquire(): Promise<() => void> {
if (this.#active < this.limit) this.#active++
else await new Promise<void>((resolve) => this.#queue.push(resolve))
return () => {
const next = this.#queue.shift()
if (next === undefined) this.#active--
else next() // pass the slot straight to the longest waiter
}
}
}

When a waiter exists, the slot is handed over without lowering #active, so no third caller can slip in between the release and the waiter waking up. The run method wraps the pair so a forgotten release cannot happen:

declare class Semaphore {
acquire(): Promise<() => void>
}
async function run<T>(sem: Semaphore, task: () => Promise<T>): Promise<T> {
const release = await sem.acquire()
try {
return await task()
} finally {
release() // also when the task throws
}
}

A slot leaked by a task that threw is a limit that shrinks until Relay stops delivering. finally is what prevents that.

mapLimit(items, n, fn) is the semaphore applied to a list: n workers share one cursor, and each takes the next item when it finishes its current one. Results go into the slot of their input index, so order does not depend on who finishes first:

async function mapLimit<T, R>(
items: readonly T[],
limit: number,
fn: (item: T, index: number) => Promise<R>,
): Promise<R[]> {
const results = new Array<R>(items.length)
const entries = items.entries() // one iterator, shared by every worker
async function worker(): Promise<void> {
for (let next = entries.next(); !next.done; next = entries.next()) {
const [index, item] = next.value
results[index] = await fn(item, index)
}
}
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker))
return results
}

R flows from fn, so mapLimit(targets, 10, send) is a Promise<number[]>. Sharing the iterator is what makes the pool safe: next() runs synchronously, so two workers can never take the same item.

A global limit of 50 can still send all 50 to one struggling target. Give each target its own semaphore, created on first use:

declare class Semaphore {
constructor(limit: number)
run<T>(task: () => Promise<T>): Promise<T>
}
class KeyedLimiter {
readonly #semaphores = new Map<string, Semaphore>()
constructor(readonly limitPerKey: number) {}
run<T>(key: string, task: () => Promise<T>): Promise<T> {
let sem = this.#semaphores.get(key)
if (sem === undefined) {
sem = new Semaphore(this.limitPerKey)
this.#semaphores.set(key, sem)
}
return sem.run(task)
}
}

Combine the two limits by nesting: mapLimit with a global cap of 50, and each call going through limiter.run(target.host, ...) with 2 per host.

Timers make a poor stopwatch here. A test that sleeps 10 ms and hopes is slow and flaky. Count instead. Each fake call bumps an inFlight counter, records the peak, and returns a promise the test resolves by hand. The test then reads the counter at every step, and the answer is exact.

Write Semaphore, mapLimit and KeyedLimiter. The tests use hand-resolved promises to check the peak concurrency, the queue order, the result order and what happens after a failure. The starter lets everything through at once.

  • Promise.all(items.map(...)) starts every call at once. Cap the number in flight.
  • A semaphore hands out limit slots. Release in finally so a throwing task does not leak one.
  • mapLimit shares one iterator between n workers and writes results by index, so order is kept.
  • Use a semaphore per key to limit each target separately.
  • Test concurrency by counting in-flight calls with hand-resolved promises, not with timers.