Search code examples
c#.netcouchbasecouchbase-view

Couchbase Get() followed by atomic Increment()


I have a program that does the following :

  1. Check if the key is present in couchbase using Get()

  2. If its present then don't do anything, return a false to the calling application.

  3. if the key is not present, then increment it with a value of 1.

So basically, the value of my key created with Increment will always be 1 and actually wont be incremented ( im using Increment just to create the key using atomicity ).

My question is what if the Get() operation is invoked from 3 requests at the exact same time.. ?

Will the first request be successful in incrementing the key and will point number 2 mentioned above be applicable for the remaining 2 requests.. ?

or

Will all 3 requests face point number 1 and then increment the key 3 times.. ?

Im using the .NET SDK for couchbase.


Solution

  • Just use insert instead of the sequence of operations you're currently using. Insert is atomic in regards to a single key, so only one session will succeed and all other concurrent/subsequent inserts will fail.

    var result = await bucket.InsertAsync("key", 1);
    

    If the operation succeeds, the item didn't exist before and was successfully created with the value 1. If it fails with the error code KEY_EXISTS, then the item was already present, presumably with value 1 if nothing else changed it.