Our application needs to lock a record to avoid simultaneous access to the same record from two different servers. How that can be done with Aerospike ?
You use the record’s generation, and a CAS (check-and-set) pattern to invalidate the write if another updated happened between when you read, and this write operation. Here’s an example of how the Java client does it.
And no, you don’t need a lock
Let me add a little more color.
Between “CAS”, and atomic increment, and the create-if-doesn’t-exist feature, Aerospike has the semantics you need. If you need to prevent reads from another server, for example ( preventing access from two different servers ) it’s pretty easy to see how to code that.
However, a staggering useful in databases is called an “optimistic lock”. This is the CAS pattern rbotzer mentions. When you read the object, you also get a “token” ( generation ). When you want to update the record, you can make sure you are updating the record that you read by re-presenting the token. If another write has occurred, your write will fail and you’ll have to retry. This allows an ORM-like complex update pattern that’s pretty swank.
The benefit of the optimistic lock pattern is that there are no “hung locks” in the system — cases where a client takes a lock but forgets to release it, which is eventually resolved by a timeout, but only after blocking many applications’ access.
Let us know if these patterns don’t suit your application.
Thanks a lot for your replies !! We want to block the read in case data is already locked and do not want simultaneous processing by two process at the same time. So, “optimistic lock” and CASare not suitable for us. So, it seems: Only write if the record does not already exist: Change the WritePolicy to CREATE_ONLY, will work for us.
- In case record exists and if we want to create it again, what error code i will get ?
- Do you have any sample code written in C ?
- Is Write Policy can be applied to a single set and not on the complete Database (or on all Sets) ?
I got the answers for the following:
- In case record exists and if we want to create it again, what error code i will get ? Error returned is “5 - AEROSPIKE_ERR_RECORD_EXISTS”
- Do you have any sample code written in C ? With the examples, i created my own.
- Is Write Policy can be applied to a single set and not on the complete Database (or on all Sets) ? Policies can be applied when a query is fired and on a single set.
Thanks for chiming in with the answers. CREATE_ONLY does seem to be the policy that supports your use. We usually find that one of our policies is right for just about any use.