Editorials

Stateless Apps and RowVersion

The value of the RowVersion data type continues to increase in stateless applications such as those found on tablets and web sites. RowVersion is maintained by the SQL Server engine. Each time a row is modified, the value of the RowVersion is modified.

If your application retrieves the RowVersion column, it can use the value for comparison, determining if the data against which the current value is stale, the source data having been modified by another user since you retrieved data from the database.

Let’s say you are using Entity Framework for your database access layer. You have a rest call to update a record in your database. The controller gets the latest object from your database. It updates the properties. It then chooses to save the results. When the save occurs, if no other user modified the data since you retrieved it from the database, all is well. If someone else saved before you, your save will fail.

Extending the scenario further, if you maintain the RowVersion value in your rest objects, you can do a validation yourself. The controller for your rest call first retrieves the current value from the database. You can confirm that the RowVersion property matches immediately, without any further calls to SQL Server, because someone else has modified the data you wish to write, simply by comparing the RowVersion value. So, you can use the RowVersion property in a row twice. The first time you compare it yourself in the Repository code. The second time, it is compared by SQL Server itself.

That’s a lot of bang for the buck. It provides a lot of value in a optimistic locking (or non-locking) implementation of a stateless system. The worst case I have seen is in products such as On-Time that attempted to implement pessimistic locking in a stateless implementation. Their locking scheme resulted in records being locked for long periods, and sometimes requiring an administrator to go in an released locks.

Have you got your locking figured out for your stateless applications? Share your implementation in comments.

Cheers,

Ben