❯ehsan.blog
~/blog/why-p-queue-never-calls-array-shift — zsh
❯cat why-p-queue-never-calls-array-shift.md

Why p-queue never calls array.shift()

·9 min read

Why p-queue never calls array.shift() — article card for a post by Ehsan Shahid

I wrote a small queue for nextjs-logger to batch log calls before sending them over the network. Then I read the source of p-queue, the library most people reach for when they need this, expecting to find a fancier version of what I had written. Half of it was exactly what I expected. The other half taught me something I had never thought about: p-queue never calls array.shift() to take an item off its queue, and the reason is worth knowing even if you never install it.

This is me reading a library I do not maintain, checking its claims against a stopwatch, and writing down the parts that changed how I would build my own.

What a queue has to do

A queue holds jobs. You put jobs in at one end, you take them out at the other, and you run a few at a time instead of all at once. That last part is the whole point: if you fire two hundred network requests at the same moment, you will hurt the server and probably yourself.

So there are two jobs here. Decide when a new task is allowed to start. And store the waiting tasks so you can pull the next one out quickly.

The first job is simple. The second one is where the surprise lives.

The simple half: counting

p-queue’s rule for starting a task is a single comparison:

js
get #doesConcurrentAllowAnother() {
  return this.#pending < this.#concurrency;
}

#pending is how many tasks are running right now. #concurrency is your limit. If the queue is full, nothing new starts, no matter how many tasks are waiting. When a task finishes, p-queue decrements #pending and tries again right away, so a free slot gets used immediately instead of waiting for a timer.

Pausing works the same plain way. There is an #isPaused flag, every start attempt checks it first, and start() clears it and then loops until nothing more can start:

js
#processQueue() {
  while (this.#tryToStartAnother()) { }
}

No tricks. This is the version most of us would write on our own, and that is fine, because it is already the right answer.

The expensive habit: taking from the front

Now the storage half. You have an array of waiting tasks and you want the first one. The obvious move is array.shift().

shift() removes the first element and then slides every other element down one slot. For a queue of ten, that is nothing. For a queue of a hundred thousand, every single shift() moves almost a hundred thousand elements. Drain the whole queue and you have done that work once per item.

I did not want to take anyone’s word on how bad that gets, so I measured it. Same machine, same Node version, draining a queue one item at a time:

js
const COMPACTION_THRESHOLD = 100

function drainWithShift(n) {
  const q = []
  for (let i = 0; i < n; i++) q.push({ value: i })
  const start = process.hrtime.bigint()
  while (q.length > 0) q.shift()
  return Number(process.hrtime.bigint() - start) / 1e6
}

function drainWithHead(n) {
  const q = []
  for (let i = 0; i < n; i++) q.push({ value: i })
  let head = 0
  const start = process.hrtime.bigint()
  while (head < q.length) {
    q[head] = undefined
    head++
    if (head === q.length) {
      q.length = 0
      head = 0
    } else if (head > COMPACTION_THRESHOLD && head > q.length / 2) {
      q.splice(0, head)
      head = 0
    }
  }
  return Number(process.hrtime.bigint() - start) / 1e6
}

On Node v22.16.0:

Itemsshift()head pointer
10,0002.2 ms0.5 ms
50,000188.1 ms0.6 ms
100,000850.2 ms0.6 ms
200,0003551.0 ms2.6 ms

Look at the shift() column as the count doubles. 100,000 items cost 850 ms. 200,000 items cost 3551 ms — more than four times as long for twice the work. That is the signature of quadratic cost. Double the input, quadruple the time. The head-pointer column barely moves at all.

Three and a half seconds of a single thread doing nothing but sliding array elements around. That is the bill shift() quietly hands you.

The fix: stop removing things

p-queue’s answer is to not remove the item at all. The comment in priority-queue.js says it plainly:

The queue is stored as a sorted array, but dequeued slots are left before #head until compaction. Only items from #head onward are live, which keeps repeated dequeues amortized O(1).

So taking an item is just: read the slot at #head, then move #head forward by one. Nothing slides. This is called lazy deletion — the item is logically gone, but physically still sitting there.

That raises a fair question. If you never delete anything, does the array grow forever and eat your memory?

Two things stop it. First, the slot gets cleared, which is the detail I would have missed:

js
this.#queue[this.#head] = undefined;
this.#head++;

Setting the slot to undefined drops the reference to the task function. The closure and everything it was holding can be garbage collected right away, instead of being pinned until the array is cleaned up. Without that single line, a long-lived queue would hold onto dead work indefinitely.

Second, the dead space does get reclaimed, just not on every operation.

When it actually cleans up

Here is the bit I got wrong on my first read, and had to go back to the source to correct. I assumed it compacted once the head passed the halfway mark. It is stricter than that — there are two conditions, and both must hold:

js
else if (this.#head > compactionThreshold && this.#head > this.#queue.length / 2) {
  this.#compact();
}

compactionThreshold is 100. So a queue that never holds more than a hundred items never compacts mid-drain at all. The halfway rule alone would have triggered cleanup constantly on small queues, for no benefit.

There is also a faster exit. If the head catches up to the end, the queue is empty, and it resets in place rather than splicing:

js
if (this.#head === this.#queue.length) {
  this.#queue.length = 0;
  this.#head = 0;
}

This is the amortized trade in miniature. Pay nothing on most operations, pay once in a while, and come out ahead overall.

Adding items: do the least work that is correct

Insertion follows the same instinct. Three cases, cheapest first:

  1. Queue is empty — push it. Nothing to compare against.
  2. New priority is lower than or equal to the last item’s — push it. One comparison, and equal priorities keep their arrival order for free.
  3. Anything else — only now compact, then binary search for the right spot with lowerBound, then splice it in.

Most tasks in a real queue share the same priority, so case 2 handles nearly everything with a single check.

The Infinity trap hiding in the comparator

Case 3 holds the sharpest detail in the file, and the draft of this post I started from had missed it completely. Here is the comparator:

js
const index = lowerBound(
  this.#queue,
  element,
  (a, b) => a.priority === b.priority ? 0 : b.priority - a.priority
);

The equality check looks redundant. If two priorities are the same, surely b.priority - a.priority is already 0? The source comment explains why not:

Equal priorities compare as 0 first, because Infinity - Infinity is NaN.

Infinity is a legal priority. And Infinity - Infinity is not zero — it is NaN. I tested both comparators against a queue already holding two Infinity-priority items, inserting a third:

plaintext
Infinity - Infinity = NaN
guarded comparator -> 0   | index: 2
naive   comparator -> NaN | index: 0
NaN <= 0 is false

The guarded version returns index 2, appending the new item after the two already waiting. Correct. The naive version compares NaN, and because every comparison with NaN is false, the binary search collapses to index 0 and inserts the new item at the front — ahead of two items that were queued before it.

That is a real bug, and a nasty one. No crash, no error. Your highest-priority tasks just quietly run in the wrong order, and only when more than one of them uses Infinity. Three characters of comparison guard prevent it.

What I am taking back to my own queue

My logger’s queue does not need priorities today. Every batched entry is equal, flushed in arrival order, which is the right default when the goal is not losing logs. Nothing here says otherwise.

But there is one case where priority would earn its place. During a burst, a fatal entry can land behind ninety-nine debug entries. If the batch hits its size cap and starts dropping the oldest under pressure, the single entry you most needed is the one you lose. That is a concrete argument for letting it jump the line — not “priority queues are good,” but “the entry I cannot afford to lose should not be dropped by arrival order.”

If I add it, I am copying this shape rather than inventing one. Keep the common path to a single comparison. Pay for the binary search only on the rare out-of-order insert. And guard the comparator, because I now know what Infinity does to it.

The takeaway

The concurrency gate taught me nothing, and that is a good sign — it means the obvious answer was already right. The storage layer is where the real lesson sits.

When something gets removed from one end over and over, deleting it properly every time is rarely the fastest correct option. Mark it dead, move a pointer, clear the reference so memory can be reclaimed, and do the real cleanup occasionally in a batch. The same shape shows up in ring buffers and garbage collectors.

The wider habit is worth more than the technique. I almost published the version of this post that said compaction happens at the halfway mark, because that sounded right. Reading the actual line showed a threshold of 100 sitting next to it, and a test showed a NaN bug that a one-line guard prevents. Both were a few minutes of checking. That same instinct is what found a fetch timeout that starts before the request does and a 30-day setTimeout that fires immediately — plausible beats measured exactly never. If you want the queue concepts in the context of a real client, I wrote up dedup, retries, timeouts, and the queue separately.

Run the benchmark above on your own machine. Watching that shift() column quadruple is more convincing than any argument I can make for it.

❯ls ./related
❯cat ./comments

Comments are not configured yet. Enable GitHub Discussions and paste the giscus repo-id / category-id into src/consts.ts.