Hello everyone. I have a case where I need to implement a lock to prevent race conditions when working with a record.
I was wondering whether the following would work for what I'm trying to accomplish.
I want to use SET <key === recordId> <value === 'locked'>[NX] [EX 20], which should create a lock record that expires after 20 seconds only if the record isn't already present.
Then on subsequent attempts to create the lock it won't be created due to NX and the response will say that the record already exists, which I'll use in my logic to fetch another record to prevent writing to this one before the lock expires.
Does this concept sound reasonable or am I confused on how I should be using SET NX to record lock.
Thank you! 💯
#Record locking with SET
7 messages · Page 1 of 1 (latest)
This will work. Are you planning to remove the lock manually after the process completes or are you just gonna let it expire?
Hello Guy. Thank you for the response!!! I'll just let it expire. The record should only be moved from one state to another once, so no need to keep it locked for anything past the initial automatic expiry
Also thank you for confirming. I am also using a single cluster with three nodes (multi A-Z enabled) deployed via AWS elasticache, so I'm using this basic setup instead of the more elaborate redlock libraries. Also the documentation doesn't say, but attempting the SET NX command to an already existing key should return a response signifying that the record already exists, correct? Or is the correct approach to fetch the value of the lock key with it being 'locked' by using GET?
I tested it before I responded. A successful write returns OK. A "failure" returns (nil).
Thank you so much for confirming. I need a better testing setup. The current redis instance in elasticache requires either lambda invocations or an EC2 running on the same VPC ( can't connect from local) and iterating during testing is a bit of a PITA.
Again, thanks for responding and confirming. I owe you a coffee