Sub topic 15
Multiversion and optimistic concurrency control
This chapter assumes you know timestamp ordering, the lock-based protocols from the earlier chapters, and the SQL isolation levels. It covers two designs that avoid blocking. Multiversion concurrency control (MVCC) keeps several versions of each item so readers never wait. Optimistic concurrency control (OCC) lets transactions run without checks and validates them at the end.
Why look beyond locks and basic timestamps
Two-phase locking blocks. Readers wait for writers, and writers wait for readers. It also risks deadlock. Basic timestamp ordering never deadlocks, but it aborts a transaction whenever it reads or writes "too late".
Both problems get worse when most transactions only read. A long report should not stall order entry, and an update should not abort a report that already ran.
The two ideas in this chapter attack the problem differently:
- MVCC keeps old versions, so a late reader can be served an old value instead of being aborted or blocked.
- OCC assumes conflicts are rare, does the work first, and checks for conflicts only at commit.
Multiversion timestamp ordering (MVTO)
Each write creates a new version instead of overwriting. Every transaction Ti gets a start timestamp TS(Ti). Each version Qk of item Q stores three things:
value, the data.W-TS(Qk), the timestamp of the transaction that created the version.R-TS(Qk), the largest timestamp of any transaction that has read this version.
To act on Q, transaction Ti first picks the version Qk with the largest W-TS(Qk) that is at most TS(Ti). This is the version Ti "should see" in timestamp order.
Read(Q). Return the value of Qk. Set R-TS(Qk) = max(R-TS(Qk), TS(Ti)). A read never fails and never waits.
Write(Q).
- If
TS(Ti) < R-TS(Qk), roll backTi. A younger transaction has already read the version thatTiwould have replaced. - Else if
TS(Ti) = W-TS(Qk), overwrite the value ofQk.Tiis updating its own version. - Otherwise create a new version with
W-TS = R-TS = TS(Ti).
Only writes can cause aborts, and only through rule 1. Rule 1 is the same check as basic timestamp ordering applied to one version. Late writes are never ignored, so there is no Thomas write rule here. A late write that no younger transaction has read simply becomes an older version.
A runnable model
class MVItem:
def __init__(self, initial):
# each version is [value, w_ts, r_ts]
self.versions = [[initial, 0, 0]]
def _version_for(self, ts):
return max((v for v in self.versions if v[1] <= ts),
key=lambda v: v[1])
def read(self, ts):
v = self._version_for(ts)
v[2] = max(v[2], ts)
return v[0]
def write(self, ts, value):
v = self._version_for(ts)
if ts < v[2]:
return 'rollback'
if ts == v[1]:
v[0] = value
else:
self.versions.append([value, ts, ts])
return 'ok'
q = MVItem(100)
print(q.read(5)) # 100 (T5 reads the initial version, R-TS becomes 5)
print(q.write(3, 50)) # rollback (3 < R-TS 5)
print(q.write(7, 70)) # ok (new version with W-TS 7)
print(q.read(6)) # 100 (T6 still sees the version before T7)
print(q.read(9)) # 70
print(q.versions) # [[100, 0, 6], [70, 7, 9]]The call q.read(6) runs after T7 has written, yet it returns the older value. T6 is older than T7, so in the equivalent serial order T6 comes first. Basic timestamp ordering would have aborted T6 here.
What MVTO does and does not guarantee
- The result is equivalent to the serial schedule ordered by timestamp, so it is serializable.
- It is not automatically recoverable. A transaction can read a version written by an uncommitted transaction. To get recoverability, a reader of an uncommitted version must delay its commit until the writer commits. If the writer aborts, its readers must abort too (a cascading rollback).
- Old versions need garbage collection. A version can be deleted once no active transaction has a timestamp that would select it.
Snapshot isolation
Most real systems, including PostgreSQL, Oracle and MySQL's InnoDB, use a variant of MVCC called snapshot isolation. This is a different protocol from MVTO.
- A transaction reads from a snapshot: the versions committed before it started, plus its own writes.
- Reads take no locks and never block.
- At commit, a first-committer-wins check applies. If another transaction committed a write to an item this transaction also wrote after this transaction started, this transaction aborts. Some systems use a first-updater-wins lock instead.
Snapshot isolation prevents dirty reads, unrepeatable reads, lost updates and, in the standard definition, phantoms in the snapshot. It is still not serializable.
Optimistic concurrency control (OCC)
OCC, from Kung and Robinson, works well when conflicts are rare. A transaction has three phases:
- Read phase. The transaction reads committed values and does all its writes on private local copies. Nothing is locked and nothing is visible to others.
- Validation phase. The system tests whether committing would violate serializability. If it would, the transaction aborts and its private copies are discarded.
- Write phase. If validation passes, the local copies are copied into the database.
A read-only transaction has no write phase.
Timestamps and the validation test
OCC records three timestamps per transaction:
Start(Ti), when the read phase begins.Validation(Ti), when the validation phase begins. This timestamp defines the serial order, soTS(Ti) = Validation(Ti).Finish(Ti), when the write phase ends.
Let RS and WS be the read set and write set. To validate Ti, check every transaction Tj with TS(Tj) < TS(Ti). At least one of these must hold:
Finish(Tj) < Start(Ti).Tjfinished completely beforeTibegan, so they did not overlap.WS(Tj) ∩ RS(Ti) = ∅andStart(Ti) < Finish(Tj) < Validation(Ti).Tjfinished writing beforeTivalidated, andTjwrote nothing thatTiread. The second condition means the two write phases cannot interleave.
If neither holds for some Tj, then Ti aborts. The check protects against Ti reading a value that an earlier transaction was about to overwrite.
For comparison, the older condition from the textbook also allows overlapping write phases when WS(Tj) is disjoint from both RS(Ti) and WS(Ti). Use the version your course states. The two conditions above are the standard GATE form.
Worked example
Tj: Start 1, Validation 5, Finish 6, WS = {A}. Ti: Start 3, Validation 7, RS = {B, C}.
Since TS(Tj) = 5 < TS(Ti) = 7, check Tj:
- Condition 1:
Finish(Tj) = 6is not less thanStart(Ti) = 3. This fails. - Condition 2:
WS(Tj) = {A}andRS(Ti) = {B, C}do not intersect, and3 < 6 < 7. This holds.
Ti validates and commits.
Comparing the approaches
| Property | Two-phase locking | Basic timestamp ordering | MVTO / snapshot | OCC |
|---|---|---|---|---|
| Readers block | Yes, on writers | No | No | No |
| Deadlock | Possible | None | None | None |
| Conflicts handled | By waiting | By abort | Mostly by abort of writers | By abort at validation |
| Cost when conflicts are rare | Lock overhead | Timestamp overhead | Version storage | Lowest |
| Cost when conflicts are frequent | Waiting | Many restarts | Restarts | Wasted work, many restarts |
| Serial order | Order of lock points | Start timestamp | Start timestamp (MVTO) | Validation timestamp |
The choice depends on the workload. Read-heavy workloads suit MVCC. Low-conflict workloads suit OCC. High-contention workloads suit locking, because waiting wastes less work than abort and redo.
Common errors
- Treating snapshot isolation as serializable. It is not, because of write skew.
- Forgetting that in MVTO a read updates
R-TS. A read can therefore cause a later, older writer to abort. - Using the start time instead of the validation time as the OCC timestamp.
- Assuming OCC is lock-free in every respect. The validation and write phases still need a short critical section.
- Believing MVTO output is automatically cascadeless. Reading an uncommitted version still creates a commit dependency.
Exercise
Item Q has one version with W-TS = 0. T10 reads Q. Then T8 tries to write Q, and later T12 writes Q. Under MVTO, what happens to T8 and T12, and what versions of Q exist at the end?
Show answer
T10's read sets R-TS of the version (W-TS 0) to 10. T8 selects that same version, because 0 is the largest W-TS at most 8. Since 8 < 10, T8 is rolled back. T12 selects the same version too, and 12 is not less than 10 and not equal to 0, so T12 creates a new version with W-TS = R-TS = 12. At the end Q has two versions, W-TS 0 (R-TS 10) and W-TS 12.
Exercise
Under OCC, Tj has Start 2, Validation 4, Finish 9 and writes {X}. Ti has Start 5, Validation 8 and reads {X, Y}. Does Ti pass validation against Tj?
Show answer
No. TS(Tj) = 4 < TS(Ti) = 8, so Tj must be checked. Condition 1 fails because Finish(Tj) = 9 is not less than Start(Ti) = 5. Condition 2 fails because WS(Tj) = {X} intersects RS(Ti) = {X, Y}. In addition, Tj has not finished by Ti's validation time (9 > 8). Ti is aborted and restarted.
Exercise
Why can snapshot isolation produce a schedule that is not serializable even though it prevents lost updates?
Show answer
First-committer-wins only compares write sets. Two transactions that read overlapping data but write different items both commit. This is write skew. Their read-write conflicts form a cycle in the precedence graph, so no equivalent serial order exists.