The Ruby on Rails framework is powerful in many ways. One of its strong points is that Ruby on Rails is being shipped with ActiveRecord - an Object Relational Mapping system. ActiveRecord comes up with its own DSL, which lets you write Ruby code, which in turn is translated to SQL, allowing you to use database native features, including “locking”.
Before we start discussing pessimistic locking in Rails, we have to understand the mechanism of database locking itself. To cut the long story short, locking can be explained as a feature that allows two people to update, change or modify an object at the same time, in an unconflicted way.
Let me write some code illustrating the point. The first presented iteration will be implemented without setting any locks on the database:
As you can see, those are two methods in two consoles. One of them has
sleep, which can represent some kind of timeouts or errors in the system and this is how we usually do it when updating a user.
I run it in the consoles.
But as a final result, I got Joe Doe, instead of Anna Doe.
So the question is, what happened? Well, the first transaction did not finish and in the meantime, someone else wanted to change the user name, because of that we got the wrong result. In such a situation we can make use of pessimistic locking. In Rails, the lock method allows us to block the object and in this case, stop it from updating.
This is how it looks like with the pessimistic locking
Again, I have two similar methods, but now the second one is run right after the first one and this time, our result is
In Rails applications, the default behaviour of the lock method is ‘For Update’, but also other strategies exist. You can check the documentation for PostgreSQL to find different locking mechanism strategies, not only for an update.
What are the real world examples of using database locking technique in Ruby on Rails applications? Well, I can think of a few examples: we can use it in banking when performing money transfers. From my personal experience, I found it most useful when we wanted to withdraw money from an account, which more people have access to. So by mistake, we could give permission to withdraw money from an empty account. Also, database locking could be a good choice to manage bookings of rooms in hotels. This would allow two people to have access to the same object at the same time.
With pessimistic locking, there also comes optimistic locking, but this is a topic for a separate article, which may be featured on our blog in the nearest future. As for now, this is all. Happy locking!
Don't forget to check out our expert Ruby on Rails developers!