Bitpath

Boss lesson · Unit 03

The lost update

Two buyers, one ticket, three ways to get it right

13 exercisesabout 3 min

What you practise

  • Two transactions read-modify-write the same row
  • Fixes: atomic UPDATE ... SET n = n - 1, SELECT ... FOR UPDATE, optimistic version columns
  • How deadlocks form and how the database breaks them

Try a question from this lesson

Pick one

Two people like a post at the same moment. Each request reads the count, adds one, and writes it back. What is the count afterwards?

likes = 10
A: read likes        -> 10
B: read likes        -> 10
A: write likes = 11
B: write likes = 11

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

Read, modify, write

The pattern behind the bug: read a value, compute a new one in your code, write it back. Between your read and your write, someone else can do the same.

Three fixes follow. Let the database do the arithmetic in one statement. Lock the row before you read it. Or skip the lock, detect the clash, and retry.

Concept

Optimistic locking

Fix three: do not lock. Check.

Give the row a version number and read it along with the data. Write back only if the version is still the one you read, and bump it as you write.

If zero rows were updated, someone got there first: read again and retry.

SQL
UPDATE tickets
SET stock = 4, version = 2
WHERE id = 1 AND version = 1;

10 more exercises in the app

  • 3× type the answer
  • 1× fill the blanks
  • 4× multiple choice
  • 1× true or false
  • 1× order the lines

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy