Reputation: 6588
I've got a Rails web application that runs on Heroku in production on a multi-threaded unicorn server.
In my application is a method that can only be executed by max. one of these processes. If concurrent calls happen, they need to queue up.
What is the most secure way to do this?
What I already thought of was to use the environment:
def my_method
sleep .1 while ENV['method_locked'] == 'locked'
ENV['method_locked'] = 'locked'
# Do my stuff
ENV['method_locked'] = 'unlocked'
end
I've got two concerns about this:
The other solution I had in mind was to spawn a separate process to take care of this, either using a separate worker dyno or by somehow abusing another unicorn thread (although I don't know whether this is possible at all.)
My question is: is there an even nicer way to do this?
Upvotes: 2
Views: 161
Reputation: 230521
Mutating ENV
wouldn't work. You'd only change ENV for the current process, it will not affect other processes.
If I were you, I would probably use redis to handle my locks. Here's a gem that I would use: redis-lock.
If you don't know, redis is single-threaded and very fast. Ideal external memory for your case.
Upvotes: 2