Repository navigation
Description
Here is my code:
import express from "express";
import postgres from "postgres";
const sql = postgres('postgres://test:[email protected]:5432/test')
const port = 3000;
const app = express();
app.get("/", async (req, res) => {
for (let i = 1; i <= 20; i++) {
const xs = await sql`select * from posts where id=1`
}
res.send(`ok`);
});
app.listen(port, () => {
console.log(`Listening on port ${port}...`);
});
I run the following ab test:
ab -n 2000 -c 5 http://localhost:3000 ( number:2000, concurrency: 5 requests at a time)
The result is stable at around 900/sec, whatever times repeat the command.
Then I run:
ab -n 2000 -c 10 http://localhost:3000 (change 5 to 10)
The result is still around 900/sec
Then issue came. When I run
ab -n 2000 -c 5 http://localhost:3000 (change 10 back to 5)
After repeat this command several times, the results significantly dropped to 150/sec, and even keep dropping.
If I restart the express server, and run the above command, it become stable at 900/sec again.
This issue is that, if I set -c 10 and then set -c 5, the reqeusts/sec will drop significantly.
I have tested both ts-node and bun, both express and bun native serve, same issue occured.
Activity
WIGGLES-dev commentedon Dec 9, 2023
Can confirm experiencing same issue in bun, performance degrades between stress test. Notably the issue is only present when max connections is set great than 1. So it may be a pooling issue.
porsager commentedon Dec 9, 2023
This is a very nice repro @lnlife ! Thank you! I've looked closer, and there's a really bad regression all the way back from 3.0.1. I'll be looking deeper into this tomorrow.
divmgl commentedon Mar 1, 2024
Is this still happening? I was about to go all in on
postgresfor some of the services in our codebase given the sheer amount of performance problems with Prisma.stan023 commentedon Mar 1, 2024
Yes it is. I have to set
{max:1}in the connection option to stop pool. Even so, it is still the fasted client.jonataslaw commentedon Apr 17, 2024
any update on this?
IcyFoxe commentedon Mar 22, 2025
I just played with some load tests today, querying simple data from DB using Fastify.
If default 10 max connections are set, performance starts degrading after few tests, from 20k req/s to 10k or lower.
At 5 max connections I get impressive 40k req/s, drops to around 35k after few tests.
At 1 to 3 max connection it runs at stable 40k req/s, no drops in speed even after reruns.
Another interesting thing, when using Drizzle ORM, max speed I get is around 15k req/s.
With Node Postgres I get around 10k req/s for comparison.
nikelborm commentedon Apr 26, 2025
During an investigation of Effect-TS/effect#4793 (highly recommend reading it too, if the reader has plans on fixing the issue), I noticed very weird behavior related to this library. For some reason, the performance of the SQL connection Pool keeps degrading over time as if some connections become unavailable, but then suddenly performance turns back to normal.
Logs
Here is a diagram representing logs from above:
Notice that at the 25-second mark, there are already only 8 out of 10 connections being used.
At 30 seconds, it's 7 connections.
At 35 seconds, there are only 3 connections that weren't unloaded, etc
But then, suddenly, when I ran the identical promise immediately after, the diagram became something that was expected:
saevarb commentedon May 20, 2025
Hi. This is a really critical issue which doesn't seem to be documented anywhere. Is there any update on the fix?
valeneiko commentedon Jul 9, 2026
I think @nikelborm case can be explained with pipelining. Not sure if the cause of the original issue is the same. You can test by passing
max_pipeline: 0to pool constructor.By looking at the logic here:
postgres/src/index.js
Lines 329 to 342 in e7dfa14
The pool picks connections in order:
open,idle,closed,busy. Then falls back to generic (fallback) queue.But on initial connection the connection is moved from
closedtoconnecting.Once the initial query succeeds, its connection checks the fallback queue, picks the next query and moves to
busy. At this point we submit the next query, and it skips the queue, since it finds abusyconnection and immediately gets sent (pipelined), while the query we just picked up form the fallback queue is still executing.When the next query succeeds the same thing repeats and we send the 3rd query to the first connection. And would now have 2 connections in the busy queue.
This logic has 2 effects:
Evil0ctal commentedon Sep 29, 2026
I think I found the root cause of this. It's not connection selection or pipelining — it's the
Queuebookkeeping, and it explains why several people here narrowed it tomax > 1.Every query permanently leaks one slot in the
openqueue's backing array, andremove()rescans the whole thing on every connection hand-off. So the cost of acquiring a connection grows linearly with the number of queries the pool has served since the process started. That is the "gets slower and only a restart fixes it" shape reported throughout this thread.Still present on
master—src/queue.jsis byte-identical to 3.4.9.Mechanism
handlertakes a connection out ofopenwithshift()but leavesc.queuepointing atopen:move()then tries to remove it from the queue it no longer belongs to:indexOfreturns -1, nothing is spliced. When the query finishes,move(c, open)pushes the connection back — one more slot on the array. Andshift()only compacts when the cursor happens to reach the end:With a second idle connection sitting in
open, the cursor can never catch a tail that keeps growing, so it never compacts.lengthis computed asxs.length - index, so it keeps reporting the correct value — nothing looks wrong from the outside.Instrumented counters
Adding pure counters to
Queue(no behaviour change), poolmax: 10:remove()misses 100% of the time, and the array grows by exactly one slot per query.Why
max > 1is the trigger5000 queries, measuring the
openqueue's internal array:maxWith
max: 1the shift drainsopen, so the compaction branch fires and resets the array. With two or more connections it never does. Concurrency is irrelevant — fully sequential queries leak just as fast. This matches @WIGGLES-dev's "only present when max connections is set greater than 1" and @stan023's{max:1}workaround.Reproduction
Against an empty Postgres 16, node 20:
Worth noting: at 24k queries this script shows nothing — the curve even improves as the JIT warms up. The array is already at 10k by then, but scanning 10k elements is still cheap. That's probably why this has survived so long: it only becomes visible at a scale most benchmarks never reach.
What it looks like in production
A Node service of mine at ~13 queries/s, after three weeks of uptime:
openqueue internal array: 23,830,951 entriesQueue.remove/healthroute that touches nothing answering in a median of 3 secondsExtrapolating the repro's ~0.5ns per scanned element to 23.8M entries at the measured ~40-50
remove()calls/s lands within 2x of the observed CPU.Possible fixes
The narrow one — keep
c.queuein sync where a connection is taken withshift(), soremove()stops missing.Two independent defensive changes in
queue.js, either of which removes the pathology on its own:I'm running (1)+(2) as a build-time patch in production now — CPU is flat at ~2.5% and
/healthis back to ~2.3ms. Happy to open a PR if you'd like, though the caller-side fix may be the one you prefer.Evil0ctal commentedon Sep 30, 2026
Two corrections to my comment above, after digging further.
1. The caller-side fix is not sufficient. I suggested that keeping
c.queuein sync at the callers might be the real fix. It isn't. The backing array doesn't grow becauseremove()misses. It grows becauseshift()only compacts on a full drain, and theopenqueue is shifted and pushed back without ever draining. My own counters already showed it: the internal array length equals the number of pushes, and the cursor equals the number of shifts. Nothing is ever spliced, so it's one leaked slot per query, miss or not. The same pattern also leaksbusyunder load, the pendingqueriesbacklog, and each connection'ssentqueue (which is neverremove()d). So the fix belongs inQueue.2. The trigger is "two or more idle connections in
open", not justmax > 1. I said concurrency was irrelevant, but my repro warmed the pool with a concurrent burst first. A fresh pool running strictly sequential queries only ever opens one connection.openthen drains on everyshift()and resets, so nothing leaks. Growth starts once some burst has opened a second connection. After that, even sequential queries leak. This matches the original report here exactly:-c 5was stable until a-c 10run had opened more connections.PR with the fix and a deterministic regression test (no timing, no database): #1235
v4