How-To Guide

How to Implement a Bounded Work Queue

Keep a work queue from growing without bound by applying backpressure, priorities and deadlines instead of accepting unlimited tasks.

On this page

  1. Introduction
  2. Why an Unbounded Queue Is Dangerous
  3. Bounded Queue Semantics
  4. Backpressure to the Producer
  5. Priorities
  6. Deadlines in the Queue
  7. Observing Queue Depth
  8. Conclusion

Introduction

A work queue decouples producers from consumers, which is useful until the producers outrun the consumers and the queue grows without bound, consuming memory and delaying every task. An unbounded queue hides overload: the producer never blocks, so the backlog grows silently until memory runs out or the oldest tasks are so stale they are useless. A bounded queue makes the limit explicit and applies backpressure to the producer, rejecting or blocking when it is full. This article covers bounded queue semantics, backpressure, priorities, deadlines, and how to observe the queue so overload is visible.

Why an Unbounded Queue Is Dangerous

A queue that accepts every task can only grow when the arrival rate exceeds the service rate. Memory use is proportional to queue depth, so an unbounded queue is an unbounded memory leak under sustained overload. The tasks at the back wait longer and longer, and eventually the memory either runs out and crashes the process or triggers a garbage collection storm that slows everything.

The deeper problem is that the overload is invisible until it is fatal. With a bounded queue, the producer feels the pressure immediately and the system can respond; with an unbounded one, the pressure is converted into latency and memory until it explodes. Making the bound explicit is the difference between a controlled failure and a crash.

Bounded Queue Semantics

A bounded queue has a maximum depth and a defined behaviour when it is full: reject the task, block the producer until there is room, or drop the oldest. Each is right in a different context. Rejecting is right when the producer can retry or shed. Blocking is right when the producer must not lose the task and can wait. Dropping the oldest is right when stale tasks are worthless and the newest matter most.

class BoundedQueue {
  constructor(capacity) {
    this.capacity = capacity;
    this.items = [];
    this.waiters = [];   // producers blocked on a full queue
    this.consumers = []; // consumers blocked on an empty queue
  }
  // put blocks when full; returns false if the caller chose to drop instead.
  async put(item, { timeoutMs } = {}) {
    while (this.items.length >= this.capacity) {
      if (timeoutMs === undefined) {
        await new Promise((r) => this.waiters.push(r));   // backpressure
      } else {
        const ok = await Promise.race([
          new Promise((r) => this.waiters.push(() => r(true))),
          new Promise((r) => setTimeout(() => r(false), timeoutMs)),
        ]);
        if (!ok) return false;                            // shed the task
      }
    }
    this.items.push(item);
    this.consumers.shift()?.();
    return true;
  }
  async take() {
    while (this.items.length === 0) {
      await new Promise((r) => this.consumers.push(r));
    }
    const item = this.items.shift();
    this.waiters.shift()?.();                             // wake a producer
    return item;
  }
  get depth() { return this.items.length; }
}

Backpressure to the Producer

The queue’s bound is only useful if it propagates to the producer. When the queue is full, the producer must either block, slow down, or shed. In a request-handling path, blocking the producer means the request waits, which is often better than an unbounded backlog; shedding means the request is rejected with a retry hint. Either way, the pressure reaches whoever generates the work, which is what allows the system to respond.

A subtlety is where to apply the backpressure. Blocking the thread that produces in a single-threaded runtime stalls everything, so prefer an async wait or a bounded number of producers. The goal is that the arrival rate is limited to the service rate plus the queue depth, not that producers pile up unboundedly.

Priorities

When the queue is full, the order matters: a low-priority task can fill the space a high-priority one needs. A priority queue admits high-priority tasks ahead of low-priority ones and sheds the low-priority work first, so under overload the important tasks still complete. Without priorities, the queue is first-in-first-out and overload punishes the important and the trivial alike.

Priorities interact with fairness: a stream of high-priority tasks can starve low-priority ones forever. Use priority combined with aging, where a task’s priority rises as it waits, so low-priority work eventually runs. This is the same starvation-avoidance idea as a fair lock.

Deadlines in the Queue

A task has a time by which its result is useful; a task that runs after that time wastes work. Stamp each task with a deadline and drop or fail tasks whose deadline has passed when they are dequeued, so the worker does not spend time on a result nobody will use. This also bounds how stale the output can be, which is a property the consumer often needs.

Deadlines are especially important for queues that back a latency-sensitive path: a task that has already exceeded its deadline is better shed than processed, because processing it delays the tasks behind it that might still be in time. Combine deadlines with the priority order so the tasks closest to their deadline run first.

// Drain expired tasks instead of spending a worker on a useless result.
async function workerLoop(queue, processTask) {
  for (;;) {
    const task = await queue.take();          // priority order, nearest deadline first
    if (task.deadline && task.deadline <= Date.now()) {
      metrics.increment('tasks_expired');
      continue;                               // shed it, do not process
    }
    try {
      await processTask(task);
      metrics.increment('tasks_done');
    } catch (err) {
      metrics.increment('tasks_failed');
      throw err;
    }
  }
}

Observing Queue Depth

Expose the queue depth and the wait time of the oldest task. A depth that sits near the capacity during normal operation means the queue is too small and shedding too often; a depth that grows without bound means the bound is not enforced or the service rate cannot keep up. The wait time of the oldest task is the staleness of the backlog, which is often what users feel.

Alert on sustained depth near the capacity, because that is the signal to add consumers or reduce the arrival rate. Track the shed rate alongside, since a queue that sheds constantly is a queue whose consumers are too slow, not one that is working as designed. The queue depth and the shed rate together tell you whether the bound is a safety net or a permanent constraint.

Conclusion

A bounded work queue makes the limit explicit and applies backpressure so overload is visible rather than absorbed into memory. Choose the full-queue behaviour deliberately, propagate the pressure to the producer, prioritise so under overload the important tasks complete, stamp tasks with deadlines and drop the expired ones, and observe the depth and the oldest wait time. Then the queue is a safety net that keeps the system responsive, not a buffer that hides a growing problem until it crashes.

Sources: Little’s law, AWS: back pressure, Reactive Streams backpressure.

FAQ

What should a bounded queue do when it is full?
One of: reject the task, block the producer until there is room, or drop the oldest. Reject when the producer can retry or shed, block when the task must not be lost and the producer can wait, drop the oldest when stale tasks are worthless.
Why stamp tasks with deadlines?
Because a task whose result is due at a time that has passed wastes work when it runs. Dropping expired tasks when they are dequeued avoids spending time on a result nobody will use and keeps the queue from delaying fresher tasks behind it.

Related Examples