I have a PHP/jQuery/AJAX/MySQL app built for managing databases. I want to implement the ability to prevent multiple users from editing the same database row at the same time.
- What is this called?
- Do I use a token system and who ever has the token can edit it until they release the token?
- Do I use a “last edit date/time” to compare you loading the HTML form with the time in the database and if the database is the most resent edit then it warns you?
- Do I lock the row using database functions?
I’m just not sure which is the best. Assuming between 10 – 15 concurrent users
There are two general approaches– optimistic and pessimistic locking.
Optimistic locking is generally much easier to implement in a web-based environment because it is fundamentally stateless. It scales much better as well. The downside is that it assumes that your users generally won’t be trying to edit the same set of rows at the same time. For most applications, that’s a very reasonable assumption but you’d have to verify that your application isn’t one of the outliers where users would regularly be stepping on each other’s toes. In optimistic locking, you would have some sort of
last_modified_timestampcolumn that you wouldSELECTwhen a user fetched the data and then use in theWHEREclause when you go to update the date, i.e.If that updates 1 row, you know you were successful. Otherwise, if it updates 0 rows, you know that someone else has modified the data in the interim and you can take some action (generally showing the user the new data and asking them if they want to overwrite but you can adopt other conflict resolution approaches).
Pessimistic locking is more challenging to implement particularly in a web-based application particularly when users can close their browser without logging out or where users may start editing some data and go to lunch before hitting
Submit. It makes it harder to scale and generally makes the application more difficult to administer. It’s really only worth considering if users will regularly try to update the same rows or if updating a row takes a large amount of time for a user so it’s worth letting them know up front that someone else has locked the row.