Multiple versions make concurrent reads and writes possible, but versions aren’t free: who creates them, who can see them, and when they can be dropped all need explicit answers.
Part five of the plan series.
1. TxnMgr holds very little
TxnMgr{
currentStartTs uint64 // starts at 2, +1 per txn, < 2^62
currentTxnId uint64 // starts at 2^62, +1 per txn
lowestActiveId uint64
lowestActiveStart uint64
activeTxns []Txn // created, not committed/rolled back
committedTxns []Txn // committed, not GC'd
oldTxns []Txn // GC-able, not GC'd
}
The two counters start in different ranges so timestamps and transaction ids never collide:
- below
2^62is a timestamp; - at or above
2^62is a transaction id.
Comparing the number alone tells you which it is — no extra tag needed.
2. What a transaction records
| Field | Purpose |
|---|---|
startTs / commitId | visibility checks |
undoBuffer | undo log for rollback |
local storage | written but uncommitted data |
active query id / highest active query id | whether any query still references it, for GC |
3. Lifecycle
- Create: allocate start timestamp and id, commitId = 0, join the active queue;
- Read: decide visibility by its own
startTs; - Write: local storage + undo log, with conflict detection;
- Commit: allocate a commit timestamp from
currentStartTs, write redo log to disk, maybe trigger a checkpoint; - Rollback: undo via the undo log;
- GC: leave the active queue; committed goes to the committed queue, rolled back to the old queue.
4. Two GC conditions
A transaction object can’t be freed at commit — other queries may still reference its versions:
| Step | Condition | Meaning |
|---|---|---|
| committed → old | commitId < lowestActiveStart | every active txn started after it, so nobody will read its old versions |
| old → freed | highestActiveQueryId < lowestActiveQueryId | no active query can reference it |
Why the second condition matters: a long query may still read old versions after a transaction commits. Checking commitId alone would free too early.
5. What this means in practice
- Long transactions stall GC: they pin
lowestActiveStart; - Long queries do too: they pin
lowestActiveQueryId; - So “idle in transaction” and half-hour report queries deserve separate handling in production.
6. Checklist
| Check | Expectation |
|---|---|
| Timestamps and txn ids in separate ranges | yes (< 2^62 / ≥ 2^62) |
| Rollback uses undo log | yes |
| GC checks active queries | yes |
| Long transactions are monitored | should be, in production |
7. Next
Transactions give consistency; checkpoint and redo give crash recovery. That’s the last post in this series.
Series: Database kernel · Project page
Get the next post
New posts on database kernels and engineering.