Reputation: 23268
Redis has SETNX command.
I read the documentation. However, it doesn't explicitly says whether it's atomic or not.
I read that it's not recommended to be used for distributed locks. However, my case is a little bit simpler. All I need to make sure that whomever comes first (first caller) set the value and second caller receives an error (SETNX will return 0).
So, the question is, is it truly atomic?
Upvotes: 5
Views: 3225
Reputation: 48952
Yes, SETNX
is atomic and will do what you ask regardless of how many callers there are.
Individual Redis commands are essentially always atomic, since Redis is single-threaded. So the documentation doesn't bother to specify that for every single command. (Perhaps the most direct reference comes from the first line of the FAQ: "Redis is a different evolution path in the key-value DBs where values can contain more complex data types, with atomic operations defined on those data types.")
When it comes to setting and releasing locks you're no longer dealing with a single command, so that's why there are other considerations. But the SETNX
command itself is atomic.
Upvotes: 8
Reputation: 5265
If you need to perform atomic operations you can use MULTI
and EXEC
to group commands into a transaction, at which point all commands will be atomic.
You can read more on their website: https://redis.io/topics/transactions
Make sure you read the whole document because there are some important notes about failures.
It's important to note that even when a command fails, all the other commands in the queue are processed – Redis will not stop the processing of commands.
Upvotes: 0