I trying to implement the active record pattern using Java/JDBC and MySQL along with optimistic locking for concurrency handling.
Now, I have a ‘version_number’ field for all the records in a table which is incremented after every update.
There seem to be 2 strategies for implementing this:
- The application when it requests the data it also stores the corresponding version number of each of the objects (i.e. record). On updating, the version number is ‘sent down’ to the data layer which is used in the UPDATE…SET…WHERE query for optimistic locking
- The application DOES NOT store the version number, but only some parts of the object (as opposed to an entire row of data). For optimistic locking to succeed, the data layer (active record) would need to first fetch the ‘row’ from the DB, get version number and then fire the same UPDATE…SET…WHERE query for updating the record.
In the former there is the ‘first fetch’ and then an update. In the latter case you do have a ‘first fetch’ but also a fetch right before an update.
The question is this: by design, which is the better approach? Is it okay/safe/correct to have all the data, including the version number be stored in the web application’s front-end (Javascript/HTML)? Or is it better to take a performance hit of a read before update?
Is there a ‘right way’ to implement this design? I’m not sure how current implementations of active record handle this (Ruby, Play, ActiveJDBC etc.) If I’m to implement it ‘raw’ in JDBC what’s the right design decision in this case?
This is neither a matter of performance nor security, the two approaches are functionally different and achieve different goals.
With the first approach you are optimistically locking the row for the user’s entire “think time.” If User 1 loads the screen, then User 2 makes changes, User 1’s changes will fail and they will see an error that they were looking at out of date data.
With the second approach you are only protecting against interleaving writes between competing request threads. User 1 may load a page, then User 2 makes changes, then when User 1 hits submit, their changes will go through and blow out User 2’s changes. User 1 may have made a decision based on outdate information and never know.
It’s a matter of which behaviour is the one you want for your business rules, not one or the other being technically “correct.” they are both valid, they do different things.