I would like to know if there are any ways one can perform ‘locking’ on an asp.net web application which is deployed on multiple servers, using a distributed server like MySQL Cluster.
For example, take the classic example of updating an account balance. No two requests should update the same account balance at the same time. For example:
Member 1 account balance is 100.
- Request A accesses Server 1 to add 100 to the balance of member 1
- Request B accesses Server 2 to add 50 to the balance of member 1
Thus request A updates the balance from 100 to 200 and saves.
Request B updates the balance to 150, and saves.
These all happen exactly at the same time, thus losing the information as the end result should have been 250.
How can one lock such that Request B would have to wait until Request A finishes, until it retrieves the balance. If it was a single process, this could be implemented by an application-wide lock. However, since there are multiple independent processes, this wouldn’t work as for Server 1 it is not locked, and neither Server 2
Any ideas or best-practices how this can be done?
That’s what transactions are for.
Wrap the operations that need to be atomic in a
TransactionScopeto enrol them in an explicit transaction.This doesn’t completely resolve the issue of stale data, as once a transaction completes if the other concurrent user is using the old value to update, you still have a problem.
The solution is to use a field on the table that changes whenever the row changes – in SQL Server 2008 this is the rowversion type.
You only update the row if the
rowversionhas not changed – if it has, you notify the user and bring back the current values without making an update.