InFailedSqlTransaction: commands ignored until end of transaction block
psycopg2.errors.InFailedSqlTransaction: current transaction is aborted, commands ignored until end of transaction blockShort answer
Some earlier statement in the same transaction failed, and PostgreSQL ignores everything after it until you roll back. The error you see is only the second one. Find the first failure, roll back after it, and use a savepoint when you expect a statement to fail.
Fix it fast
1Find out which cause you have
Look above this error in the log for the first exception. That statement is the real bug, and everything after it is a symptom.
python app.py 2>&1 | grep -n -B2 -A8 "Error"2Match what you see, then jump to its fix
- 1
A try/except around a query logs the first error and carries on, then the next query fails with InFailedSqlTransactionAn error was caught but the transaction was never rolled backFix - 2
Every later request on the same connection fails until the process restartsA long-lived connection is reused after a failure without ending the transactionFix - 3
Code inserts rows and relies on a unique-violation or similar error to skip duplicatesYou expect a statement to fail and want the transaction to survive itFix
- 1
What does the error look like?
psycopg2.errors.InFailedSqlTransaction: current transaction is aborted, commands ignored until end of transaction blockSQLSTATE 25P02 (in_failed_sql_transaction)
Cause 1 of 3
An error was caught but the transaction was never rolled back
1Check
psycopg2 starts a transaction at the first command. After a failed command the transaction is aborted and no further command runs until rollback() is called.
grep -n -A4 "except" app.py2Fix
Call rollback() in the except block, then continue or re-raise.
try:
cur.execute("INSERT INTO users (email) VALUES (%s)", (email,))
conn.commit()
except psycopg2.Error:
conn.rollback()
raise3Verify
Trigger the failing insert twice in a row; the second attempt reports the real error again, not InFailedSqlTransaction.
python app.pyConfirmed by psycopg.org
Cause 2 of 3
A long-lived connection is reused after a failure without ending the transaction
1Check
A connection used as a context manager commits on a clean exit and rolls back on an exception. Code that holds one global connection and never uses a with block never gets that cleanup.
grep -n "psycopg2.connect" -r .2Fix
Wrap each unit of work in a with block on the connection. It ends the transaction either way, but it does not close the connection, so close it separately.
with conn:
with conn.cursor() as cur:
cur.execute("UPDATE accounts SET balance = balance - %s WHERE id = %s", (50, 1))3Verify
After a deliberate failure inside the block, the next block on the same connection works.
python app.pyConfirmed by psycopg.org
Cause 3 of 3
You expect a statement to fail and want the transaction to survive it
1Check
Rolling back throws away all earlier work in the transaction. A savepoint marks a point you can return to without losing that work.
grep -n "IntegrityError" -r .2Fix
Set a savepoint before the risky statement and roll back to it on failure.
cur.execute("SAVEPOINT before_insert")
try:
cur.execute("INSERT INTO tags (name) VALUES (%s)", (name,))
cur.execute("RELEASE SAVEPOINT before_insert")
except psycopg2.errors.UniqueViolation:
cur.execute("ROLLBACK TO SAVEPOINT before_insert")3Verify
A duplicate row is skipped and the surrounding transaction still commits.
python app.pyConfirmed by postgresql.org
How do I stop it coming back?
- Never swallow a psycopg2 exception without rolling back or re-raising.
- Keep transactions short and use a with block per unit of work.
- Turn on autocommit only for statements that need it, such as CREATE DATABASE or VACUUM, since autocommitted commands cannot be rolled back.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
- stegnor.comMy company site: 804 pages from a Python and Jinja generator, with 15 free browser tools.
- MenuloA restaurant discovery platform in Germany, kept current by a Python ingestion pipeline.
- ShopGoAn e-commerce aggregator with a Python scraping engine behind its catalog, past 10K Google Play downloads.
Related fixes
Databases
python manage.py migrate finishes but the tables for my app are missing
relation "myapp_book" does not exist
migrate only applies migration files that exist.
3 causes, each with a fixDatabases
Django save fails on PostgreSQL: null value in a column violates a not-null constraint
django.db.utils.IntegrityError: null value in column "price" of relation "shop_product" violates not-null constraint
A model field is NOT NULL in the database unless it has null=True.
3 causes, each with a fixDatabases
Django migration on PostgreSQL stops with 'pending trigger events'
django.db.utils.OperationalError: cannot ALTER TABLE "mytable" because it has pending trigger events
PostgreSQL runs a Django migration in one transaction.
2 causes, each with a fixDatabases
psycopg2 cannot connect: connection refused on port 5432
Is the server running on that host and accepting TCP/IP connections?
Connection refused means nothing accepted the connection at the address psycopg2 tried.
3 causes, each with a fixDatabases
psycopg2 cannot resolve the host name db in Docker Compose
could not translate host name "db" to address
Compose registers each service in its own DNS under the service name, but only containers on the same Compose network can look it up.
4 causes, each with a fixDatabases
psycopg2 hangs with no timeout: connect, query and dead connections
psycopg2.errors.QueryCanceled (SQLSTATE 57014) after you set a statement timeout
Neither psycopg2 nor PostgreSQL sets a time limit by default, so a stuck connect, a slow query, a lock wait or a silently dead network link can wait forever.
4 causes, each with a fix