Bounded Async Queue With Backpressure

A bounded async queue that applies backpressure to producers when full and drains to consumers without dropping or duplicating items.

JavascriptCli Tooling

Code

export class BoundedQueue {
  constructor(capacity) {
    if (!Number.isInteger(capacity) || capacity < 1) {
      throw new RangeError("capacity must be a positive integer");
    }
    this.capacity = capacity;
    this.items = [];
    this.consumerWaiting = [];
    this.producerWaiting = [];
    this.closed = false;
  }

  get size() {
    return this.items.length;
  }

  async push(item) {
    if (this.closed) throw new Error("queue is closed");
    while (this.items.length >= this.capacity) {
      await new Promise((resolve) => this.producerWaiting.push(resolve));
      if (this.closed) throw new Error("queue is closed");
    }
    this.items.push(item);
    this.wakeConsumer();
  }

  async take() {
    while (this.items.length === 0) {
      if (this.closed) return undefined;
      await new Promise((resolve) => this.consumerWaiting.push(resolve));
    }
    const item = this.items.shift();
    this.wakeProducer();
    return item;
  }

  close() {
    this.closed = true;
    for (const resolve of this.consumerWaiting) resolve();
    for (const resolve of this.producerWaiting) resolve();
    this.consumerWaiting = [];
    this.producerWaiting = [];
  }

  async run(consumer) {
    const results = [];
    while (true) {
      const item = await this.take();
      if (item === undefined && this.closed) break;
      results.push(await consumer(item));
    }
    return results;
  }

  wakeConsumer() {
    const resolve = this.consumerWaiting.shift();
    if (resolve) resolve();
  }

  wakeProducer() {
    const resolve = this.producerWaiting.shift();
    if (resolve) resolve();
  }
}

An unbounded queue buffers every produced item until memory runs out, and an unbuffered one drops items under load.

Use case: engineers connecting fast producers to slow consumers

Inputs / outputs

  • Input: capacity, items pushed by the producer, a consumer function
  • Output: processed results in push order; producers await space when the queue is full

Error conditions

  • capacity below 1
  • consumer throws (the error propagates and the queue stops)

Approach

internal array plus resolvers for waiting producers and consumers; push resolves a waiting consumer when items exist, otherwise awaits space; close signals the end of stream.

Implementation

export class BoundedQueue {
  constructor(capacity) {
    if (!Number.isInteger(capacity) || capacity < 1) {
      throw new RangeError("capacity must be a positive integer");
    }
    this.capacity = capacity;
    this.items = [];
    this.consumerWaiting = [];
    this.producerWaiting = [];
    this.closed = false;
  }

  get size() {
    return this.items.length;
  }

  async push(item) {
    if (this.closed) throw new Error("queue is closed");
    while (this.items.length >= this.capacity) {
      await new Promise((resolve) => this.producerWaiting.push(resolve));
      if (this.closed) throw new Error("queue is closed");
    }
    this.items.push(item);
    this.wakeConsumer();
  }

  async take() {
    while (this.items.length === 0) {
      if (this.closed) return undefined;
      await new Promise((resolve) => this.consumerWaiting.push(resolve));
    }
    const item = this.items.shift();
    this.wakeProducer();
    return item;
  }

  close() {
    this.closed = true;
    for (const resolve of this.consumerWaiting) resolve();
    for (const resolve of this.producerWaiting) resolve();
    this.consumerWaiting = [];
    this.producerWaiting = [];
  }

  async run(consumer) {
    const results = [];
    while (true) {
      const item = await this.take();
      if (item === undefined && this.closed) break;
      results.push(await consumer(item));
    }
    return results;
  }

  wakeConsumer() {
    const resolve = this.consumerWaiting.shift();
    if (resolve) resolve();
  }

  wakeProducer() {
    const resolve = this.producerWaiting.shift();
    if (resolve) resolve();
  }
}

Verification tests

import { test } from "node:test";
import assert from "node:assert/strict";
import { BoundedQueue } from "./example.mjs";

test("preserves order under load", async () => {
  const queue = new BoundedQueue(3);
  const seen = [];
  const consumerDone = queue.run(async (item) => {
    await new Promise((r) => setTimeout(r, 1));
    seen.push(item);
    return item;
  });
  for (let i = 0; i < 20; i++) await queue.push(i);
  queue.close();
  await consumerDone;
  assert.deepEqual(seen, Array.from({ length: 20 }, (_, i) => i));
});

test("applies backpressure when full", async () => {
  const queue = new BoundedQueue(2);
  await queue.push("a");
  await queue.push("b");
  assert.equal(queue.size, 2);
  let resolved = false;
  const pending = queue.push("c").then(() => { resolved = true; });
  await new Promise((r) => setTimeout(r, 10));
  assert.equal(resolved, false); // blocked by backpressure
  const first = await queue.take();
  assert.equal(first, "a");
  await pending;
  assert.equal(resolved, true);
});

test("stops after close", async () => {
  const queue = new BoundedQueue(4);
  await queue.push(1);
  queue.close();
  const drained = await queue.run(async (x) => x * 2);
  assert.deepEqual(drained, [2]);
  await assert.rejects(queue.push(9), /queue is closed/);
});

test("rejects invalid capacity", () => {
  assert.throws(() => new BoundedQueue(0), RangeError);
});

Dependencies and running

No external dependencies (standard library only).

Runtime: node >= 18 Entry point: node example.mjs

Limitations and error handling

single consumer; no priority; no timeout on waiting producers.

Verification boundary

execution tests ran offline in an isolated temp dir with a sanitized environment; no network, no writes outside the sandbox

Interactive Tools for This Topic