Skip to content

A weird issue: speed dropped  #747

Closed

Description

@stan023

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

  1. WIGGLES-dev commented on Dec 9, 2023

    @WIGGLES-dev

    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.

  2. added
    bug
    on Dec 9, 2023
  3. porsager commented on Dec 9, 2023

    @porsager
    Owner

    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.

  4. divmgl commented on Mar 1, 2024

    @divmgl

    Is this still happening? I was about to go all in on postgres for some of the services in our codebase given the sheer amount of performance problems with Prisma.

  5. stan023 commented on Mar 1, 2024

    @stan023
    Author

    Is this still happening? I was about to go all in on postgres for some of the services in our codebase given the sheer amount of performance problems with Prisma.

    Yes it is. I have to set {max:1} in the connection option to stop pool. Even so, it is still the fasted client.

  6. jonataslaw commented on Apr 17, 2024

    @jonataslaw

    any update on this?

  7. IcyFoxe commented on Mar 22, 2025

    @IcyFoxe

    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.

  8. nikelborm commented on Apr 26, 2025

    @nikelborm

    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.

    import postgres from "postgres";
    
    const sql = postgres({
      user: "root",
      password: "mypass",
      host: "localhost",
      port: 5432,
      database: "main",
      idle_timeout: 5 * 60, // 5 minutes just in case
      connect_timeout: 5 * 60, // 5 minutes just in case
      max_lifetime: 30 * 60,
      keep_alive: 5 * 60, // 5 minutes just in case
      max: 10,
    });
    
    const test = () =>
      Promise.all(
        Array.from({ length: 20 }, async (_, i) => {
          const task = `task #${i.toString(20)}`;
          const startedAt = new Date();
          const time = () =>
            (
              Math.floor((new Date().getTime() - startedAt.getTime()) / 1000) + "s"
            ).padStart(3, " ");
    
          console.log(`${task}   -> 1 at ${time()}`);
          await sql`select pg_sleep(5);`;
          console.log(`${task} 1 -> 2 at ${time()}`);
          await sql`select pg_sleep(5);`;
          console.log(`${task} 2 -> 3 at ${time()}`);
          await sql`select pg_sleep(5);`;
          console.log(`${task} 3 ->   at ${time()}`);
        })
      );
    
    await test();
    
    console.log("\nThe f***ing magic\n");
    
    await test();
    
    await sql.end();
    Logs
    task #0   -> 1 at  0s
    task #1   -> 1 at  0s
    task #2   -> 1 at  0s
    task #3   -> 1 at  0s
    task #4   -> 1 at  0s
    task #5   -> 1 at  0s
    task #6   -> 1 at  0s
    task #7   -> 1 at  0s
    task #8   -> 1 at  0s
    task #9   -> 1 at  0s
    task #a   -> 1 at  0s
    task #b   -> 1 at  0s
    task #c   -> 1 at  0s
    task #d   -> 1 at  0s
    task #e   -> 1 at  0s
    task #f   -> 1 at  0s
    task #g   -> 1 at  0s
    task #h   -> 1 at  0s
    task #i   -> 1 at  0s
    task #j   -> 1 at  0s
    task #5 1 -> 2 at  5s
    task #3 1 -> 2 at  5s
    task #1 1 -> 2 at  5s
    task #0 1 -> 2 at  5s
    task #2 1 -> 2 at  5s
    task #7 1 -> 2 at  5s
    task #4 1 -> 2 at  5s
    task #6 1 -> 2 at  5s
    task #9 1 -> 2 at  5s
    task #8 1 -> 2 at  5s
    task #a 1 -> 2 at 10s
    task #b 1 -> 2 at 10s
    task #c 1 -> 2 at 10s
    task #d 1 -> 2 at 10s
    task #e 1 -> 2 at 10s
    task #f 1 -> 2 at 10s
    task #g 1 -> 2 at 10s
    task #j 1 -> 2 at 10s
    task #h 1 -> 2 at 10s
    task #i 1 -> 2 at 10s
    task #5 2 -> 3 at 15s
    task #1 2 -> 3 at 15s
    task #g 2 -> 3 at 15s
    task #2 2 -> 3 at 15s
    task #4 2 -> 3 at 15s
    task #e 2 -> 3 at 15s
    task #a 2 -> 3 at 15s
    task #9 2 -> 3 at 15s
    task #c 2 -> 3 at 15s
    task #j 2 -> 3 at 15s
    task #5 3 ->   at 20s
    task #3 2 -> 3 at 20s
    task #d 2 -> 3 at 20s
    task #7 2 -> 3 at 20s
    task #2 3 ->   at 20s
    task #8 2 -> 3 at 20s
    task #h 2 -> 3 at 20s
    task #9 3 ->   at 20s
    task #e 3 ->   at 20s
    task #g 3 ->   at 20s
    task #0 2 -> 3 at 25s
    task #3 3 ->   at 25s
    task #4 3 ->   at 25s
    task #b 2 -> 3 at 25s
    task #i 2 -> 3 at 25s
    task #c 3 ->   at 25s
    task #8 3 ->   at 25s
    task #7 3 ->   at 25s
    task #6 2 -> 3 at 30s
    task #h 3 ->   at 30s
    task #0 3 ->   at 30s
    task #i 3 ->   at 30s
    task #j 3 ->   at 30s
    task #1 3 ->   at 30s
    task #b 3 ->   at 30s
    task #d 3 ->   at 35s
    task #f 2 -> 3 at 35s
    task #6 3 ->   at 35s
    task #a 3 ->   at 40s
    task #f 3 ->   at 40s
    
    The f***ing magic
    
    task #0   -> 1 at  0s
    task #1   -> 1 at  0s
    task #2   -> 1 at  0s
    task #3   -> 1 at  0s
    task #4   -> 1 at  0s
    task #5   -> 1 at  0s
    task #6   -> 1 at  0s
    task #7   -> 1 at  0s
    task #8   -> 1 at  0s
    task #9   -> 1 at  0s
    task #a   -> 1 at  0s
    task #b   -> 1 at  0s
    task #c   -> 1 at  0s
    task #d   -> 1 at  0s
    task #e   -> 1 at  0s
    task #f   -> 1 at  0s
    task #g   -> 1 at  0s
    task #h   -> 1 at  0s
    task #i   -> 1 at  0s
    task #j   -> 1 at  0s
    task #0 1 -> 2 at  5s
    task #3 1 -> 2 at  5s
    task #5 1 -> 2 at  5s
    task #7 1 -> 2 at  5s
    task #2 1 -> 2 at  5s
    task #8 1 -> 2 at  5s
    task #1 1 -> 2 at  5s
    task #4 1 -> 2 at  5s
    task #6 1 -> 2 at  5s
    task #9 1 -> 2 at  5s
    task #a 1 -> 2 at 10s
    task #c 1 -> 2 at 10s
    task #d 1 -> 2 at 10s
    task #h 1 -> 2 at 10s
    task #e 1 -> 2 at 10s
    task #f 1 -> 2 at 10s
    task #b 1 -> 2 at 10s
    task #i 1 -> 2 at 10s
    task #g 1 -> 2 at 10s
    task #j 1 -> 2 at 10s
    task #3 2 -> 3 at 15s
    task #7 2 -> 3 at 15s
    task #5 2 -> 3 at 15s
    task #2 2 -> 3 at 15s
    task #4 2 -> 3 at 15s
    task #0 2 -> 3 at 15s
    task #8 2 -> 3 at 15s
    task #9 2 -> 3 at 15s
    task #6 2 -> 3 at 15s
    task #1 2 -> 3 at 15s
    task #a 2 -> 3 at 20s
    task #h 2 -> 3 at 20s
    task #e 2 -> 3 at 20s
    task #g 2 -> 3 at 20s
    task #i 2 -> 3 at 20s
    task #f 2 -> 3 at 20s
    task #d 2 -> 3 at 20s
    task #j 2 -> 3 at 20s
    task #c 2 -> 3 at 20s
    task #b 2 -> 3 at 20s
    task #2 3 ->   at 25s
    task #1 3 ->   at 25s
    task #3 3 ->   at 25s
    task #0 3 ->   at 25s
    task #9 3 ->   at 25s
    task #5 3 ->   at 25s
    task #6 3 ->   at 25s
    task #7 3 ->   at 25s
    task #4 3 ->   at 25s
    task #8 3 ->   at 25s
    task #g 3 ->   at 30s
    task #b 3 ->   at 30s
    task #a 3 ->   at 30s
    task #f 3 ->   at 30s
    task #c 3 ->   at 30s
    task #e 3 ->   at 30s
    task #j 3 ->   at 30s
    task #h 3 ->   at 30s
    task #i 3 ->   at 30s
    task #d 3 ->   at 30s
    

    Here is a diagram representing logs from above:

    0 -|x| | | |x|x| | |
    1 -|x| |x| | |x| | |
    2 -|x| |x|x| | | | |
    3 -|x| | |x|x| | | |
    4 -|x| |x| |x| | | |
    5 -|x| |x|x| | | | |
    6 -|x| | | | |x|x| |
    7 -|x| | |x|x| | | |
    8 -|x| | |x|x| | | |
    9 -|x| |x|x| | | | |
    a -| |x|x| | | | |x|
    b -| |x| | |x|x| | |
    c -| |x|x| |x| | | |
    d -| |x| |x| | |x| |
    e -| |x|x|x| | | | |
    f -| |x| | | | |x|x|
    g -| |x|x|x| | | | |
    h -| |x| |x| |x| | |
    i -| |x| | |x|x| | |
    j -| |x|x| | |x| | |
       0 | 10| 20| 30| 40
         5   15  25  35
    

    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:

    0 -|x| |x| |x| |
    1 -|x| |x| |x| |
    2 -|x| |x| |x| |
    3 -|x| |x| |x| |
    4 -|x| |x| |x| |
    5 -|x| |x| |x| |
    6 -|x| |x| |x| |
    7 -|x| |x| |x| |
    8 -|x| |x| |x| |
    9 -|x| |x| |x| |
    a -| |x| |x| |x|
    b -| |x| |x| |x|
    c -| |x| |x| |x|
    d -| |x| |x| |x|
    e -| |x| |x| |x|
    f -| |x| |x| |x|
    g -| |x| |x| |x|
    h -| |x| |x| |x|
    i -| |x| |x| |x|
    j -| |x| |x| |x|
       0 | 10| 20| 30
         5   15  25
    
  9. saevarb commented on May 20, 2025

    @saevarb

    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.

    Hi. This is a really critical issue which doesn't seem to be documented anywhere. Is there any update on the fix?

  10. valeneiko commented on Jul 9, 2026

    @valeneiko
    Contributor

    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: 0 to pool constructor.

    By looking at the logic here:

    postgres/src/index.js

    Lines 329 to 342 in e7dfa14

    function handler(query) {
    if (ending)
    return query.reject(Errors.connection('CONNECTION_ENDED', options, options))
    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 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 closed to connecting.

    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 a busy connection 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:

    • The connections that completes initial query first ends up getting more queries pipelined on it, which leads to imbalanced pool, where we are waiting for some overloaded connection, while other are sitting idle.
    • Some queries submitted while connections were closed are stuck behind new queries skipping the queue due to this pipelining logic.
  11. Evil0ctal commented on Sep 29, 2026

    @Evil0ctal

    I think I found the root cause of this. It's not connection selection or pipelining — it's the Queue bookkeeping, and it explains why several people here narrowed it to max > 1.

    Every query permanently leaks one slot in the open queue's backing array, and remove() 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.js is byte-identical to 3.4.9.

    Mechanism

    handler takes a connection out of open with shift() but leaves c.queue pointing at open:

    return go(open.shift(), query)          // src/index.js:334

    move() then tries to remove it from the queue it no longer belongs to:

    function move(c, queue) {               // src/index.js:308
      c.queue.remove(c)                     // ← always a miss after a shift()
      queue.push(c)
      c.queue = queue

    indexOf returns -1, nothing is spliced. When the query finishes, move(c, open) pushes the connection back — one more slot on the array. And shift() only compacts when the cursor happens to reach the end:

    if (index === xs.length) { index = 0; xs = [] }   // src/queue.js
    else { xs[index - 1] = undefined }

    With a second idle connection sitting in open, the cursor can never catch a tail that keeps growing, so it never compacts. length is computed as xs.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), pool max: 10:

    after warmup          open: length=10  array=    10  cursor=    0  pushes=   10  shifts=    0  remove hit=0  miss=    0
    after 10000 queries   open: length=10  array= 10010  cursor=10000  pushes=10010  shifts=10000  remove hit=0  miss=10000
    

    remove() misses 100% of the time, and the array grows by exactly one slot per query.

    Why max > 1 is the trigger

    5000 queries, measuring the open queue's internal array:

    pool max concurrency internal array
    1 1 1
    2 1 5002
    10 1 5010
    10 5 5010

    With max: 1 the shift drains open, 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

    // npm i [email protected]
    import postgres from 'postgres'
    
    const sql = postgres(process.argv[2], { max: 10, idle_timeout: 0 })
    await Promise.all(Array.from({ length: 10 }, () => sql`select 1`))  // warm the pool
    
    const BATCH = 25000
    for (let b = 1; b <= 12; b++) {
      const t0 = performance.now()
      let done = 0, started = 0
      await new Promise((resolve, reject) => {
        const kick = () => {
          while (started - done < 5 && started < BATCH) {
            started++
            sql`select 1`.then(() => { done++; done === BATCH ? resolve() : kick() }, reject)
          }
        }
        kick()
      })
      const ms = performance.now() - t0
      console.log(`batch ${b}: ${ms.toFixed(0)}ms  ${(ms * 1000 / BATCH).toFixed(0)}µs/query`)
    }
    await sql.end()

    Against an empty Postgres 16, node 20:

    batch  1:  186 µs/query
    batch  6:  220 µs/query
    batch 12:  323 µs/query     ← 1.7x slower, identical work
    

    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:

    • open queue internal array: 23,830,951 entries
    • CPU profile: 89.3% of self time in Queue.remove
    • one core pinned at 100%, event-loop p99 1.6s
    • a /health route that touches nothing answering in a median of 3 seconds
    • restarting the process: CPU 3.7%, /health 2.3ms

    Extrapolating 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.queue in sync where a connection is taken with shift(), so remove() stops missing.

    Two independent defensive changes in queue.js, either of which removes the pathology on its own:

    // 1. search from the cursor — slots below it were blanked by shift()
    //    and can never hold x, so the result is identical
    remove: (x) => {
      const at = xs.indexOf(x, index)
      return at === -1 ? null : (xs.splice(at, 1), x)
    },
    
    // 2. compact once the dead prefix outgrows the live entries
    } else {
      xs[index - 1] = undefined
      if (index > 64 && index * 2 >= xs.length) {
        xs = xs.slice(index)
        index = 0
      }
    }

    I'm running (1)+(2) as a build-time patch in production now — CPU is flat at ~2.5% and /health is back to ~2.3ms. Happy to open a PR if you'd like, though the caller-side fix may be the one you prefer.

  12. Evil0ctal commented on Sep 30, 2026

    @Evil0ctal

    Two corrections to my comment above, after digging further.

    1. The caller-side fix is not sufficient. I suggested that keeping c.queue in sync at the callers might be the real fix. It isn't. The backing array doesn't grow because remove() misses. It grows because shift() only compacts on a full drain, and the open queue 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 leaks busy under load, the pending queries backlog, and each connection's sent queue (which is never remove()d). So the fix belongs in Queue.

    2. The trigger is "two or more idle connections in open", not just max > 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. open then drains on every shift() 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 5 was stable until a -c 10 run had opened more connections.

    PR with the fix and a deterministic regression test (no timing, no database): #1235

  13. added a commit that references this issue on Oct 29, 2026
    06cf284
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions