Database Optimistic and Pessimistic Control
What you will learn
- The difference between pessimistic and optimistic concurrency control
- How a version column detects conflicts
- When to choose each
1. Two attitudes to conflict
Lesson 6.4 showed a lost update, and a single SET qty = qty - 3 statement avoids it. But sometimes a person reads a record, thinks for a while (say, edits a product in a form) and saves later. You cannot do that in one statement. Two designs handle it:
| Design | Idea | Cost |
|---|---|---|
| Pessimistic | "Conflicts are likely, so lock first." Take a lock when reading and hold it until the save. | others wait; long locks (lesson 6.6) |
| Optimistic | "Conflicts are rare, so don't lock." Work freely, and at save time check that nobody changed the row; if they did, refuse and retry. | some saves fail and must be redone |
2. Pessimistic: lock first
In many databases you read with a "lock for update" request such as SELECT ... FOR UPDATE. The PostgreSQL manual says it locks the selected rows so that other transactions cannot lock, change or delete them until the current transaction ends. SQLite does not have this command, so it is not run in this lesson; the exact behaviour is in each system's manual. In SQLite you take the write lock for the whole database with BEGIN IMMEDIATE, as in lesson 6.6. Everyone else who wants to write waits until you commit.
This is safe but poor for forms, because the lock lasts as long as the person thinks.
3. Optimistic: a version column
This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). It adds a column to one real table in your browser's copy (Reset data puts the original back). Add a number to the row that goes up with every change:
ALTER TABLE products ADD COLUMN version INTEGER NOT NULL DEFAULT 0;
UPDATE products SET stock = 10 WHERE product_id = 1;
SELECT product_id, stock, version FROM products WHERE product_id = 1;
product_id stock version
---------- ----- -------
1 10 0
(1 row)
ALTER TABLE accounts ADD COLUMN version INTEGER NOT NULL DEFAULT 0;
UPDATE accounts SET balance_cents = 10000 WHERE account_id = 1;
SELECT account_id, balance_cents, version FROM accounts WHERE account_id = 1;
account_id balance_cents version
---------- ------------- -------
1 10000 0
(1 row)
ALTER TABLE sections ADD COLUMN version INTEGER NOT NULL DEFAULT 0;
UPDATE sections SET capacity = 30 WHERE section_id = 1;
SELECT section_id, capacity, version FROM sections WHERE section_id = 1;
section_id capacity version
---------- -------- -------
1 30 0
(1 row)
To save, say "update the row only if the version is still the one I read", and bump the version. A and B both read the same value and version 0 (the cell above), and each saves its own calculation. A goes first:
UPDATE products SET stock = 7, version = version + 1 WHERE product_id = 1 AND version = 0;
(1 row changed)
Now B saves, still asking for version 0:
UPDATE products SET stock = 6, version = version + 1 WHERE product_id = 1 AND version = 0;
(0 rows changed)
SELECT product_id, stock, version FROM products WHERE product_id = 1;
product_id stock version
---------- ----- -------
1 7 1
(1 row)
UPDATE accounts SET balance_cents = 7000, version = version + 1 WHERE account_id = 1 AND version = 0;
(1 row changed)
Now B saves, still asking for version 0:
UPDATE accounts SET balance_cents = 6000, version = version + 1 WHERE account_id = 1 AND version = 0;
(0 rows changed)
SELECT account_id, balance_cents, version FROM accounts WHERE account_id = 1;
account_id balance_cents version
---------- ------------- -------
1 7000 1
(1 row)
UPDATE sections SET capacity = 27, version = version + 1 WHERE section_id = 1 AND version = 0;
(1 row changed)
Now B saves, still asking for version 0:
UPDATE sections SET capacity = 26, version = version + 1 WHERE section_id = 1 AND version = 0;
(0 rows changed)
SELECT section_id, capacity, version FROM sections WHERE section_id = 1;
section_id capacity version
---------- -------- -------
1 27 1
(1 row)
A's save matched version 0 and succeeded, making the version 1. B's save asked for version 0, found none, and changed 0 rows. The program sees "0 rows changed", knows someone else changed the row, and tells B: "this row was changed by someone else; reload and try again". Nothing was overwritten (the row still holds A's value).
(In a real program the two readers are separate connections; the check works the same, because the WHERE version = ? test happens inside the database.)
Worked example: choosing a design
| Situation | Better choice | Why |
|---|---|---|
| Two admins rarely edit the same product page | Optimistic | conflicts are rare; no one waits |
| A hot item sold by hundreds of shoppers per minute | One-statement update (qty = qty - 1) or pessimistic lock |
optimistic retries would pile up |
| A form that stays open for ten minutes | Optimistic | a lock held that long is not acceptable |
The situations are made up.
Common mistakes
- Forgetting
AND version = ?in theUPDATE; then the check does nothing. - Forgetting to bump the version on every change.
- Ignoring
rowcount == 0. The program must handle the refusal and offer a retry. - Using optimistic control on a very hot row, where almost every save conflicts.
Key takeaways
- Pessimistic control locks first; optimistic control checks at save time.
- A version column plus
WHERE version = ?detects that a row changed after you read it. - If
rowcountis 0, nothing was saved; reload and retry. - Choose by how often conflicts happen and how long the user holds the record.
Practice
1. What is the difference between optimistic and pessimistic control?
Show answer
Pessimistic locks the data before working on it; optimistic does not lock and checks for a conflict when saving.
2. In the example, why did B's update change 0 rows?
Show answer
B asked for version = 0, but A's save had already made the version 1.
3. What should the program do when rowcount is 0?
Show answer
Tell the user the record changed, reload it and let them redo the edit.
4. Why is pessimistic locking a poor fit for an edit form?
Show answer
The lock would be held for as long as the person takes, blocking everyone else.
5. Why must every update bump the version?
Show answer
Otherwise a changed row would still have the old version number and a stale save would pass the check.
6. When is a single SET qty = qty - 1 better than either design?
Show answer
When the change can be expressed in one statement, since the database applies it safely in one step with no extra column or lock logic.