Suppose you are doing lots of transactions, like the following:
BEGIN; SELECT * FROM accounts WHERE holder_name ='BOB' FOR UPDATE; <do some calculations here> UPDATE accounts SET balance = 42.00 WHERE holder_name ='BOB'; COMMIT;
Then, you may gain some performance by moving from explicit locking (SELECT … FOR UPDATE
) to optimistic locking.
Optimistic locking assumes that others don't update the same record, and checks this at update time instead of locking the record for the time it takes to process the information on the client side.
Rewrite your application so that the preceding transaction is transformed into something like the following (pay attention to the placeholders):
BEGIN; SELECT A.*, (A.*::text) AS old_acc_info FROM accounts a WHERE holder_name ='BOB'; <do some calculations here> UPDATE accounts SET balance = 42.00 WHERE holder_name ='BOB' AND (A.*::text) = <old_acc_info from select above>; COMMIT;
Then, check whether...