How can I do an atomic update from etcd

I am trying to understand what is "atomic" update in terms of etcd.

When I think "atomic", I think there are "before" and "after" (during not, and if the update is not done, it is still "before").

Here's an example:

curl -s -XPUT http://localhost:2379/v2/keys/message -d value='Hidee Ho'

      

So, at the moment, anyone can access this message and get the current value:

curl -s http://localhost:2379/v2/keys/message
{"action":"get","node":{"key":"/message","value":"Hidee Ho","modifiedIndex":4748,"createdIndex":4748}}

      

I can change this value afterwards, for example:

curl -s -XPUT http://localhost:2379/v2/keys/message -d value='Mr Hanky'

      

And the result can be obtained as before. Before my change it returns "Hidee Ho", after change, "Mr Hanky" returns. So my question is: do I guarantee this or that result? That is, I want to confirm that one or the other will be returned (and not a nil value between the result).

I don't really care about timing. If I do Mr. Hankey's update and subsequent value collectors to get Hidee Ho in a (short) period of time, that's OK.

I am confused because there is an Atomic CompareAndSwap function in the protocol. As far as I can tell, this isn't as much Atomic as "only update if value is what I say". In my case, I don't care what the value was. I just want to know that it has changed and that no reader will see anything other than the "before" or "after" values.

+3


source to share


1 answer


You are correct that a simple PUT is atomic since the client will only see the previous value or the new value.



The CompareAndSwap function allows you to do optimistic locking so that you can write new values ​​that depend on the previous value, for example. counter. If you were to use a counter without using CompareAndSwap you would have something like write("count", 1 + read("count"))

, in which case read and write would be separate, if both callers did it at the same time, then perhaps they would both see the same initial value. and you will lose one of the increments. using CAS, the caller can say to set it to 12 only if the previous value is 11, now if this happens at the same time, one of the entries will fail and then she can re-read and reapply its delta so you don't lose any increments ...

+3


source







All Articles