❯ehsan.blog
~/blog/postgres-js-pipelining-the-first-run-of-every-query-is-always-slow — zsh
❯cat postgres-js-pipelining-the-first-run-of-every-query-is-always-slow.md

postgres.js never pipelines a query's first run

·11 min read

postgres.js never pipelines a query's first run — article card for a post by Ehsan Shahid

postgres.js is often described as the fastest Postgres client for Node. The reason given is always “it pipelines queries.” I wanted to see that happen with my own eyes, so instead of reading the README I pointed the library at a fake Postgres server I wrote, and logged every byte it sent.

Two things surprised me, and neither one is in the docs:

  1. The first time you run a given query, postgres.js refuses to pipeline it. It sends that one query and waits, alone, for a reply.
  2. max_pipeline: 3 does not mean three queries in flight. It means four.

Everything below was measured against postgres@3.4.9 on Node 22. You can reproduce all of it on your laptop without installing Postgres.

First, what “pipelining” even means

Imagine you are at a coffee counter with ten friends. The slow way: friend one orders, waits for the cup, steps aside; friend two orders, waits, steps aside. Ten walks to the counter and back.

The fast way: all ten of you shout your orders at once, then wait together. The barista still makes ten coffees, one at a time — that part does not speed up. What you saved is the walking.

That walk is the network round trip. If your database sits 2ms away and your page needs ten queries one after another, you spend 20ms just walking back and forth, even though your laptop could have shouted all ten orders in a single breath. Pipelining is shouting them in one breath.

Most Node Postgres clients solve the walking problem with a pool — more people at the counter. postgres.js does that too, but it also lets a single person place several orders before any coffee arrives. Those are different wins, and you get both.

How I watched it: a Postgres that is not Postgres

I did not have a database handy, and honestly a real one would have made this harder to see — real Postgres replies so fast that everything blurs together.

So I wrote about 70 lines of Node that pretend to be Postgres. It speaks just enough of the wire protocol to say “you are logged in” and “your query finished,” and it records every chunk of bytes the client sends. Then I gave it one superpower: stop replying.

The moment the server goes silent, anything the client keeps sending is, by definition, a query it fired without waiting for an answer. That is pipelining, caught in the act.

js
// The whole trick: hold every reply back for 500ms,
// then count what the client sent us anyway.
const sql = postgres({ host: '127.0.0.1', port, fetch_types: false, max: 1 })

await sql`select 1`                  // open the connection
srv.hold()                           // server goes quiet

const all = Promise.all(
  Array.from({ length: 10 }, (_, i) => sql`select ${i}::int`)
)
await new Promise(r => setTimeout(r, 250))   // peek at the wire mid-silence
console.log('executes received:', srv.log.queriesReceived)

I set max: 1 so there is exactly one connection. Without that, the pool would quietly spread the work across ten connections and I would be measuring the wrong thing.

Result one: the first run of a query stands alone

Here is what the fake server saw, with the ten queries fired at a silent server:

text
A. statement never seen before
   executes in flight: 0/10 | TCP chunks: 1 | bytes: 61 | msgs: PDH

B. same statement, already run once
   executes in flight: 10/10 | TCP chunks: 1 | bytes: 450
   msgs: BESBESBESBESBESBESBESBESBESBES

Read the msgs line — it is the sequence of protocol messages that arrived.

In case B, BES repeated ten times: Bind, Execute, Sync, ten times over, all ten queries on the wire before a single reply came back. That is pipelining working exactly as advertised.

In case A, the client sent P, D, H — Parse, Describe, Flush — and then stopped. One query. Nine still sitting in memory, waiting.

The difference between A and B is only that in B, I ran the same query once beforehand.

Why the first one has to wait

When postgres.js sees a query shape it has never run before, it cannot send it blind. It has to ask Postgres a question first: what types are these parameters, and what columns will come back?

Until that answer arrives, the client literally does not know how to encode your arguments or decode the result. You cannot pipeline behind a question you have not had answered yet. So it sends Parse + Describe, then Flush — “please answer this one right now” — and waits.

Once the answer comes back, postgres.js caches that shape under the statement’s text. Every later run of the same SQL, even with completely different parameter values, skips the question and goes straight to Bind/Execute/Sync. That is why B pipelines and A does not.

The practical consequence: a freshly started process is slower than a warm one, and no amount of pipelining fixes it. It is a one-time cost per distinct query shape, per connection — not per request.

The one boolean that decides everything

All of this comes from a single expression in src/connection.js:

js
return write(toBuffer(q))
  && !q.describeFirst
  && !q.cursorFn
  && sent.length < max_pipeline
  && (!q.options.onexecute || q.options.onexecute(connection))

This function does not decide whether to send your query. Your query is already on its way by the time this line runs. What it returns is an answer to a different question: may I hand this connection another query right now?

  • write(toBuffer(q)) — did the write go through cleanly
  • !q.describeFirst — this is case A above: a shape we have not learned yet
  • !q.cursorFn — a cursor is consumed in chunks, so there is nothing to run ahead of
  • sent.length < max_pipeline — the cap, and it is sneakier than it looks
  • onexecute — how sql.begin grabs a connection for itself (more below)

If the whole thing is true, the pool keeps feeding this connection. If any part is false, the connection is moved to a list literally named full, and nothing else goes to it until a reply arrives.

Result two: max_pipeline is off by one

Same experiment, now with the cap turned down:

text
C. max_pipeline: 3 → executes in flight: 4/10   (BES × 4)
D. max_pipeline: 1 → executes in flight: 2/10   (BES × 2)

Three gives you four. One gives you two. Every time.

The reason is one line further up:

js
query
  ? sent.push(q)
  : (query = q, query.active = true)

There are two places a query can live. The first one becomes query, the single “currently active” slot. Everything after it goes into the sent queue. And the cap is checked against sent.length — the queue behind the active query, not the total.

So max_pipeline is not “how many queries may be in flight.” It is “how many may be queued up behind the one in flight.” The real number on the wire is always one more than you configured. The default is 100, so in practice 101.

This almost never bites you at the default. It absolutely bites you if you set max_pipeline: 1 believing you have disabled pipelining — you have not. Two queries still go out together.

Where the pipelining actually gets triggered

I expected to find pipelining somewhere dramatic. It is three lines in src/index.js, in the function that routes a new query to a connection:

js
if (open.length) return go(open.shift(), query)
if (closed.length) return connect(closed.shift(), query)

busy.length
  ? go(busy.shift(), query)
  : queries.push(query)

The first two lines are what every pool does: use an idle connection, or open a new one.

The third line is the whole feature. When nothing is idle and nothing is left to open, most clients park the query in a queue. postgres.js instead grabs a connection that is already busy waiting for a result and hands it the query anyway.

That is it. Pipelining here is not a mode you enable — it is what happens when the pool runs out of idle connections and decides that “busy” is not the same as “unavailable.”

The part everyone gets wrong: write() does not write

This one caught me out, and I have seen it explained incorrectly more than once.

It is tempting to read write(...) in that boolean as “the TCP socket accepted the bytes, and returns false under backpressure.” That is not what the function does:

js
function write(x, fn) {
  chunk = chunk ? Buffer.concat([chunk, x]) : Buffer.from(x)
  if (fn || chunk.length >= 1024)
    return nextWrite(fn)
  nextWriteTimer === null && (nextWriteTimer = setImmediate(nextWrite))
  return true
}

It appends your query to a buffer and returns true without touching the socket, unless the buffer has grown past 1KB. The real socket.write happens later, on a setImmediate.

In other words: postgres.js glues your pipelined queries together and sends them as one lump. Look back at result B — ten queries, 450 bytes, one chunk. Not ten small writes the kernel happened to merge. One write, because the client deliberately batched them.

I confirmed the 1KB threshold by growing the parameter until the buffer had to flush early:

text
param   10B → 10 executes, 1 chunk  (540 bytes)
param  200B → 10 executes, 2 chunks (1220, 1220 bytes)
param 2000B → 10 executes, 2 chunks (2044, 18396 bytes)

Small queries: one syscall for the batch. Larger ones: flushed roughly every kilobyte. All ten still pipeline either way — the buffering changes how many writes, not how many queries go out.

Backpressure is still real: once the buffer does flush, socket.write can return false, and that false travels back up through the boolean and parks the connection. But it is the exception, not the mechanism. The mechanism is batching.

If you have ever queued outgoing HTTP calls yourself, this is the same instinct I wrote about in the request queue inside api-client: the cheap win is usually not more concurrency, it is fewer trips.

The transaction error that is not about pipelining

There is an error in the source that is easy to misread:

js
if (result.command === 'BEGIN' && max !== 1 && !connection.reserved)
  return errored(Errors.generic('UNSAFE_TRANSACTION',
    'Only use sql.begin, sql.reserved or max: 1'))

I have seen this quoted as proof that “postgres.js turns pipelining off inside transactions.” Read the condition literally — it has nothing to do with pipelining.

It fires when a BEGIN finishes on a connection that is part of a pool larger than one and has not been reserved. That is the situation where you sent a bare BEGIN through sql yourself. Your transaction is now open on a shared connection, and the very next query from anywhere in your app may land on that same connection and join your transaction by accident.

postgres.js refuses to let that happen, and the message tells you the three ways out: sql.begin (which reserves the connection for you, via that onexecute hook from the boolean), sql.reserved, or a pool of exactly one.

The guard is about connection ownership, not query ordering. If you only ever use sql.begin, you will never see it.

What to actually do with this

  • Expect the first run of each query to be slower. If you benchmark a cold process and conclude postgres.js is not pipelining, run the query twice first. Same applies to anything that measures a cold Lambda.
  • Do not set max_pipeline: 1 to disable pipelining. It does not. Use max: 1 with a reserved connection if you genuinely need strict one-at-a-time ordering.
  • Do not fight the batching. Ten small queries leaving as one 450-byte packet is the best case, not something to tune.
  • Use sql.begin for transactions, always. The alternative is an error at best, and someone else’s query inside your transaction at worst.
  • If you only ever await one query at a time, none of this helps you. Pipelining needs several queries in flight. Promise.all is what hands the pool something to overlap. If your data layer awaits in a loop, you are paying for every walk to the counter. (The same trap shows up in ORMs — see your Drizzle table has two row types, not one for a related place where the shape of your calls matters more than the client under them.)

The takeaway

I went in expecting pipelining to be a clever network trick. It is mostly bookkeeping: a count of what is in flight, a buffer that waits a tick before flushing, and one list called busy that the pool is willing to reuse.

The part I would not have guessed from the README is how much of the code is about refusing to pipeline — the first run of a statement, cursors, a reserved transaction, a full buffer. Each of those is a case where going fast would have been wrong, and someone wrote the guard instead.

That is the difference between a pipelining bullet point and a pipelining implementation you would put in front of a real database.

❯ls ./related
❯cat ./comments

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