I’m using Postgres 9.1. I’m wondering if using multiple SELECT FOR UPDATES in the same transaction could potentially cause a race condition.
2 concurrent transactions:
transaction 1: select for update on table 1 — successfully acquires lock
transaction 2: select for update on table 2 — successfully acquires lock
transaction 2: select for update on table 1 — waiting for lock release from transaction 1
transaction 1: select for update on table 2 — waiting for lock release from transaction 2
What happens in this situation? Does one of the waiting transactions eventually time out? If so, is there a way to configure the timeout duration?
edit: is deadlock_timeout the configuration I am looking for?
Yes, you should look for the
deadlock_timeoutin the docs.But your scenario doesn’t means that there will be a deadlock, ‘cos PostgreSQL is using row-level locks and it is not clear whether your transactions are concurring for the same rows.
Another option is to use serialization level higher then default
READ COMMITTED. But in this case your application should be ready to receive exceptions withSQLCODE=40001:This is expected, you should just re-try transaction as is.
A very good overview of Serializable isolation level you can find on the wiki.