Lightweight transactions

A description about lightweight transactions and when to use them.

Lightweight transactions with linearizable consistency ensure transaction isolation level similar to the serializable level offered by RDBMS’s. They are also known as compare and set transactions. You use lightweight transactions instead of durable transactions with eventual/tunable consistency for situations the require nodes in the distributed system to agree on changes to data. For example, two users attempting to create a unique user account in the same cluster could overwrite each other’s work. Using a lightweight transaction, the nodes can agree to create only one account.

Cassandra implements lightweight transactions by extending the Paxos consensus protocol, which is based on a quorum-based algorithm. Using this protocol, a distributed system can agree on proposed data additions/modifications without the need for a master database or two-phase commit.

You use extensions in CQL for lightweight transactions.

You can use an IF clause in a number of CQL statements, such as INSERT, for lightweight transactions. For example, to ensure that an insert into a new accounts table is unique for a new customer, use the IF NOT EXISTS clause:

INSERT INTO customer_account (customerID, customer_email) 
VALUES (‘LauraS’, ‘lauras@gmail.com’)
IF NOT EXISTS;

DML modifications you make using UPDATE can also make use of the IF clause by comparing one or more columns to various values:

UPDATE customer_account
SET    customer_email=’laurass@gmail.com’
IF     customerID=’LauraS’; 

Cassandra 2.1.1 and later support non-equal conditions for lightweight transactions. You can use <, <=, >, >=, != and IN operators in WHERE clauses to query lightweight tables. Behind the scenes, Cassandra is making four round trips between a node proposing a lightweight transaction and any needed replicas in the cluster to ensure proper execution so performance is affected. Consequently, reserve lightweight transactions for those situations where they are absolutely necessary; Cassandra’s normal eventual consistency can be used for everything else.

A SERIAL consistency level allows reading the current (and possibly uncommitted) state of data without proposing a new addition or update. If a SERIAL read finds an uncommitted transaction in progress, Cassandra performs a read repair as part of the commit.