could not serialize access due to concurrent update
SQLSTATE 40001 is serialization_failure. PostgreSQL rejected a transaction to preserve the guarantees of Repeatable Read or Serializable isolation. Message wording can also mention read/write dependencies among transactions. A transient conflict is expected under concurrency, but the application must restart the complete transaction rather than continue with its old snapshot.
could not serialize access due to concurrent update
Why it happens
A Repeatable Read transaction attempts to modify a row changed by another transaction after its snapshot was established.
Serializable transactions create conflicting read/write dependencies that cannot all produce a valid serial execution.
Long transactions, hot records, or synchronized workers increase contention, while an incomplete retry loop reuses decisions made from an obsolete snapshot.
How to fix it
Capture SQLSTATE and the full message, including whether failure occurred during a statement or COMMIT. Before reproducing it, inspect SHOW transaction_isolation; inside the transaction and check ORM settings. Roll back a failed transaction before issuing diagnostic queries.
On 40001, roll back the failed transaction and start a new one. Re-run its reads, application decisions, calculations, and writes using fresh data. Retrying only COMMIT or the final UPDATE does not recreate the transaction correctly.
Wrap the complete unit of work in a bounded retry policy with backoff and jitter. Handle errors from both statements and commit, record attempts, and return a clear failure when the retry budget or request deadline expires.
Prevent duplicate external effects during retries. Do not send emails, charge a payment, or publish an irreversible event on every attempt; use an appropriate idempotency or post-commit delivery design. A database rollback cannot undo those external actions.
If failures are frequent, shorten the transaction, reduce avoidable contention, and examine access patterns and indexes. Test with concurrent clients and verify final business invariants. Do not lower isolation merely to hide the error without reviewing correctness, and do not classify every constraint violation as a retryable serialization failure.