
Introduction
Last month I shared a simple but effective strategy of how to create a Redis Mutex in your Ruby applications to handle cross-process/cross server synchronisation. As a quick recap, the problem this is solving is if you need to use locking synchronisation to control access across multiple systems to a resource. In this case a standard Ruby Mutex won't help you as you are bound within the constraints of a single process. And a file mutex (for example) won't help you because you're bound within the constraints of a single server (NAS implementations aside :)
Now, looking at the RedisMutex implementation we shared last week, there is an obvious but slightly tricky in-efficiency with it. To illustrate this let me refresh your memory by outlining the essential workflow below:
So what you see is that we have a recheck frequency seconds during which time we are waiting (for simplicity lets call this recheck_wait from here on). If we make recheck_wait very small then we are going to end up hitting our Redis server a lot (causing unnecessary load there) and if we make recheck_wait too big then we end up with periods of time where the lock is released, but we are still waiting! To get around this we can extend our RedisMutex class to make use of Redis Key Event Notifications!
As with the last post, I'll talk through the way that we implemented the code below. Please feel free to use it or reach out if you have any feedback or comments. Remember to always understand the code you're running and using it is at your own risk; Cloud 66 can not be held liable.
This time you'll need a Redis Server running at least version 2.8 to use this Mutex.
Implementation
1. Redis Initializer
- Once a redis connection is in a subscription mode, it can only perform subscription related actions - so we need a pool of redis connections to use exclusively for our subscription events. To manage this pool we use Mike Perham's excellent connection_pool gem. (Unrelated: we're huge fans of Mike's sidekiq gem too)
- Redis needs to be told that it should raise key events for us. This should be done when your application starts up. You can choose which events to receive notifications on - we need the following ones:
- K: Keyspace events published with __keyspace@DB
- g: Generic commands like DEL, EXPIRE, RENAME, ...
- x: Expired events (events generated every time a key expires)
2. Mutex Implementation
- Instead of waiting a set time for keys to expire we can now simply subscribe to specific Redis
delorexpiredevents that are raised for our key; and move on in that case.
How to use it
Now, see the simple usage sample below (exactly the same as we did it before)
Conclusion
In this blog post, we took our previous implementation of a multithreading/cross process or server synchronization solution, and enhanced it for better throughput performance.
Happy coding!
- Check out part I - 'Ruby Mutex Mayhem'.
