Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Locking entities to perform get-update-set operations in Google Cloud datastore

What is the recommeneded way to lock an entity (e.g. User(amount_earned)) to perform consistent read --> update --> set operations on Google Cloud Datastore.

Using memcache, we usually do a memcache.add(lock_key), to make sure there is only process/thread modifying a object.

Since memcache's add is atomic and returns false, if key wasn't previously added, it is easy to simulate "locking" using memcache.

How can one simulate similar locking semantic on Google Cloud datastore.

Ideally

with gcp.lock(lock_key)as key:
   user.get(user_id) # read
   user.update(amount) # update
   user.set() # save

# Release the lock, so that other processes can now updated user (identified by user_id) object
like image 723
user462455 Avatar asked Oct 22 '16 21:10

user462455


1 Answers

You could perhaps use Transactions and Optimistic Locking strategy.

Let's take the example of updating User entity. In order to use optimistic locking, you would have to use a special property (e.g. entity version). The version field will be incremented by one for each update. Steps to update an entity:

  1. Load the entity
  2. Assume you have a UI that allows updating of User entity. Display the entity on the screen in Edit mode.
  3. End user reviews/makes changes to the entity
  4. End user clicks Save
  5. Now start a transaction
  6. Load the User entity using the entity's Key
  7. Compare the version of newly loaded entity and the entity previously loaded to the UI
  8. If the versions match, no one else updated the entity, so go ahead and update the entity and commit the transaction. Make sure to increment the version number while updating/committing. If the versions do not match, someone else changed the entity. Do not update the entity, rollback the transaction. Take appropriate action. For example, you can display a message to the user and have him review the latest entity and make any further changes.
like image 174
Sai Pullabhotla Avatar answered Oct 28 '22 15:10

Sai Pullabhotla