Difficulty: Intermediate
Estimated Time: 20 minutes

In this learning unit, you will:

  • Understand how lightweight transactions enforce linearizable consistency
  • Use CQL statements INSERT, UPDATE and DELETE with IF clauses
  • Explore several examples of using lightweight transactions
  • Learn when to use lightweight transactions in production

In this scenario, you learned about:

  • Lightweight transactions and linearizable consistency
  • CQL statements INSERT, UPDATE and DELETE with IF clauses
  • Several examples of using lightweight transactions
  • When to use lightweight transactions in production

Linearizable Consistency and Lightweight Transactions

Step 1 of 10

Linearizable consistency

While eventual consistency is completely adequate for most real-life use cases and tunable consistency helps to customize consistency guarantees for specific application needs, there are situations when this is still not enough. Even strong consistency, which guarantees that all acknowledged writes are visible to subsequent reads, does not help with race conditions when there are multiple transactions trying to read and write the same piece of data concurrently. Examples of race conditions include two users trying to register new accounts using the same username, or multiple auction participants placing bids on the same item and potentially overwriting each other's bids. The latter scenario is demonstrated in the following illustration:

User 1: read(10)   10<20   write(20)
--------------------------------------------> time
User 2:         read(10)   10<15   write(15)

Both users run their transactions concurrently. Both read the current highest bid of 10 and both check that their new desired bids of 20 and 15 are higher than 10. While the first user writes her bid of 20, the unsuspecting second user writes her bid of 15. The resulting highest bid value is 15 instead of 20, which is incorrect.

The solution to this and other problems that involve race conditions is linearizable consistency, which ensures that concurrent transactions produce the same result as if they execute in a sequence, one after another. For the previous example, linearizable consistency would result in the correct highest bid of 20, as shown in these two possible execution sequences:

read(10) 10<20 write(20)
--------------------------------------------> time
                    read(20) 20>15
                    read(15) 15<20 write(20)
--------------------------------------------> time
read(10) 10<15 write(15)