Last reviewed: 21 Nov 2026
A pharmacy checkout on our POS SaaS froze at 6:40pm. The cashier had already taken cash. The "paid" update never came back, and thirty seconds later every new request from the till started failing with FATAL: remaining connection slots are reserved for non-replication superuser connections. CPU on the database was quiet. The session that mattered was not running a query at all. It was sitting in PostgreSQL idle in transaction — pid 4182 had updated an orders row, then waited on a payment API, and never sent COMMIT.
I see this more often than a sudden traffic spike. An open transaction holds its row locks, holds its connection slot, and can block VACUUM. Leave a few of those sessions around and you will also hit FATAL: sorry, too many clients already. This guide is how I find those sessions, unblock the app, and stop the code that creates them. The unique connection-limit and PgBouncer details from our older "too many connections" and "remaining connection slots are reserved" posts now live here, with pointers to the deeper pooling guides where those topics already have their own home.
What "idle in transaction" actually means
Every backend in pg_stat_activity has a state. The four I look at first are:
active— the session is running a query now.idle— connected, waiting for the next command, with no open transaction. This is normal for a pool.idle in transaction— a transaction is open, and the session is waiting for the client to send the next command.idle in transaction (aborted)— a statement inside the transaction failed, and the client has not yet sentROLLBACK. Every further query in that session fails withERROR: current transaction is aborted, commands ignored until end of transaction block(SQLSTATE 25P02).
A few milliseconds between statements is normal. The problem starts when that gap becomes seconds or minutes. PostgreSQL will not close the transaction for you unless you set a timeout. The client opened it; the client has to finish it.
A one-minute diagnosis
Connect as a superuser or a role that can read pg_stat_activity and terminate backends. I start with a count, then I look at the oldest open transaction. Do not raise max_connections until you have read these two results.
SHOW max_connections;
SHOW superuser_reserved_connections;
SELECT state, count(*)
FROM pg_stat_activity
WHERE backend_type = 'client backend'
GROUP BY state
ORDER BY count(*) DESC;On the pharmacy database that evening the interesting lines looked like this:
max_connections | 100
superuser_reserved_connections | 3
state | count
----------------------------+-------
idle | 61
idle in transaction | 4
active | 9Application roles can use max_connections - superuser_reserved_connections slots. Here that is 97. We were already close, and four of those slots were doing no work. Next I find the oldest one and whatever it is blocking:
SELECT pid,
usename,
application_name,
client_addr,
state,
now() - xact_start AS xact_age,
now() - state_change AS idle_for,
left(query, 120) AS last_query
FROM pg_stat_activity
WHERE state IN ('idle in transaction', 'idle in transaction (aborted)')
ORDER BY xact_start;
SELECT pid,
pg_blocking_pids(pid) AS blocked_by,
wait_event_type,
wait_event,
now() - query_start AS waiting_for,
left(query, 120) AS query
FROM pg_stat_activity
WHERE cardinality(pg_blocking_pids(pid)) > 0;Expected shape when this is your incident:
pid | usename | application_name | state | xact_age | idle_for | last_query
------+----------+------------------+----------------------+----------+----------+-------------------------------
4182 | app_user | laravel | idle in transaction | 00:11:07 | 00:10:54 | UPDATE orders SET status = $1
pid | blocked_by | wait_event_type | wait_event | waiting_for | query
------+------------+-----------------+------------+-------------+---------------------------
4220 | {4182} | Lock | transactionid | 00:09:41 | UPDATE orders SET status = $1
4221 | {4182} | Lock | transactionid | 00:08:12 | UPDATE orders SET status = $1The last statement in query is the clue to the code. Here it was the checkout update, and the eleven-minute gap was the payment HTTP call. To see the exact locks on that pid:
SELECT l.pid, l.locktype, l.mode, l.granted, c.relname
FROM pg_locks l
LEFT JOIN pg_class c ON c.oid = l.relation
WHERE l.pid = 4182;If checkout is hanging: end the blocker, then fix the code
Terminating the session rolls the transaction back, drops the locks, and frees the slot. Confirm the pid first. Do not terminate pid = pg_backend_pid(), and be careful with pids that belong to a migration you still want to finish.
SELECT pg_terminate_backend(4182);
-- t
-- every idle transaction older than 10 minutes, excluding your own session
SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE state LIKE 'idle in transaction%'
AND xact_start < now() - interval '10 minutes'
AND pid <> pg_backend_pid();The blocked checkouts should proceed. If a migration such as CREATE INDEX or php artisan migrate is the one waiting, you can target that blocker's pid the same way. Then fix the application so you are not doing this every Friday evening.
The pharmacy bug was a payment call inside the transaction. Move slow work out, keep the database work short, and dispatch follow-up jobs only after commit:
use Illuminate\Support\Facades\DB;
$charge = $paymentGateway->charge($order->total);
DB::transaction(function () use ($order, $charge) {
$order->update(['status' => 'paid', 'charge_id' => $charge->id]);
$order->items()->update(['reserved' => false]);
});
SendReceipt::dispatch($order)->afterCommit();If you must use a manual begin, roll back in catch and never swallow the exception without it:
DB::beginTransaction();
try {
// queries only — no HTTP, email, file uploads or sleep
DB::commit();
} catch (\Throwable $e) {
DB::rollBack();
throw $e;
}If the leak is in Node, Python, a GUI or a worker
The same shape appears outside Laravel. In node-postgres, a client taken with pool.connect() that runs BEGIN and is never released will sit idle in transaction until the process dies:
const client = await pool.connect();
try {
await client.query('BEGIN');
await client.query(
'UPDATE orders SET status = $1 WHERE id = $2',
['paid', id]
);
await client.query('COMMIT');
} catch (err) {
await client.query('ROLLBACK');
throw err;
} finally {
client.release();
}Python's psycopg2 opens a transaction on the first query unless autocommit is on. A long reporting script that only reads, and never commits, stays idle in transaction for the whole run. Use autocommit or an explicit commit for read-only jobs. In a GUI such as DBeaver or pgAdmin, manual-commit mode plus a forgotten BEGIN is the human version of the same bug — including a psql session left open over lunch.
Queue workers make this worse because they keep a connection for hours. One leaked transaction lives until the worker restarts. Keep transactions to database work, and if a long job waits on an external API, disconnect or return the client first.
If you also see "too many clients" or reserved connection slots
Idle-in-transaction sessions count against max_connections just like busy ones. Once application roles have used every slot not reserved for superusers, new clients fail with one of these:
FATAL: sorry, too many clients already
FATAL: remaining connection slots are reserved for non-replication superuser connections
FATAL: remaining connection slots are reserved for roles with the SUPERUSER attribute
FATAL: remaining connection slots are reserved for roles with privileges of the "pg_use_reserved_connections" roleLaravel wraps the first of those as SQLSTATE[08006] [7] ... FATAL: sorry, too many clients already. node-postgres reports code: '53300'. Prisma says it has too many database connections open. They are the same capacity problem.
See who is holding the slots before you change anything:
SELECT usename, application_name, client_addr, state, count(*)
FROM pg_stat_activity
WHERE backend_type = 'client backend'
GROUP BY usename, application_name, client_addr, state
ORDER BY count(*) DESC;Free the obvious leaks first — idle in transaction, then (with care) ordinary idle sessions that have been sitting for a long time and are not behind a pooler you still need:
SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE usename = 'app_user'
AND state IN ('idle', 'idle in transaction')
AND now() - state_change > interval '10 minutes'
AND pid <> pg_backend_pid();Cap noisy roles and databases so a reporting tool cannot eat the whole server:
ALTER ROLE app_worker CONNECTION LIMIT 30;
ALTER DATABASE reporting CONNECTION LIMIT 20;Raising max_connections is a last resort, not a fix. Each backend uses memory, and a restart is required:
ALTER SYSTEM SET max_connections = 200;
-- sudo systemctl restart postgresql
-- or, in Docker: postgres -c max_connections=200If the count is high because every PHP-FPM worker, Node process and Prisma client holds its own set of connections, you need a pool in front of PostgreSQL, not a bigger ceiling. I cover that in How to Fix PostgreSQL Connection Pool Exhaustion and in the PgBouncer PostgreSQL setup guide. A typical starting point for transaction pooling looks like this:
[databases]
appdb = host=127.0.0.1 port=5432 dbname=appdb
[pgbouncer]
listen_addr = 0.0.0.0
listen_port = 6432
auth_type = scram-sha-256
auth_file = /etc/pgbouncer/userlist.txt
pool_mode = transaction
max_client_conn = 1000
default_pool_size = 20On the application side, create one pool per process and always release it. In Laravel, keep PDO::ATTR_PERSISTENT off unless you have a clear reason, and call DB::disconnect() in a long job that waits on an external API. In Node, set max on a single shared Pool. In Prisma, reuse one client and cap it, for example connection_limit=5 in the database URL, so hot reload does not open a new pool on every change.
Put a timeout on the role, then prove it
After the code fix, I still set idle_in_transaction_session_timeout on the application role. It is the safety net for the next forgotten BEGIN. New sessions pick the value up; existing ones do not.
ALTER ROLE app_user SET idle_in_transaction_session_timeout = '60s';
-- or, for a single database:
-- ALTER DATABASE app_db SET idle_in_transaction_session_timeout = '60s';
-- in a fresh session
SHOW idle_in_transaction_session_timeout;
-- 1minTo prove it, open psql as app_user, run BEGIN; SELECT 1;, and wait longer than the limit. The next command should fail with FATAL: terminating connection due to idle-in-transaction timeout (SQLSTATE 25P03 in Laravel). Then run the diagnosis queries again: you should see no stale idle-in-transaction rows, and pg_blocking_pids should be empty during normal traffic. If a migration must wait on a lock, fail fast instead of queueing behind it:
SET lock_timeout = '5s';idle_session_timeout (PostgreSQL 14+) can also reap plain idle connections, but be careful behind a pooler — a 30-minute timeout on session-mode pooling can drop connections the pool still thinks are good. Prefer idle_in_transaction_session_timeout first. In Docker you can set the latter at start time, in milliseconds:
command: postgres -c idle_in_transaction_session_timeout=60000If queries themselves run for too long, that is a different state (active), and I treat it in How to Find and Terminate Long-Running PostgreSQL Queries.
Common mistakes I still catch in review
- Raising
max_connectionsbecause the error said "too many clients," without looking atidle in transactionfirst. - Calling a payment gateway, sending mail, or uploading a file between
BEGINandCOMMIT. - Catching an exception after
DB::beginTransaction()and not rolling back. - Taking a
pgclient withpool.connect()and returning from an error path withoutclient.release(). - Leaving
idle_in_transaction_session_timeoutat0on the application role. - Setting
idle_session_timeoutaggressively in front of PgBouncer session pooling. - Terminating a pid that belongs to a migration you still need, or terminating your own
psqlsession. - Treating
idlepooled connections as a leak. Those are normal. The dangerous state isidle in transaction.
Questions I get asked
Is idle in transaction always a problem?
No. Every transaction is briefly idle between statements. It becomes a problem when the same pid stays in that state for many seconds or minutes, holds locks others need, or appears in large numbers and fills the connection limit.
How is this different from "too many connections"?
Idle in transaction is a session state. "Too many clients already" and "remaining connection slots are reserved" are what you see when those sessions (and everything else) have used every application slot. Fix the open transactions first; add pooling if the healthy connection count is still too high.
Will pg_terminate_backend lose committed data?
It rolls back only the open transaction on that pid. Statements already committed in earlier transactions stay committed. That is why a payment call inside the transaction is so painful: you may have charged the card and then rolled back the "paid" update when the session is killed.
Why does a table keep growing while the row count is stable?
An old open transaction can stop autovacuum from removing dead row versions. End the idle transaction, then check last_autovacuum in pg_stat_user_tables. Table bloat should stop growing once the oldest transaction is recent again.
Can I set the timeout to a few seconds?
Only if every real transaction in that role finishes faster than the timeout, including brief reporting queries. I use 30–60 seconds for a web role. A batch role that legitimately holds a transaction longer gets a higher value, not a disabled one.
About the author. Muhammad Wilayat Shah is a senior full-stack engineer and team lead based in Islamabad, with 13+ years shipping ERP and multi-tenant SaaS products — including pharmacy POS, Campus School ERP, and delivery platforms — on Laravel, React and PostgreSQL. He wrote this after a checkout on a pharmacy POS SaaS hung on a payment API call inside an open transaction, then filled the remaining connection slots. More at wilayats.com/about.
Last reviewed: 21 Nov 2026




Comments
Join the discussion. Replies load on demand, up to 5 levels.
0 threads
No comments yet
Be the first to start the conversation.