How to handle concurrent increments for the same key?

Hi,

I would like to use add-operation in my application, so that concurrent increments for the same key are possible (my application runs on several servers). I already read about the generation-property of WritePolicy, but cannot figure out how to use it in the context of this operation. How do I have to implement this?

Cheers,

Assen

One should avoid using something like incremented id’s, if possible. Can’t you use something like an user’s email as an unique part of your primary key? That’s how it’s typically solved. Synchronization of counters across multiple machine’s is a complex and not really ‘real time’ thing.

Cheers, Manuel

Hi Assen,

Every key-value operation is atomic. The record, relating to the key, is locked at the start of the operation and unlocked at the end of the operation. This means that the add() operation is atomic.

I suspect that you want to increment the counter and get the new value. If so, this can be done in a single operation atomically by using operate(). Here is an example that increments a counter and gets the new value, similar to INCR in Redis:

String binName = "my_counter";
Key key = new Key("test", "demo", "my-record-that-has-a-counter");
Record record = aerospikeClient.operate(null, key, Operation.add(new Bin(binName, 1)), Operation.get(binName));
long counterValue =  record.getLong(binName);

I hope this helps

Peter

Hi Peter,

Thanks for your explanation and the example. That was, what I was looking for.

Cheers,

Assen

1 Like

One Question though, What if the key is not present, and I call Operation.add(),

Currently it is just adding a new bin with no key.

Is there a way possible that it creates the Key which is sent if not found??