timestamp ordering and OCC
concurrency control without locks: order by timestamp, or validate at the end and abort.
- address
- everything.locking.timestamp_ordering_and_occ
- part
- part 15, locks and concurrency control
- chapter
- chapter 9 of 10
- reading time
- 10 min
two ways to get serializability without making anyone wait for a lock. timestamp ordering fixes the serial order up front: every transaction gets a timestamp at start, every item remembers the newest timestamp that read it and wrote it, and an operation that arrives too late for its timestamp aborts. optimistic concurrency control lets everyone run on private copies and checks at the end, in a validation phase, whether anything they read changed underneath them. both trade waiting for aborts.
the picture
you know how two-phase locking makes conflicting transactions wait, and then needs a deadlock detector for when the waiting goes in circles? the alternative is to never wait at all. if two transactions conflict in a way that could break serializability, abort one and restart it.
think of a deli counter with numbered tickets. timestamp ordering is "serve strictly in ticket order": if number 12 tries to grab the last loaf after number 15 already touched it, number 12 is sent back to take a new ticket. optimistic control is self-checkout: everyone fills their basket freely, and at the till you check nothing in your basket was changed by someone who paid in the meantime. if it was, put it all back and start again.
timestamp ordering
each transaction T gets a timestamp ts(T) when it starts, and the rule is that the result must equal the serial order by timestamp. each item x keeps two numbers: RTS(x), the largest timestamp that read it, and WTS(x), the largest that wrote it.
- read x by T: if ts(T) < WTS(x), a younger transaction already overwrote the value T should see. abort T. otherwise read, and raise RTS(x) to ts(T).
- write x by T: if ts(T) < RTS(x), a younger transaction already read x and should have seen this write. abort T. if ts(T) < WTS(x), a younger write is already there. abort T. otherwise write, and set WTS(x) to ts(T).
- 1T1R1(A)
- 2T2R2(A)
- 3T2W2(A)
- 4T1W1(A)
- timestamps: T1 = 1, T2 = 2. smaller is older, and goes first in the serial order.
| item | RTS | WTS |
|---|---|---|
| A | 0 | 0 |
each item starts with RTS = WTS = 0. step through the schedule.
every precedence-graph edge then goes from an older transaction to a younger one, because any operation that would make an edge point backwards is refused. timestamps only go up, so no cycles. it's the same argument as 2PL with timestamps in place of lock points, but decided at start instead of discovered during the run.
the Thomas write rule
in "blind writes", T2 writes A, then T1 (older) writes A. in timestamp order T1's write comes first and T2's overwrites it, so T1's value would never be seen by anyone, provided nobody younger read A in between (that case is caught by the RTS check). Thomas's observation (1979): just skip the obsolete write instead of aborting. the result is still view serializable, though no longer conflict serializable: the schedule's ww pair is in the "wrong" order, it just doesn't matter.
the weak spots: long transactions are old by the time they write, so they're the ones that keep losing. a reader has to write (RTS) to shared state on every read. and basic TO allows reading uncommitted data, so real implementations add commit bits or buffering. MVCC systems keep the idea but store several versions, so a late reader can be handed the version that matches its timestamp instead of being aborted. that's multiversion timestamp ordering, and a snapshot is a close cousin of "the versions as of my timestamp".
optimistic concurrency control
Kung and Robinson (1981) split each transaction into three phases:
- read: run the transaction against private copies. record the read set (what you read) and the write set (what you'd write). no locks.
- validate: at the end, check against every transaction that committed after you started. if any of them wrote something in your read set, you may have read a stale value: abort.
- write: if valid, install the write set. validation and write happen as one step, so nobody slips in between.
OCC is cheap when conflicts are rare: no lock manager, no waiting, no deadlocks. when conflicts are common it's expensive: work is thrown away at the very end, after all of it was done, and the same transaction can lose again and again. in-memory databases like it (Hekaton in SQL Server uses an optimistic multiversion scheme), and so do most application caches.
T1: read ..... validate ✓ write
T2: read ............... validate ?the app-level version: a version column
you've probably written OCC already. read a row with its version number, let the user think for a minute (no transaction open, no lock held), then write it back only if the version hasn't moved. the validate-and-write step is a single UPDATE, which postgres runs atomically:
CREATE TABLE accounts (id int PRIMARY KEY, balance numeric(12,2) NOT NULL, version int NOT NULL);
INSERT INTO accounts VALUES (1, 100.00, 1);
SELECT balance, version FROM accounts WHERE id = 1; -- the app reads version 1
UPDATE accounts SET balance = 130.00, version = version + 1
WHERE id = 1 AND version = 1; -- someone else saves first
UPDATE accounts SET balance = 110.00, version = version + 1
WHERE id = 1 AND version = 1; -- our save: validation fails
SELECT balance, version FROM accounts WHERE id = 1;| balancenumeric | versionint4 |
|---|---|
| 100.00 | 1 |
| balancenumeric | versionint4 |
|---|---|
| 130.00 | 2 |
we read the row and keep version 1 in hand. no transaction stays open and no lock is held while the user thinks. the other app read the same version (its save checks it too).
UPDATE 1, then UPDATE 0. the second save matched no row because the version moved: that's a failed validation, and the app re-reads and retries (or shows the user the newer data). with two real sessions, the second UPDATE waits for the first one's row lock, then re-checks the WHERE on the new version and finds nothing (lost updates has that capture). so even the "lock-free" version relies on a row lock for the moment of validation.
one level deeperwhere postgres sits
postgres uses no textbook timestamp ordering and no pure OCC. writes take row locks held until commit (strict 2PL for writes). reads use snapshots, which is multiversioning: each transaction effectively reads "as of" its snapshot, like multiversion TO without the read timestamps. its SERIALIZABLE (SSI) is optimistic in spirit: nothing waits for a read, conflicts are recorded as they happen, and a transaction is aborted with 40001 when a dangerous pattern appears, sometimes not until COMMIT, which is exactly where OCC would validate.
keylines
- timestamp ordering: serial order = start order. RTS and WTS per item, late operations abort.
- the Thomas write rule skips an obsolete write instead of aborting.
- OCC: read on private copies, validate at the end, then write. first committer wins.
- both trade waiting for aborts: great when conflicts are rare, bad when they're common.
- a version column checked in UPDATE ... WHERE is OCC in your app. UPDATE 0 means retry.