Counting Semaphore For Async Concurrency
A counting semaphore that bounds in-flight async tasks with FIFO fairness and a safe release path for pooled resources.
Code
export class Semaphore {
constructor(max) {
if (!Number.isInteger(max) || max < 1) throw new RangeError("max must be a positive integer");
this.max = max;
this.active = 0;
this.waiters = [];
}
get inFlight() {
return this.active;
}
async acquire() {
if (this.active < this.max) {
this.active += 1;
return this.makeRelease();
}
await new Promise((resolve) => this.waiters.push(resolve));
return this.makeRelease();
}
makeRelease() {
let released = false;
return () => {
if (released) return;
released = true;
this.active -= 1;
const next = this.waiters.shift();
if (next) {
this.active += 1;
next();
}
};
}
async run(task) {
const release = await this.acquire();
try {
return await task();
} finally {
release();
}
}
async runAll(tasks) {
return Promise.all(tasks.map((t) => this.run(t)));
}
}Promise.all over thousands of URLs exhausts sockets and gets the client throttled or OOM-killed.
Use case: engineers fanning out calls to rate limited or memory heavy endpoints
Inputs / outputs
- Input: max concurrent permits, tasks returning promises
- Output: results in input order once all tasks settle
Error conditions
- maxPermits below 1
- a task rejects (other tasks still run, error surfaces in order)
Approach
permit queue of resolvers; acquire waits on the queue when exhausted; release wakes the next waiter in FIFO order; runAll maps tasks through acquire/release.
Implementation
export class Semaphore {
constructor(max) {
if (!Number.isInteger(max) || max < 1) throw new RangeError("max must be a positive integer");
this.max = max;
this.active = 0;
this.waiters = [];
}
get inFlight() {
return this.active;
}
async acquire() {
if (this.active < this.max) {
this.active += 1;
return this.makeRelease();
}
await new Promise((resolve) => this.waiters.push(resolve));
return this.makeRelease();
}
makeRelease() {
let released = false;
return () => {
if (released) return;
released = true;
this.active -= 1;
const next = this.waiters.shift();
if (next) {
this.active += 1;
next();
}
};
}
async run(task) {
const release = await this.acquire();
try {
return await task();
} finally {
release();
}
}
async runAll(tasks) {
return Promise.all(tasks.map((t) => this.run(t)));
}
}
Verification tests
import { test } from "node:test";
import assert from "node:assert/strict";
import { Semaphore } from "./example.mjs";
test("never exceeds the permit limit", async () => {
const sem = new Semaphore(2);
let peak = 0;
const task = async () => {
peak = Math.max(peak, sem.inFlight);
await new Promise((r) => setTimeout(r, 10));
return 1;
};
await sem.runAll(Array.from({ length: 10 }, () => task));
assert.equal(peak, 2);
assert.equal(sem.inFlight, 0);
});
test("preserves input order regardless of completion order", async () => {
const sem = new Semaphore(3);
const out = await sem.runAll([
() => new Promise((r) => setTimeout(() => r("slow"), 30)),
() => Promise.resolve("fast"),
() => new Promise((r) => setTimeout(() => r("mid"), 10)),
]);
assert.deepEqual(out, ["slow", "fast", "mid"]);
});
test("releases permits when a task rejects", async () => {
const sem = new Semaphore(1);
await assert.rejects(sem.run(() => Promise.reject(new Error("boom"))));
assert.equal(sem.inFlight, 0);
const ok = await sem.run(() => Promise.resolve("recovered"));
assert.equal(ok, "recovered");
});
test("rejects invalid permit counts", () => {
assert.throws(() => new Semaphore(0), RangeError);
});
Dependencies and running
No external dependencies (standard library only).
Runtime: node >= 18 Entry point: node example.mjs
Limitations and error handling
no timeout on waiting; single process only.
Verification boundary
execution tests ran offline in an isolated temp dir with a sanitized environment; no network, no writes outside the sandbox
Report a problem with this exampleOpens a pre-filled issue on GitHub.