Lock it carefully!

Zain Butt
Sendoso Engineering
Nov 7, 2020


Photo by Michael Chacon on Unsplash

While implementing features of an app that is expected to be accessed by multiple users, we make sure to keep data consistent and not getting into a race condition, we use the locking technique.

There are two types of locking, optimistic and pessimistic locking. Here, we would be talking about pessimistic locking. To help us Rails provides us with a helpful locking module that provides support for row-level locking using SELECT … FOR UPDATE and other lock types.

So, to avoid getting into said issues above, we use locking all over our application where needed. But there was one place where locking produced an error while running specs that were caught by our CI tool although the specs were passing locally.

Turns out the locked object somehow became dirty (modified) and locking a dirty object raised an error.

Locking a record with unpersisted changes is not supported. Use `save` to persist the changes, or `reload` to discard them explicitly.

Make sure to reload or save any modified changes to your object before locking it.

user.reload.with_lock do
# ... your code here