Using optimistic locking to avoid long lock waits
If you perform work in one long transaction, the database will lock rows for long periods of time. Long lock times often result in application performance issues because of long lock waits:
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;
If that is happening, then you may gain some performance benefits 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.
How to do it…
Rewrite your application so that the SQL is transformed into two separate transactions, with a double-check to ensure that the rows haven't changed (pay attention...