You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Deadlocked/hung pool when connected to Postgres through Supavisor #970
Creating this issue mostly in hopes that someone else has ran into this issue.
We use Supabase for our Postgres DB and connect through their pooling service Supavisor in transaction mode; Supavisor is an alternative to pgBouncer (link). On postgres.js side, we set prepare: false.
What we're seeing is that the postgres.js pooler will start swallowing queries at some point. Imagine a function like:
async function userGet(id: string) {
console.log("trying to get the user");
const users = await db<User[]>`SELECT * FROM user WHERE id=${id}`;
console.log("got the user!");
return users;
}
After a while, this will print "trying to get the user" but not "got the user!". Does this ring any bells?
P.S. been trying to find an isolated script to reproduce but unsuccessful so far. the only reproduction is live production traffic.
Reacted by Henry, Akbar, sagar-vapi and Giacomo Randazzo
Please forgive not answering your exact question but we have run into very similar issues and it boiled down to our queries being blocking & locking. We've used this query (modify as needed) to run down issues in our Supabase PG instance:
SELECTblocked_locks.pidAS blocked_pid,
blocked_activity.usenameAS blocked_user,
blocking_locks.pidAS blocking_pid,
blocking_activity.usenameAS blocking_user,
blocked_activity.queryAS blocked_statement,
blocking_activity.queryAS current_statement_in_blocking_process
FROMpg_catalog.pg_locks blocked_locks
JOINpg_catalog.pg_stat_activity blocked_activity ONblocked_activity.pid=blocked_locks.pidJOINpg_catalog.pg_locks blocking_locks
ONblocking_locks.locktype=blocked_locks.locktypeANDblocking_locks.DATABASE IS NOT DISTINCT FROMblocked_locks.DATABASEANDblocking_locks.relation IS NOT DISTINCT FROMblocked_locks.relationANDblocking_locks.page IS NOT DISTINCT FROMblocked_locks.pageANDblocking_locks.tuple IS NOT DISTINCT FROMblocked_locks.tupleANDblocking_locks.virtualxid IS NOT DISTINCT FROMblocked_locks.virtualxidANDblocking_locks.transactionid IS NOT DISTINCT FROMblocked_locks.transactionidANDblocking_locks.classid IS NOT DISTINCT FROMblocked_locks.classidANDblocking_locks.objid IS NOT DISTINCT FROMblocked_locks.objidANDblocking_locks.objsubid IS NOT DISTINCT FROMblocked_locks.objsubidANDblocking_locks.pid!=blocked_locks.pidJOINpg_catalog.pg_stat_activity blocking_activity ONblocking_activity.pid=blocking_locks.pidWHERE NOT blocked_locks.GRANTED;
Smashing this query over and over when the problem is happening may give some insight as well:
SELECT
query,
avg(now() - query_start) AS average_duration,
usename,
pid
FROM
pg_stat_activity
WHERE
state ='active'AND query <>'<IDLE>'AND query NOT LIKE'%pg_stat_activity%'GROUP BY
query,
usename,
pid
ORDER BY
average_duration DESCLIMIT10000;
If your logs aren't helpful, ye olde ALTER SYSTEM SET log_lock_waits TO on; may yield more helpful info in the Postgres and/or Pooler logging views, as well as altering log_statement_sample_rate and log_min_duration_sample.
re: your actual question - I did implement something hideous with await Promise.race(... which did not help. We did not have any specific issues with Supavisor but switched to running our own pgbouncers.
also likewise shout out to @porsager for making an amazing library that lets me avoid the hell of ORMs.
I don't intend to answer the question, but just wanted to add to this discussion since I encountered the same issue
we use postgres.js as driver for drizzle-orm on our project and connect the service to supabase database through supavisor. to give more context, this is a next.js based project deployed on vercel. after some research on what are the suitable NPMs for this kind of project, we went with pairing drizzle-orm + postgres.js for doing backend stuffs.
we also noticed when my code has big Promise.all operation, the issue became more prevalent. so before solving this, the patching method that we used was to blame code with Promise.all and refactored it. Honestly I hated it since it hindered us from using Promise.all which is known to improve the speed of execution.
initially we thought it was the issue with supavisor, but with trial and errors also hours of google search, we finally managed to resolve (sort of) my problem with 2 methods.
connect directly to postgres with session pooler (port 5432)
change the driver from postgres.js with node-postgres
method 1 improved the stability. and after trying method 2, we realized not only it did solve the problem but also improved the system performance. thus, we decided to go with the later method.
we did some empirical test on it by doing stress-test
using node-postgres: my test endpoint took around 4-5s to response. 20vu in 1min gave better throughput
using postgres.js with direct connection: it took more than 8s in average, less throughput but all requests were responded successfully
using postgres.js with supavisor: not only worse througput than using other driver, also worse goodput by only < 80% request responded successfully
PS: I am not supporting or villaining any driver here, but I hope my findings help pinpointing the issue and yielding the solutions
We’ve recently encountered the same issue in our backend and wanted to share some findings that might help with debugging.
We’re currently using the dedicated pooler provided by Supabase (PgBouncer). Interestingly, switching to a self-hosted PgBouncer instance (via Docker) completely resolves the problem. We’ve also observed that using node-postgres does not result in this issue.
One key detail: the issue appears to be directly related to how concurrent connections are handled. When we use the max option to limit the number of active connections, it significantly influences the behavior. For example, setting max: 1 makes the issue much worse — almost all SQL commands fail or don’t go through. Increasing the value to something like max: 50 nearly eliminates the issue, but obviously that’s not a scalable or long-term solution.
If there’s anything we can do on our end to help pinpoint the root cause, we’re happy to assist.
Edit: Here is the code we are using to create the postgres client for drizzle (max setting only for test purposes)
functionmakeClient(){constdb=parseDatabaseUrl(env.DATABASE_URL);returnpostgres(env.DATABASE_URL,{/** * @see https://supabase.com/docs/guides/database/drizzle * @see https://supabase.com/docs/guides/database/connecting-to-postgres#supavisor-transaction-mode * Disable prepared statements when using pgBouncer in transaction mode, as it doesn't support them. */prepare: db.isPooler ? false : true,ssl: db.ssl,max: 1});}
We hit this exact issue in production (Supabase Pooler port 6543 + Vercel serverless). After investigation, we found a reliable reproduction and the root cause.
Reproduction
importpostgresfrom"postgres";// Connection through Supabase Pooler (PgBouncer, transaction mode)constsql=postgres(process.env.DATABASE_URL,{prepare: false,max: 3});awaitsql`SELECT 1`;// warmup// This hangs forever — 5 concurrent queries on pool of 3awaitPromise.all(Array.from({length: 5},()=>sql`SELECT 1`));
Deadlock occurs when concurrent queries exceed pool size, forcing postgres.js to pipeline queries on the same connection.
Root cause
postgres.js pipelines multiple queries on a single TCP connection by default (max_pipeline: 100). PgBouncer/Supavisor in transaction mode can reassign the backend PostgreSQL connection between pipelined queries. When this happens, the response to the pipelined query is lost — the promise hangs indefinitely.
Verification matrix
Configuration
5 concurrent SELECT 1, pool max: 3
Pooler + pipelining (default)
DEADLOCK ❌
Pooler + max_pipeline: 0
244ms ✅
Direct connection + pipelining
254ms ✅
Direct connection + max_pipeline: 0
255ms ✅
Only the combination of pooler + pipelining fails. Direct connections handle pipelining fine.
Debug trace
With debug logging, we can see the lost query:
conn=2 query=SELECT 1 AS x ← first query
conn=2 query=SELECT 1 AS x ← second query PIPELINED on same connection
conn=4 query=SELECT 1 AS x
conn=3 query=SELECT 1 AS x
conn=4 query=SELECT 1 AS x
req 1: done (conn 4)
req 4: done (conn 4)
req 0: done (conn 2, first query)
req 2: done (conn 3)
req 3: NEVER RESOLVES ← conn 2's pipelined query lost
conn 4 successfully handles 2 pipelined queries, but conn 2's second pipelined query never gets a response. The timing/backend reassignment by PgBouncer is non-deterministic.
max_pipeline: 0 = one query per connection at a time. No pipelining, no lost responses. No performance impact in practice since queries are fast and PgBouncer handles connection multiplexing.
Why small pools trigger it more
Default max: 10 means pipelining only kicks in with 11+ concurrent queries — rare. With max: 3 (common for serverless), just 4 concurrent queries trigger pipelining. Vercel recommends small pools for serverless, making this a likely hit for Supabase + Vercel users.
Environment
postgres.js 3.4.8
Supabase Pooler (PgBouncer, port 6543, transaction mode)
Vercel serverless (Node.js 24)
Drizzle ORM (but reproduction is pure postgres.js)
We hit this in production (Next.js on Vercel + Supabase Supavisor transaction mode) and root-caused it. Sharing since this issue matches our symptoms exactly (hung pool, backends stuck active/ClientRead, only recovery is killing the connection).
Root cause
postgres.js pipelines queued queries onto an already-busy connection (execute() writes the query to the socket even when another query is active). Supavisor transaction mode cannot handle pipelining: the connection wedges deterministically once ≥2 queries are pipelined behind the active one. The active query and the first pipelined query complete; the bytes of everything after are never forwarded to a backend — the pooled backend sits in ClientRead forever and every query queued on that connection hangs.
Minimal repro (any Supabase transaction-mode URL, port 6543):
Same five queries awaited sequentially: all fine. With a pool (max: 6) and 24 concurrent queries we got exactly 12 ok / 12 hung on every run — active + 1 pipelined survive per connection, the rest wedge it.
Workaround — and a small bug blocking it
max_pipeline: 0 fixes it completely (strict one-query-per-connection; our failing loads went from 50% hang to 100% clean, ~10% wall-clock cost). But max_pipeline: 0 breaks sql.begin: in execute() the onexecute callback (which reserves the connection for the transaction) is chained after the pipeline gate:
so the synthetic BEGIN completes on an unreserved connection and falsely trips UNSAFE_TRANSACTION: Only use sql.begin, sql.reserved or max: 1.
Swapping the last two terms fixes it with no behavior change otherwise (with max_pipeline: 0, sent is always empty, and onexecute returning undefined keeps the overall result falsy exactly as before):
We run that as a patch-package patch in production; happy to open a PR if wanted.
Notes:
max_pipeline: 1 does NOT help — still wedges. 0 is the only safe value against Supavisor transaction mode.
prepare: false alone is not sufficient (that's the only thing Supabase's docs mention for postgres.js).
Session mode (port 5432) is unaffected under identical load.
Arguably Supavisor should support extended-protocol pipelining or at least fail loudly; from postgres.js's side, documenting max_pipeline: 0 for transaction-mode poolers (+ the one-line fix above) would make it survivable.
We hit what looks like exactly this (queries silently never settling against Supavisor transaction mode), and were able to reduce it to a deterministic minimal repro plus a mechanism analysis. Posting in case it unblocks this issue — happy to open a separate issue instead if you'd prefer.
Minimal repro
120 concurrent parameterlesssql.unsafe() queries against a max: 15 pool, pointed at a Supabase/Supavisor transaction-mode pooler (:6543), reproduce it on every run for us (verbatim script below, re-verified immediately before posting):
importpostgresfrom"postgres";constsql=postgres(process.env.SUPAVISOR_TXN_URL,{max: 15,prepare: false,connect_timeout: 10,idle_timeout: 60,});letsettled=0;constqueries=Array.from({length: 120},(_,i)=>Promise.resolve(sql.unsafe("SELECT 1 AS one")).then(()=>settled++,(err)=>{settled++;console.log(`query ${i} rejected: ${err.message}`);}));awaitPromise.race([Promise.all(queries),newPromise((r)=>setTimeout(r,20_000)),]);console.log(`${settled}/120 settled after 20s`);
Observed output, consistently: a cluster of write CONNECTION_DESTROYED rejections, and then 34/120 settled after 20s — 86 promises never settle at all, no resolution, no rejection, indefinitely (we've waited 90s+). Smaller overloads (e.g. 6 concurrent against max: 2) reproduce the same thing intermittently — it's a race during connection ramp-up, so modest concurrency sometimes squeaks through; 8× the pool size has been 100% reliable for us.
Environment: [email protected] (the 3.4.9 diff is types-only, so latest should behave the same), Bun 1.2.13 and 1.2.21 (not yet verified under Node), Supabase Supavisor transaction pooler (aws-0-us-west-2.pooler.supabase.com:6543), prepare: false.
The discriminating matrix
We varied one factor at a time; the discriminator is whether the query carries bind parameters, not protocol, not query identity:
pool max
N concurrent
query shape
result
2
6
unsafe, no params
intermittent WEDGE (ramp-up race) — when it hits: 5/6 settle, 1 lost
15
120
unsafe, no params
WEDGE — 34/120 settle, ~86 never settle
15
120
unsafewith params ($1)
all settle, ~1.8s
15
120
tagged template
all settle, ~1.8s
15
120
unsafe, no params, { simple: false } forced
WEDGE — extended protocol does not help
15
120
unsafe, identical param [1] ×120
all settle (identity irrelevant)
15
120
no params, session pooler :5432
all settle 0.7s — overload rejects cleanly (EMAXCONNSESSION)
15
120
no params, in-flight capped at max (app-side semaphore)
With binds (and prepare: false), describeFirst is true → the client sends Parse+Describe+Flush and waits a round trip before Bind/Execute — submission is self-pacing.
Without binds, the whole sequence goes out in one pipelined write (unnamed() for extended; a single Q for simple — which is why forcing { simple: false } doesn't help).
Under concurrent pool ramp-up, those one-shot pipelined writes are what Supavisor's transaction mode kills (write CONNECTION_DESTROYED client-side). That part may arguably be Supavisor's problem.
The part that looks like a postgres-js bug regardless of who kills the connection: when the connection is destroyed, only some of its queries reject — the rest are silently lost and their promises never settle. error() does drain sent, so the leak appears to be queries associated with a connection in the connecting/queue state; we didn't pin the exact line. A destroyed connection settling all of its queries (even with rejections) would turn this from an infinite hang into a recoverable error.
Workaround
Capping in-flight unsafe() queries at the pool's max with an app-side semaphore fully avoids the wedge for us (last matrix row).
Investigation and repro by Claude (an AI agent) operated by @edobry, debugging a production hang in our own system; the matrix results are from live runs against our Supabase project.
max_pipeline: 0 is not available to Drizzle users who use transactions
@BuildShipGrowRepeat noted max_pipeline: 0 breaks sql.begin because the onexecute reservation callback is short-circuited by the pipeline gate. I confirm this.
drizzle-orm's postgres-js driver implements db.transaction() as client.begin() (session.js).
The documented happy path leads straight into this
Supabase's Drizzle guide recommends drizzle-orm + postgres, pointed at the Shared Pooler, with prepare: false and the comment "Disable prefetch as it is not supported for 'Transaction' pool mode". Follow this, but write a Promise.all, and you land here.
Question
Is issuing concurrent queries on a single client considered unsupported usage against a transaction-mode pooler?
I don't understand whether the expectation is that a postgres client handles one query at a time and pipelining is an optimisation that pooler users must opt out of, or whether pipelining is meant to be transparent and this is squarely a bug. Promise.all over independent queries seems a normal thing to write.
Ask
Could a maintainer weigh in on the intended path forward? Specifically:
Is max_pipeline: 0 the sanctioned workaround for transaction-mode poolers, or a workaround that happens to work?
If it is sanctioned — would you take a PR for the execute() reordering @BuildShipGrowRepeat proposed, so it doesn't break sql.begin?
If not — is the recommendation to "use session mode / node-postgres with Supavisor", as @akbarsahata and @pascalmtts landed on (instead of @postgres)?
Adding a reproduction, since this issue has none. We hit what looks like the same
thing and narrowed it down; posting the matrix in case it helps others land here
from a search.
Symptom
Not "queries hang" — concurrent queries return each other's data. Parameters
and result parsers cross between queries in flight:
round 1: ok
round 2: FAIL — value.map is not a function
round 5: FAIL — invalid input syntax for type uuid: "f"
round 6+: FAIL — timeout
"f" is the first character of false — a boolean arriving in a uuid parameter
slot. We also saw a text value handed to a bigint parser (Cannot convert <a name> to a BigInt) and an array parser applied to a scalar. These are positional crossing, not type coercion.
Round 1 always passes; it degrades from round 2 as the pool starts reusing
connections.
Setup
postgres 3.4.x, prepare: false
Supabase pooler (Supavisor) in transaction mode, port 6543
~12 independent queries issued concurrently via Promise.all, mixed column
types (uuid, bigint, text[], boolean), repeated on a short interval in
one long-lived process
What we measured
Configuration
Result
transaction pooler, concurrent
✗ corrupts round 1–2
transaction pooler, max: 1
✗ corrupts round 1
transaction pooler, sequential (same queries, awaited one at a time)
Also tested and not the cause: fetch_types: false, pool size, credentials,
idle connection age, and the ORM's own query cache (a fresh ORM instance per round
still corrupts).
Why we think it is pipelining
The max: 1 row is the informative one. With a single pooled connection the
concurrent callers all share it — and it still corrupts — while the same queries
awaited one at a time are clean. So the variable is not concurrency across
connections; it is more than one query in flight on a single connection.
postgres.js pipelines by default. A transaction-mode pooler binds a server
connection per transaction and releases it when it believes the statement is
complete, so pipelined independent statements can be assigned to different
backends, and their bind parameters and row descriptions cross.
pgbouncer hit the same thing and describes it in the same terms — pgbouncer/pgbouncer#203, "swapping query parameters in
txn pooling mode" — and its fix was to count expected ReadyForQuery packets so
the server is not released too early. That mechanism matches every row above,
including why session mode is clean (a dedicated server connection per client) and
why pg is clean (it queues per client rather than pipelining).
Note for anyone reproducing
Use queries whose columns have distinguishable types. We first tried eight
concurrent select 1 / select 2 and it passed — crossing between two integer
results is invisible. The failure only becomes observable when a crossed value hits
a parser that rejects it.
Confirming this against Supabase Supavisor (transaction mode, port 6543) on [email protected], Node 24, Windows — and adding two findings for anyone applying the workarounds.
Reproduction (production-shaped): { max: 4, prepare: false, idle_timeout: 20 }, concurrent bursts of parameterless sql.unsafe('select 1') interleaved with parameterized queries. Default pipelining: 11/33 pipelining-exposed promises never settled (plus some CONNECTION_DESTROYED rejections); the parameterized control group was 33/33 clean (consistent with describeFirst self-pacing under prepare: false); max_pipeline: 0 was 100% clean across the same matrix. In production this manifested for us as single lost queries with pg_stat_activity fully idle — the promise sits in the connection's private sent queue where no pool recovery path reaches it, exactly as diagnosed above.
Two notes on the max_pipeline: 0 + execute() reorder workaround (moving the onexecute term ahead of the sent.length < max_pipeline gate so sql.begin reservations still run):
Patch both builds. The package ships src/ (ESM) and cjs/src/ — patching only src/connection.js leaves require() consumers on the unpatched CJS mirror, and sql.begin keeps failing with UNSAFE_TRANSACTION there. Bit us via a CJS-resolving test harness while the ESM app worked.
max_pipeline is missing from types/index.d.tsOptions — TypeScript users need a typings addition alongside.
With both in place: sql.begin works under max_pipeline: 0 on ESM and CJS paths, drizzle-orm transactions work, and repeated burst matrices show zero losses. Happy to share the harness script if useful.
Adding a small deterministic reproduction and a measured matrix, in case it helps pin this down.
Setup:[email protected], Node 24, prepare: false, Supabase Supavisor in transaction mode (port 6543). One connection (max: 1), four queries issued at once, the third returning a result of some size:
importpostgresfrom"postgres";constcap=(p,ms)=>Promise.race([p,newPromise((r)=>setTimeout(()=>r(null),ms))]);asyncfunctiontrial(options,fillerRows){constsql=postgres(process.env.DATABASE_URL,{ssl: "require",max: 1,prepare: false,idle_timeout: 2, ...options});constanswers=awaitPromise.all([sql`select 1 as a`,sql`select 2 as b`,sql`select repeat('x', 30) as filler from generate_series(1, ${fillerRows}::int)`,sql`select 3 as c`,].map((q)=>cap(q.then((rows)=>rows.length,()=>"error"),6000)),);awaitPromise.race([sql.end({timeout: 1}),newPromise((r)=>setTimeout(r,1000))]);returnanswers.every((a)=>a!==null);// null = never settled}for(const[label,options]of[["default pipelining",{}],["max_pipeline: 0",{max_pipeline: 0}]]){for(constrowsof[500,5000]){letcomplete=0;for(leti=0;i<10;i++)if(awaittrial(options,rows))complete++;console.log(`${label}, ${rows} filler rows: ${complete}/10 trials answered every query`);}}
Result:
500 filler rows
5,000 filler rows
default pipelining
2/10 trials answered every query
0/10
max_pipeline: 0
10/10
10/10
Measured separately, with a replay of the exact query sequence that hung in our app rather than this script: max_pipeline: 1 and 2 still lost the query, max_pipeline: 0 did not, and the same app-level reproduction pointed at the session-mode pooler (port 5432) never lost one.
The lost query is the one pipelined behind the larger result (and whatever is pipelined after it): its promise never settles, no error is raised, and it never reaches Postgres (not visible in pg_stat_activity, no lock involved). statement_timeout and connect_timeout therefore never fire; in our app it surfaced as a page that hung for ever once a request used all max connections and postgres.js started pipelining.
What we shipped: max_pipeline: 0, plus the execute() reorder from #1210 / #1211 (so sql.begin still works), applied to both src/ and cjs/src/, plus an application-side deadline on every awaited query that cancels it and logs the SQL, so a lost query becomes an error instead of a hang.
One unconfirmed observation, offered with that caveat: while this reproduction was running against the pooler, an unrelated test in a different process failed once with malformed array literal on a text-array parameter, which looks like the parameter crossing described above. We did not try to reproduce that deliberately.
Another confirmation, plus a small patch that keeps sql.begin working, unlike max_pipeline: 0.
Against Supavisor 2.9.13 in transaction mode (local docker), with postgres.js 3.4.9 and prepare: false: at max: 1, issuing 4 parameterless queries at once leaves 2 that never settle. Connecting directly to Postgres, nothing hangs. Supavisor has a fix on main (supabase/supavisor#1239, supabase/supavisor#1207), but it isn't released yet.
The pipelining comes from the pool, not from connection.execute(). handler() sends to a busy connection when none is free, and onopen() drains several queued queries onto one connection in a single write. This patch queues instead. Transaction and reserve() handlers are untouched, so pipelining inside sql.begin still works; there the backend stays pinned because ReadyForQuery is T. Apply the same change to src/, cjs/src/ and cf/src/:
--- a/src/index.js+++ b/src/index.js
@@ function handler(query) {
if (closed.length)
return connect(closed.shift(), query)
- busy.length- ? go(busy.shift(), query)- : queries.push(query)+ queries.push(query)
}
@@ function onopen(c) {
if (queries.length === 0)
return move(c, open)
- let max = Math.ceil(queries.length / (connecting.length + 1))- , ready = true-- while (ready && queries.length && max-- > 0) {- const query = queries.shift()- if (query.reserve)- return query.reserve(c)-- ready = c.execute(query)- }-- ready+ const query = queries.shift()+ if (query.reserve)+ return query.reserve(c)++ c.execute(query)
? move(c, busy)
: move(c, full)
}
With the patch, the same harness gives 0 hangs across mixed parameterless and parameterised queries and concurrent sql.begin calls, including 40 queries at max: 2. We apply it with pnpmpatchedDependencies.
An opt-in option to turn off pool-level pipelining would make this unnecessary, and would help anyone behind a transaction-mode pooler. So would #1211 landing, since that makes max_pipeline: 0 usable with transactions.
v4 rewrote the pool and fixed several hangs, and is tested through PgBouncer in transaction mode; queue_timeout turns a wait for a connection into an error. If it still hangs through Supavisor on v4, please open a new issue.
Activity
nikhilro commentedon Oct 27, 2024
I'm more confident that is an issue with Supavisor under load. A thing that would be helpful is postgres.js statement limit.
I know we have:
But, that is not useful when connecting to transaction mode poolers.
Is there an easy way to "abort" the query if it's taking too long?
lllleonnnn commentedon Nov 26, 2024
Please forgive not answering your exact question but we have run into very similar issues and it boiled down to our queries being blocking & locking. We've used this query (modify as needed) to run down issues in our Supabase PG instance:
Smashing this query over and over when the problem is happening may give some insight as well:
If your logs aren't helpful, ye olde
ALTER SYSTEM SET log_lock_waits TO on;may yield more helpful info in the Postgres and/or Pooler logging views, as well as alteringlog_statement_sample_rateandlog_min_duration_sample.re: your actual question - I did implement something hideous with
await Promise.race(...which did not help. We did not have any specific issues with Supavisor but switched to running our own pgbouncers.also likewise shout out to @porsager for making an amazing library that lets me avoid the hell of ORMs.
akbarsahata commentedon Mar 25, 2025
I don't intend to answer the question, but just wanted to add to this discussion since I encountered the same issue
we use postgres.js as driver for drizzle-orm on our project and connect the service to supabase database through supavisor. to give more context, this is a next.js based project deployed on vercel. after some research on what are the suitable NPMs for this kind of project, we went with pairing drizzle-orm + postgres.js for doing backend stuffs.
we also noticed when my code has big Promise.all operation, the issue became more prevalent. so before solving this, the patching method that we used was to blame code with Promise.all and refactored it. Honestly I hated it since it hindered us from using Promise.all which is known to improve the speed of execution.
initially we thought it was the issue with supavisor, but with trial and errors also hours of google search, we finally managed to resolve (sort of) my problem with 2 methods.
method 1 improved the stability. and after trying method 2, we realized not only it did solve the problem but also improved the system performance. thus, we decided to go with the later method.
we did some empirical test on it by doing stress-test
PS: I am not supporting or villaining any driver here, but I hope my findings help pinpointing the issue and yielding the solutions
porsager commentedon Mar 25, 2025
It's great @akbarsahata , but can you please share some code? 😊
pascalmtts commentedon Jul 30, 2025
We’ve recently encountered the same issue in our backend and wanted to share some findings that might help with debugging.
We’re currently using the dedicated pooler provided by Supabase (PgBouncer). Interestingly, switching to a self-hosted PgBouncer instance (via Docker) completely resolves the problem. We’ve also observed that using node-postgres does not result in this issue.
One key detail: the issue appears to be directly related to how concurrent connections are handled. When we use the max option to limit the number of active connections, it significantly influences the behavior. For example, setting max: 1 makes the issue much worse — almost all SQL commands fail or don’t go through. Increasing the value to something like max: 50 nearly eliminates the issue, but obviously that’s not a scalable or long-term solution.
If there’s anything we can do on our end to help pinpoint the root cause, we’re happy to assist.
Edit: Here is the code we are using to create the postgres client for drizzle (max setting only for test purposes)
AnDeVerin commentedon Apr 11, 2026
Minimal reproduction + root cause analysis
We hit this exact issue in production (Supabase Pooler port 6543 + Vercel serverless). After investigation, we found a reliable reproduction and the root cause.
Reproduction
Deadlock occurs when concurrent queries exceed pool size, forcing postgres.js to pipeline queries on the same connection.
Root cause
postgres.js pipelines multiple queries on a single TCP connection by default (
max_pipeline: 100). PgBouncer/Supavisor in transaction mode can reassign the backend PostgreSQL connection between pipelined queries. When this happens, the response to the pipelined query is lost — the promise hangs indefinitely.Verification matrix
SELECT 1, pool max: 3max_pipeline: 0max_pipeline: 0Only the combination of pooler + pipelining fails. Direct connections handle pipelining fine.
Debug trace
With debug logging, we can see the lost query:
conn 4 successfully handles 2 pipelined queries, but conn 2's second pipelined query never gets a response. The timing/backend reassignment by PgBouncer is non-deterministic.
Workaround
max_pipeline: 0= one query per connection at a time. No pipelining, no lost responses. No performance impact in practice since queries are fast and PgBouncer handles connection multiplexing.Why small pools trigger it more
Default
max: 10means pipelining only kicks in with 11+ concurrent queries — rare. Withmax: 3(common for serverless), just 4 concurrent queries trigger pipelining. Vercel recommends small pools for serverless, making this a likely hit for Supabase + Vercel users.Environment
fix(migrate-xlsx): retry transient pooler drops with grounded error m…
fix(migration): addressKey null-bug + tcv lib + findServiceAddressByK…
fix(server): disable pipelining on the txn pooler to fix the pool-wed…
fix(db): session-mode-ready pool options + restore manual-only prod d…
BuildShipGrowRepeat commentedon Jul 15, 2026
We hit this in production (Next.js on Vercel + Supabase Supavisor transaction mode) and root-caused it. Sharing since this issue matches our symptoms exactly (hung pool, backends stuck
active/ClientRead, only recovery is killing the connection).Root cause
postgres.js pipelines queued queries onto an already-busy connection (
execute()writes the query to the socket even when another query is active). Supavisor transaction mode cannot handle pipelining: the connection wedges deterministically once ≥2 queries are pipelined behind the active one. The active query and the first pipelined query complete; the bytes of everything after are never forwarded to a backend — the pooled backend sits inClientReadforever and every query queued on that connection hangs.Minimal repro (any Supabase transaction-mode URL, port 6543):
Same five queries awaited sequentially: all fine. With a pool (
max: 6) and 24 concurrent queries we got exactly 12 ok / 12 hung on every run — active + 1 pipelined survive per connection, the rest wedge it.Workaround — and a small bug blocking it
max_pipeline: 0fixes it completely (strict one-query-per-connection; our failing loads went from 50% hang to 100% clean, ~10% wall-clock cost). Butmax_pipeline: 0breakssql.begin: inexecute()theonexecutecallback (which reserves the connection for the transaction) is chained after the pipeline gate:so the synthetic
BEGINcompletes on an unreserved connection and falsely tripsUNSAFE_TRANSACTION: Only use sql.begin, sql.reserved or max: 1.Swapping the last two terms fixes it with no behavior change otherwise (with
max_pipeline: 0,sentis always empty, andonexecutereturningundefinedkeeps the overall result falsy exactly as before):We run that as a patch-package patch in production; happy to open a PR if wanted.
Notes:
max_pipeline: 1does NOT help — still wedges. 0 is the only safe value against Supavisor transaction mode.prepare: falsealone is not sufficient (that's the only thing Supabase's docs mention for postgres.js).max_pipeline: 0for transaction-mode poolers (+ the one-line fix above) would make it survivable.edobry commentedon Jul 15, 2026
We hit what looks like exactly this (queries silently never settling against Supavisor transaction mode), and were able to reduce it to a deterministic minimal repro plus a mechanism analysis. Posting in case it unblocks this issue — happy to open a separate issue instead if you'd prefer.
Minimal repro
120 concurrent parameterless
sql.unsafe()queries against amax: 15pool, pointed at a Supabase/Supavisor transaction-mode pooler (:6543), reproduce it on every run for us (verbatim script below, re-verified immediately before posting):Observed output, consistently: a cluster of
write CONNECTION_DESTROYEDrejections, and then34/120 settled after 20s— 86 promises never settle at all, no resolution, no rejection, indefinitely (we've waited 90s+). Smaller overloads (e.g. 6 concurrent againstmax: 2) reproduce the same thing intermittently — it's a race during connection ramp-up, so modest concurrency sometimes squeaks through; 8× the pool size has been 100% reliable for us.Environment: [email protected] (the 3.4.9 diff is types-only, so latest should behave the same), Bun 1.2.13 and 1.2.21 (not yet verified under Node), Supabase Supavisor transaction pooler (
aws-0-us-west-2.pooler.supabase.com:6543),prepare: false.The discriminating matrix
We varied one factor at a time; the discriminator is whether the query carries bind parameters, not protocol, not query identity:
unsafe, no paramsunsafe, no paramsunsafewith params ($1)unsafe, no params,{ simple: false }forcedunsafe, identical param[1]×120:5432EMAXCONNSESSION)max(app-side semaphore)Why binds-presence is the variable
In
build()(connection.js):prepare: false),describeFirstis true → the client sendsParse+Describe+Flushand waits a round trip beforeBind/Execute— submission is self-pacing.unnamed()for extended; a singleQfor simple — which is why forcing{ simple: false }doesn't help).Under concurrent pool ramp-up, those one-shot pipelined writes are what Supavisor's transaction mode kills (
write CONNECTION_DESTROYEDclient-side). That part may arguably be Supavisor's problem.The part that looks like a postgres-js bug regardless of who kills the connection: when the connection is destroyed, only some of its queries reject — the rest are silently lost and their promises never settle.
error()does drainsent, so the leak appears to be queries associated with a connection in the connecting/queue state; we didn't pin the exact line. A destroyed connection settling all of its queries (even with rejections) would turn this from an infinite hang into a recoverable error.Workaround
Capping in-flight
unsafe()queries at the pool'smaxwith an app-side semaphore fully avoids the wedge for us (last matrix row).Investigation and repro by Claude (an AI agent) operated by @edobry, debugging a production hang in our own system; the matrix results are from live runs against our Supabase project.
43jay commentedon Jul 28, 2026
(claude and) I hit this standing up an ordinary Next.js app on a freshly seeded database with a single user and no load at all.
The triggering code is one route handler doing idiomatic JS:
max: 1, default pipelinemax: 5, default pipelinemax: 5,max_pipeline: 1max: 1,max_pipeline: 1max: 5,max_pipeline: 0max: 1,max_pipeline: 0max: 5, sequentialawaitsVersions:
[email protected],[email protected], Next.js 16.2.12, Node 22/23, Supabase transaction pooler.max_pipeline: 0is not available to Drizzle users who use transactions@BuildShipGrowRepeat noted
max_pipeline: 0breakssql.beginbecause theonexecutereservation callback is short-circuited by the pipeline gate. I confirm this.drizzle-orm's postgres-js driver implementsdb.transaction()asclient.begin()(session.js).The documented happy path leads straight into this
Supabase's Drizzle guide recommends
drizzle-orm+postgres, pointed at the Shared Pooler, withprepare: falseand the comment "Disable prefetch as it is not supported for 'Transaction' pool mode". Follow this, but write aPromise.all, and you land here.Question
Is issuing concurrent queries on a single client considered unsupported usage against a transaction-mode pooler?
I don't understand whether the expectation is that a
postgresclient handles one query at a time and pipelining is an optimisation that pooler users must opt out of, or whether pipelining is meant to be transparent and this is squarely a bug.Promise.allover independent queries seems a normal thing to write.Ask
Could a maintainer weigh in on the intended path forward? Specifically:
max_pipeline: 0the sanctioned workaround for transaction-mode poolers, or a workaround that happens to work?execute()reordering @BuildShipGrowRepeat proposed, so it doesn't breaksql.begin?brianjeffrelyarson commentedon Aug 3, 2026
Adding a reproduction, since this issue has none. We hit what looks like the same
thing and narrowed it down; posting the matrix in case it helps others land here
from a search.
Symptom
Not "queries hang" — concurrent queries return each other's data. Parameters
and result parsers cross between queries in flight:
"f"is the first character offalse— a boolean arriving in auuidparameterslot. We also saw a
textvalue handed to abigintparser (Cannot convert <a name> to a BigInt) and an array parser applied to a scalar. These arepositional crossing, not type coercion.
Round 1 always passes; it degrades from round 2 as the pool starts reusing
connections.
Setup
postgres3.4.x,prepare: falsePromise.all, mixed columntypes (
uuid,bigint,text[],boolean), repeated on a short interval inone long-lived process
What we measured
max: 1pg(node-postgres) instead, concurrentAlso tested and not the cause:
fetch_types: false, pool size, credentials,idle connection age, and the ORM's own query cache (a fresh ORM instance per round
still corrupts).
Why we think it is pipelining
The
max: 1row is the informative one. With a single pooled connection theconcurrent callers all share it — and it still corrupts — while the same queries
awaited one at a time are clean. So the variable is not concurrency across
connections; it is more than one query in flight on a single connection.
postgres.js pipelines by default. A transaction-mode pooler binds a server
connection per transaction and releases it when it believes the statement is
complete, so pipelined independent statements can be assigned to different
backends, and their bind parameters and row descriptions cross.
pgbouncer hit the same thing and describes it in the same terms —
pgbouncer/pgbouncer#203, "swapping query parameters in
txn pooling mode" — and its fix was to count expected
ReadyForQuerypackets sothe server is not released too early. That mechanism matches every row above,
including why session mode is clean (a dedicated server connection per client) and
why
pgis clean (it queues per client rather than pipelining).Note for anyone reproducing
Use queries whose columns have distinguishable types. We first tried eight
concurrent
select 1/select 2and it passed — crossing between two integerresults is invisible. The failure only becomes observable when a crossed value hits
a parser that rejects it.
self-similar commentedon Aug 9, 2026
Confirming this against Supabase Supavisor (transaction mode, port 6543) on
[email protected], Node 24, Windows — and adding two findings for anyone applying the workarounds.Reproduction (production-shaped):
{ max: 4, prepare: false, idle_timeout: 20 }, concurrent bursts of parameterlesssql.unsafe('select 1')interleaved with parameterized queries. Default pipelining: 11/33 pipelining-exposed promises never settled (plus someCONNECTION_DESTROYEDrejections); the parameterized control group was 33/33 clean (consistent withdescribeFirstself-pacing underprepare: false);max_pipeline: 0was 100% clean across the same matrix. In production this manifested for us as single lost queries withpg_stat_activityfully idle — the promise sits in the connection's privatesentqueue where no pool recovery path reaches it, exactly as diagnosed above.Two notes on the
max_pipeline: 0+execute()reorder workaround (moving theonexecuteterm ahead of thesent.length < max_pipelinegate sosql.beginreservations still run):src/(ESM) andcjs/src/— patching onlysrc/connection.jsleavesrequire()consumers on the unpatched CJS mirror, andsql.beginkeeps failing withUNSAFE_TRANSACTIONthere. Bit us via a CJS-resolving test harness while the ESM app worked.max_pipelineis missing fromtypes/index.d.tsOptions— TypeScript users need a typings addition alongside.With both in place:
sql.beginworks undermax_pipeline: 0on ESM and CJS paths, drizzle-orm transactions work, and repeated burst matrices show zero losses. Happy to share the harness script if useful.fix(api,worker): cambiamos de driver de Postgres, que el anterior se …
Hamzahouscene commentedon Sep 19, 2026
Adding a small deterministic reproduction and a measured matrix, in case it helps pin this down.
Setup: [email protected], Node 24,
prepare: false, Supabase Supavisor in transaction mode (port 6543). One connection (max: 1), four queries issued at once, the third returning a result of some size:Result:
max_pipeline: 0Measured separately, with a replay of the exact query sequence that hung in our app rather than this script:
max_pipeline: 1and2still lost the query,max_pipeline: 0did not, and the same app-level reproduction pointed at the session-mode pooler (port 5432) never lost one.The lost query is the one pipelined behind the larger result (and whatever is pipelined after it): its promise never settles, no error is raised, and it never reaches Postgres (not visible in
pg_stat_activity, no lock involved).statement_timeoutandconnect_timeouttherefore never fire; in our app it surfaced as a page that hung for ever once a request used allmaxconnections and postgres.js started pipelining.What we shipped:
max_pipeline: 0, plus theexecute()reorder from #1210 / #1211 (sosql.beginstill works), applied to bothsrc/andcjs/src/, plus an application-side deadline on every awaited query that cancels it and logs the SQL, so a lost query becomes an error instead of a hang.One unconfirmed observation, offered with that caveat: while this reproduction was running against the pooler, an unrelated test in a different process failed once with
malformed array literalon a text-array parameter, which looks like the parameter crossing described above. We did not try to reproduce that deliberately.DB driver: node-postgres instead of postgres.js (root cause of the ha…
rahulsingh00 commentedon Oct 19, 2026
Another confirmation, plus a small patch that keeps
sql.beginworking, unlikemax_pipeline: 0.Against Supavisor 2.9.13 in transaction mode (local docker), with postgres.js 3.4.9 and
prepare: false: atmax: 1, issuing 4 parameterless queries at once leaves 2 that never settle. Connecting directly to Postgres, nothing hangs. Supavisor has a fix onmain(supabase/supavisor#1239, supabase/supavisor#1207), but it isn't released yet.The pipelining comes from the pool, not from
connection.execute().handler()sends to a busy connection when none is free, andonopen()drains several queued queries onto one connection in a single write. This patch queues instead. Transaction andreserve()handlers are untouched, so pipelining insidesql.beginstill works; there the backend stays pinned because ReadyForQuery isT. Apply the same change tosrc/,cjs/src/andcf/src/:With the patch, the same harness gives 0 hangs across mixed parameterless and parameterised queries and concurrent
sql.begincalls, including 40 queries atmax: 2. We apply it withpnpmpatchedDependencies.An opt-in option to turn off pool-level pipelining would make this unnecessary, and would help anyone behind a transaction-mode pooler. So would #1211 landing, since that makes
max_pipeline: 0usable with transactions.porsager commentedon Oct 29, 2026
v4 rewrote the pool and fixed several hangs, and is tested through PgBouncer in transaction mode;
queue_timeoutturns a wait for a connection into an error. If it still hangs through Supavisor on v4, please open a new issue.