"current transaction is aborted, commands ignored until end of transaction block" means that some earlier statement inside the same transaction failed, and PostgreSQL has put the whole transaction into an aborted state. Every following statement gets this error until the client ends the transaction. The message itself tells you nothing about the cause; the useful error is the one before it.
BEGIN;
INSERT INTO orders (id, customer_id) VALUES (1, 42);
INSERT INTO orders (id, customer_id) VALUES (1, 43);
-- ERROR: duplicate key value violates unique constraint "orders_pkey"
SELECT count(*) FROM orders;
-- ERROR: current transaction is aborted, commands ignored until end of transaction block
COMMIT;
-- ROLLBACK
The SQLSTATE is 25P02, condition name in_failed_sql_transaction (error codes). Unlike some databases, PostgreSQL does not let you skip the failed statement and carry on: once anything in a transaction block fails, only the end of the transaction or a rollback to a savepoint set before the failure gets you out.
Step 1: find the first error
Developers usually see the 25P02 message, because it is the one their code hits next, often in a completely unrelated query. The original failure is earlier on the same connection:
- Server log. With the default
log_min_error_statement = ERROR, the server logs the text of every statement that fails with an error (logging settings). Look for the last error from the same process ID just before the first 25P02 line. Adding%ptolog_line_prefixmakes this easy if it is not there yet. - Application logs. In our experience the original exception is often caught and logged at debug level, or swallowed by a generic
except/catchthat lets the code go on using the same connection. That swallow is the real bug.
Typical first errors are constraint violations, a type conversion failure, a lock or statement timeout, a deadlock, or a serialization failure. Fix that one, and the 25P02 noise disappears with it.
Step 2: end the transaction properly
An aborted transaction can only be closed with ROLLBACK. You can type COMMIT, but it will not commit anything: in an aborted transaction PostgreSQL treats COMMIT exactly like ROLLBACK and even returns the command tag ROLLBACK (COMMIT). The documentation notes that this differs from the SQL standard, which would raise an error. Code that issues COMMIT without checking the outcome can therefore believe work was saved when it was not; in our experience this is how "the data just disappeared" tickets start.
In application code, the rule is simple: when any statement in a transaction raises an error, roll back (or let your framework's transaction block do it) before using that connection again. With psycopg 3 the documentation says it plainly: after an error the server refuses further commands until rollback() is called, and the error you get in the meantime is InFailedSqlTransaction (psycopg transactions). The with conn.transaction(): block rolls back for you when an exception leaves it.
Step 3: if one statement is allowed to fail, use a savepoint
Sometimes failure of one step is acceptable: an optional audit insert, an "insert, and if it exists, do something else" step. Wrap it in a savepoint:
BEGIN;
INSERT INTO orders (id, customer_id) VALUES (1, 42);
SAVEPOINT before_optional_step;
INSERT INTO order_audit (order_id, note) VALUES (1, 'imported');
-- if this fails:
ROLLBACK TO SAVEPOINT before_optional_step;
-- the transaction is usable again; the first INSERT is still there
COMMIT;
ROLLBACK TO SAVEPOINT undoes everything after the savepoint, destroys savepoints created after it, and leaves the savepoint itself valid for reuse (ROLLBACK TO SAVEPOINT). Savepoints exist only inside a transaction block (SAVEPOINT). For duplicate keys, INSERT ... ON CONFLICT is usually a better answer than catching the error at all.
The same mechanism sits behind several tools you may already use:
- psql has
ON_ERROR_ROLLBACK. Withon, psql issues an implicitSAVEPOINTbefore each command in a transaction block and rolls back to it if the command fails;interactivedoes this only in interactive sessions, not when reading script files;offis the default (psql). - pgJDBC has the
autosaveconnection property. The defaultnevercreates no savepoints;alwayssets a savepoint before each query and rolls back to it on failure;conservativesets the savepoint but rolls back and retries only for cases such as "cached statement cannot change return type" (pgJDBC connection properties). The relatedcleanupSavepointsproperty (defaultfalse) releases the savepoint before the next statement. - psycopg 3 implements a nested
conn.transaction()block as a savepoint, so an inner block can fail without killing the outer transaction. - PL/pgSQL
BEGIN ... EXCEPTION ... ENDblocks roll back the block's database changes when an error is caught; the documentation warns that such blocks are significantly more expensive to enter and exit, so do not use them without need (PL/pgSQL error trapping).
Do not turn on savepoint-per-statement globally to make the error go away. If your code does not expect statements to fail, hiding the failure means the transaction commits without the change that failed. Use savepoints for steps that are allowed to fail, and roll back the whole transaction for everything else.
Scripts and migrations
By default psql keeps executing after an error. Inside a transaction block that produces a wall of 25P02 errors after the first real one; outside a transaction it produces a half-applied migration. For scripts, use:
-- ~/.psqlrc: keep typos from killing a manual transaction,
-- but only at the interactive prompt, never in scripts
\set ON_ERROR_ROLLBACK interactive
-- scripts: stop at the first error instead of ploughing on
psql -v ON_ERROR_STOP=1 --single-transaction -f migration.sql
With ON_ERROR_STOP set, psql stops at the first error and exits with code 3; with --single-transaction and ON_ERROR_STOP, a failure sends ROLLBACK instead of COMMIT (psql). Your deploy tool then sees a non-zero exit code and the first error is the last thing in the output.
Find sessions stuck in an aborted transaction
When code catches an error and then simply forgets the connection, the session stays open in an aborted transaction. pg_stat_activity reports it with the state idle in transaction (aborted) (pg_stat_activity):
SELECT pid, usename, application_name, client_addr,
now() - state_change AS stuck_for,
left(query, 80) AS last_query
FROM pg_stat_activity
WHERE state = 'idle in transaction (aborted)'
ORDER BY state_change;
Such a session holds whatever locks it took before the failure and, like any open transaction, can hold back vacuum. The broader problem and how to clean it up are covered in PostgreSQL idle in transaction. As a safety net, set timeouts:
-- per role, so batch jobs can keep their own setting
ALTER ROLE app_user SET idle_in_transaction_session_timeout = '60s';
-- PostgreSQL 17+: hard cap on the whole transaction
ALTER ROLE app_user SET transaction_timeout = '10min';
idle_in_transaction_session_timeout terminates a session that waits for the client inside an open transaction longer than the limit; transaction_timeout, added in PostgreSQL 17, terminates sessions whose transaction lasts too long overall. Both default to 0, meaning disabled, and the documentation advises against setting transaction_timeout in postgresql.conf because it would affect all sessions (client connection defaults).
Connection pools
A pooled connection returned to the pool in the middle of an aborted transaction poisons the next request that borrows it: that request fails with 25P02 although it did nothing wrong. Application pools normally roll back on return, but in our experience custom wrappers and "borrowed outside the framework" connections are where this bug lives. Behind PgBouncer in transaction mode, a server connection is assigned to a client until its transaction ends, so a client that leaves an aborted transaction open also keeps a server connection away from everyone else. Pool modes and sizing are covered in PgBouncer for PostgreSQL connection pooling.
What changes on big, busy databases
On a test database with ten rows and one user, savepoints look free and an aborted transaction looks harmless. In production:
- Subtransaction overhead. Every savepoint is a subtransaction. The documentation says up to 64 open subtransaction IDs are cached in shared memory per backend; beyond that, storage I/O overhead increases significantly because of extra lookups in
pg_subtrans(subtransactions). Only subtransactions that write get an ID, but a long write transaction withautosave=alwaysand withoutcleanupSavepoints, or a PL/pgSQL loop that enters anEXCEPTIONblock per row, can cross that line. In our experience the symptom shows up under concurrency, not in a single-user test. - Large batches. One bad row in a ten-million-row load aborts the whole transaction, and everything written so far is rolled back after it has already been written to WAL. Load in chunks of a size you can afford to redo, or load into a staging table first and validate there. Since PostgreSQL 17,
COPY FROMwithON_ERROR ignoreskips rows whose values cannot be converted to the column type; it applies only to text and CSV formats and only to conversion errors, not to constraint violations (COPY). - Locks held by the dead transaction. A row lock or a migration's
ACCESS EXCLUSIVElock taken before the failure stays held until the transaction ends. On a busy table, a session left in the aborted state can queue up every other writer behind it. The timeouts above are cheap insurance. - Retries. Deadlocks and serialization failures are meant to be retried, but the retry must start a new transaction after
ROLLBACK. Retrying the failed statement on the same aborted transaction only produces 25P02.
Key takeaways
- The 25P02 error is a consequence; find the first error on the same connection in the server or application log.
- Close an aborted transaction with
ROLLBACK; aCOMMITsilently acts asROLLBACK. - Use savepoints only for steps that are allowed to fail, and prefer
ON CONFLICTfor duplicates. - Run scripts with
ON_ERROR_STOP=1; keepON_ERROR_ROLLBACKfor interactive sessions. - Watch for
idle in transaction (aborted)and set idle and transaction timeouts per role. - On busy systems, keep savepoints per transaction low and batch sizes small enough to redo.