Mutex in rails API among several client request
-
14-07-2021 - |
Question
I face a problem with mutual exclusion in my rails API. I have some Event object in my database which contain the number of person who will attend the event.
Consider my Event method which add a person to the event :
class Event
def add_person
nb = self.number_of_person + 1
# Some stuff
self.number_of_person = nb
self.save
end
end
Now, imagine that client A and B want to participate in the event E. Rails is gonna receive 2 request and will call the add_person method in parallel. At the end, it is possible that the number of person in the Event E be not incremented by 2 but by 1.
This is what I want to be able to do :
Client A | Client B | Possible in parallel
--------------------------------------------------------------------------
Event.find(1).show | Event.find(1).show | yes
Event.find(1).add_person | Event.find(1).add_person | no
Event.find(1).add_person | Event.find(2).add_person | yes
I only want to queue the add_person
method on the same object.
Is there a way to do this ?
Solution
A standard ActiveRecord transaction will prevent deadlock, or other contention. You might have to use a pessimistic locking strategy. Databases are designed to prevent exactly this kind of thing.