Cassandra - Distributed Row Locking for Select AND Update

Viewed 105

I have a micro-service which runs on multiple machines in two regions which connects to Cassandra DB. I have the following table structure.

CREATE TABLE gifts (
  gift_id text,
  user_id text
  PRIMARY KEY gift_id
);

The table contains a list of gift id.

During multiple concurrent request each user must be assigned a unique gift i.e select a random gift_id and update the user_id.

Will LWT be helpful to solve this problem?

Limitations:

  • Cannot use zookeeper for locking
  • Cannot use any relational database.
1 Answers

Note that LWT doesn't affect SELECTs. The usual last-writer-wins and tunable consistency semantics apply (though running a SELECT with consistency level ALL guarantees that you'll see the write from the latest INSERT/UPDATE (which in Cassandra should best be considered the same: INSERT has upsert semantics)).

You can use LWTs to ensure that no two users share a gift_id. Simply INSERT with IF NOT EXISTS if once a gift is associated with a user it can't be associated with any other user. Alternatively, you can do a SELECT user_id FROM gifts WHERE gift_id = ... and then INSERT with IF user_id = the_user_id_from_the_select.

Related