I have a table in my SQL Server database which contains some data about books like the given screenshot below:
+----+-------+-------+--------+
| Id | Title | Price | Status |
+----+-------+-------+--------+
| 1 | C#6 | 40.00 | 0 |
+----+-------+-------+--------+
The Status
column indicates to the availability of the book for borrowing (0 = Available, 1 = Borrowed).
Let's assume that 2 or more users saw the book in my web application and those users are trying to borrow the book at the same moment, without managing the concurrency we will get an exception for the other users except the user #1.
I know that we can use SQL transactions and also isolation level like Serializable
to make sure of no more users are using the same piece of data at the same time, but here, I have couple of questions:
- Is this the best practice of such situation? If not, kindly share your recommendation.
- If so, what about the other users and what should they get after user #1 got the book for borrowing? And also, is it good to handle the concurrency at the final level after the final confirmation or before?
The best practice in this case would be optimistic concurrency. Add a rowversion column to the table and check to see if the value has changed from the original value when updating: