Tuesday 23 August 2016

Memcached: CAS: Check and Set

CAS command is very useful in concurrent applications. For example, you want to deduct some amount from customer account on every transaction.

Thread 1 reads cust1 account balance as 1500
Thread 2 also reads the cust1 account balance as 1500
Thread 2 deduct 300 from cust1 account = 1500-300 = 1200
Thread 1 deduct 100 from cust1 account = 1500-100 = 1400.

As you see above flow, Actual balance to be deducted from cust1 account is 400, but final amount is 1400. To handle these kind of scenarios, we should use CAS command.

Syntax
cas key flags exptime bytes unique_cas_token [noreply]
value


Option
Description
key
Name of the key.
flags
It is 32-bit unsigned integer, stored along with the data in the server and retrieved when you get the <key value> pair.
exptime
Expiry time of the data stored in cache. It is represented in seconds.
bytes
length of the data in bytes that needs to be stored in Memcached.
unique_cas_token
It is a unique token number obtained from gets comamand.
noreply
It is optional, when you pass this parameter, server don’t send any reply back to you.
value
Value to be saved to memcached

$ telnet 127.0.0.1 11211
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
set balance 0 900 4
1500
STORED
gets balance
VALUE balance 0 4 36
1500
END


From the above output, you can see the key ‘balance’ jas cas version 36.
set balance 0 900 4
1200
STORED
gets balance
VALUE balance 0 4 37
1200
END


As you see, after the updation of balance, cas number is incremented to 37. Now let me try to update the balance amount, by specifying the cas version 36.
cas balance 0 900 4 36
1400
EXISTS
gets balance
VALUE balance 0 4 37
1200
END

As you see, balance is not reflected when I tried to update the data with lower cas version. Let me try to update data with current version.

cas balance 0 900 4 37
1400
STORED
gets balance
VALUE balance 0 4 38
1400
END









Previous                                                 Next                                                 Home

No comments:

Post a Comment