Timestamp-Based vs Lock-Based Concurrency Control
Comparison: Timestamp vs Locking Protocols
Read aloud is unavailable in this browser.
Two Philosophies of Concurrency Control
In the realm of database concurrency control, two dominant paradigms have emerged, each representing a fundamentally different philosophy for managing simultaneous access to shared data: Lock-Based Protocols and Timestamp-Based Protocols. Understanding the distinction between these approaches—and knowing when to apply each—is essential knowledge for any database architect, systems engineer, or developer working with transactional systems.
While both paradigms ultimately aim to ensure serializability and data consistency, they approach this goal from diametrically opposite directions. Lock-based protocols are pessimistic in nature, assuming conflicts are likely and preventing them proactively through exclusive access. Timestamp-based protocols are optimistic (or at least utilize a different conflict resolution strategy), using temporal ordering to validate whether transactions can proceed without violating serializability.
This comparison isn't merely academic. The choice between these protocols—or hybrid combinations thereof—directly impacts system throughput, latency, deadlock behavior, and the overall user experience of database applications.
By the end of this page, you will understand the fundamental philosophical differences between timestamp-based and lock-based concurrency control, their core mechanisms, conflict resolution strategies, and the conditions under which each approach excels. You'll develop the analytical framework to evaluate which protocol suits specific workload characteristics.
Philosophical Foundations
Before diving into technical mechanisms, we must understand the philosophical divergence that gives rise to these two protocol families. This isn't merely about different algorithms—it's about fundamentally different assumptions regarding the nature of concurrent workloads and the optimal strategy for ensuring consistency.
The Pessimistic Philosophy: Lock-Based Protocols
Lock-based protocols operate under the assumption that conflicts between concurrent transactions are probable and damaging. Given this worldview, the rational strategy is to prevent conflicts from occurring in the first place by ensuring that only one transaction can access a conflicting data item at a time.
The mental model is akin to a physical key-lock mechanism: if you want to modify a room, you must first obtain the key, and no one else can enter until you relinquish it. This approach guarantees safety but introduces the possibility of blocking—transactions must wait for locks held by others.
The Timestamp-Based Philosophy
Timestamp-based protocols operate from a different premise. Rather than preventing conflicts through mutual exclusion, they assign each transaction a unique timestamp at entry and use this temporal marker to determine a serialization order. The philosophy is: define the order first, then enforce it.
When conflicts arise, they are resolved by comparing timestamps. If a transaction's operation would violate the timestamp order (e.g., an older transaction trying to read data already written by a newer one), the violating transaction is typically aborted and restarted rather than forced to wait.
This approach eliminates blocking but introduces the possibility of rollbacks. The implicit assumption is that conflicts are relatively rare, or that the cost of occasional restarts is acceptable compared to the overhead of lock management.
| Aspect | Lock-Based Protocols | Timestamp-Based Protocols |
|---|---|---|
| Core Philosophy | Prevent conflicts through mutual exclusion | Order transactions temporally, detect violations |
| Conflict Assumption | Conflicts are likely and must be avoided | Conflicts are manageable through ordering |
| Response to Conflict | Block (wait) until conflict resolves | Abort and restart violating transactions |
| Mental Model | Physical key-lock mechanism | Temporal ordering and validation |
| Primary Trade-off | Waiting time vs throughput | Restart overhead vs lock management |
| Deadlock Possibility | Yes—circular wait possible | No—no waiting, hence no deadlock |
A critical insight is that neither approach is objectively better. Lock-based protocols excel when conflicts are frequent and transaction abort costs are high. Timestamp-based protocols shine when conflicts are rare or when avoiding deadlocks is paramount. Modern systems often hybridize these approaches.
Core Mechanism Comparison
Understanding the operational mechanics of each protocol family reveals why they exhibit such different behaviors. Let's examine the core operations that each protocol performs during transaction execution.
Lock-Based Protocol Mechanics
In lock-based protocols, every data access operation requires acquiring the appropriate lock:
- Before Reading: Acquire a Shared (S) lock on the data item
- Before Writing: Acquire an Exclusive (X) lock on the data item
- Lock Compatibility: S-S compatible (concurrent reads allowed), S-X and X-X incompatible
- Blocking: If desired lock is incompatible with existing lock, transaction waits
- Lock Release: Controlled by protocol variant (2PL, Strict 2PL, etc.)
The transaction maintains a lock set throughout execution, and the lock manager maintains a lock table tracking all granted and pending lock requests. This infrastructure introduces overhead but provides fine-grained control over access patterns.
Timestamp-Based Protocol Mechanics
In timestamp-based protocols, each transaction receives a unique timestamp TS(Tᵢ) at initiation. Each data item X maintains:
- W-timestamp(X): Timestamp of the last transaction that successfully wrote X
- R-timestamp(X): Largest timestamp of any transaction that successfully read X
Operations proceed as follows:
1234567891011121314151617181920212223242526
// TIMESTAMP PROTOCOL: Read OperationREAD(Transaction Ti, DataItem X): if TS(Ti) < W-timestamp(X): // Ti needs to read a value that was already overwritten // by a younger transaction - violates timestamp order ABORT(Ti) and RESTART with new timestamp else: // Read is valid - proceed Execute read operation R-timestamp(X) = max(R-timestamp(X), TS(Ti)) // TIMESTAMP PROTOCOL: Write Operation WRITE(Transaction Ti, DataItem X): if TS(Ti) < R-timestamp(X): // A younger transaction has already read the current value // Ti's write would invalidate that read - abort ABORT(Ti) and RESTART with new timestamp else if TS(Ti) < W-timestamp(X): // A younger transaction has already written a newer value // Ti's write is obsolete (Thomas Write Rule may ignore instead of abort) ABORT(Ti) and RESTART with new timestamp // Basic protocol // OR: Ignore the write (Thomas Write Rule variant) else: // Write is valid - proceed Execute write operation W-timestamp(X) = TS(Ti)Key Mechanistic Differences
The mechanistic differences have profound implications:
State Maintenance:
- Lock protocols maintain per-transaction lock sets and a global lock table
- Timestamp protocols maintain per-data-item timestamps (simpler distributed management)
Waiting vs Restarting:
- Lock protocols cause blocking when locks conflict—transaction progress halts
- Timestamp protocols never block but may restart transactions repeatedly
Centralized vs Distributed:
- Lock tables are harder to manage in distributed systems (requires distributed lock manager)
- Timestamps are local to data items, facilitating distributed database design
Overhead Profile:
- Lock protocols have overhead for lock acquisition, release, and deadlock detection
- Timestamp protocols have overhead for timestamp comparison and potential restarts
Lock-based systems require maintaining a lock table that can grow large with fine-grained locking. Timestamp-based systems avoid this by embedding ordering information directly in data items. However, timestamp systems must handle the bookkeeping of aborted transactions and their restarts, which can be significant under high-contention workloads.
Serializability Guarantees
Both protocol families aim to ensure conflict serializability—the requirement that the schedule of interleaved operations is equivalent to some serial execution. However, they achieve this guarantee through fundamentally different mechanisms.
How Lock-Based Protocols Ensure Serializability
Two-Phase Locking (2PL) guarantees serializability through a structural constraint:
- Growing Phase: Transaction may acquire locks but not release any
- Shrinking Phase: Transaction may release locks but not acquire new ones
Theorem (2PL serializability): Any schedule of transactions following 2PL is conflict-serializable. The serialization order is determined by the lock points—the moment when each transaction has acquired all its locks.
The proof is elegant: if T₁'s lock point precedes T₂'s, then T₁ appears before T₂ in the equivalent serial schedule. This creates a total order among transactions based on their lock points.
How Timestamp Protocols Ensure Serializability
Timestamp ordering ensures serializability through a different mechanism:
- Pre-established Order: Each transaction's timestamp defines its position in the serialization order before it executes any operation
- Validation at Access: Every read and write operation validates that proceeding wouldn't violate the predetermined order
- Abort on Violation: If an operation would create an out-of-order dependency, the transaction is aborted
Theorem (Timestamp ordering serializability): If all successful transactions in a timestamp-ordered schedule complete without violation, the schedule is equivalent to a serial schedule ordered by transaction timestamps.
The Equivalence and the Difference
Both protocols produce conflict-serializable schedules, but with crucial differences:
Order Determination Timing:
- Lock-Based: Serialization order emerges dynamically based on when transactions acquire their locks
- Timestamp-Based: Serialization order is fixed at transaction start (timestamp assignment)
Order Control:
- Lock-Based: Transactions implicitly negotiate their order through lock acquisition patterns
- Timestamp-Based: Order is pre-determined; transactions cannot change their position in the serial order
Implications:
- Lock-based protocols allow transactions to "negotiate" for resources—first to lock wins
- Timestamp protocols enforce a strict temporal discipline—older transactions have priority
This difference matters in practice: if an older transaction is slow to access a data item, timestamp protocols may cause newer transactions that would have completed first to abort repeatedly. Lock-based protocols would simply let the faster transaction proceed first.
In timestamp protocols, a slow transaction with an old timestamp can cause repeated aborts of younger transactions that conflict with it. This is a form of starvation where the old transaction's "priority" (its early timestamp) forces others to restart. Lock-based protocols face different starvation risks based on their lock-granting policies.
Conflict Resolution Strategies
When two transactions attempt conflicting operations (e.g., one reads while another writes the same item), the protocols must resolve the conflict. The resolution strategy is one of the most significant differentiators between these paradigms.
Lock-Based Conflict Resolution: Blocking and Waiting
In lock-based protocols, conflicts are resolved through blocking:
- Conflict Detection: Lock manager detects incompatible lock request
- Wait Queue: Requesting transaction is placed in a wait queue for the locked item
- Blocking: Transaction execution suspends until lock becomes available
- Grant on Release: When holder releases lock, next waiter is granted access
This approach has several implications:
- No wasted work: Blocked transactions have not yet performed their operations
- Waiting overhead: CPU and other resources may be idle while waiting
- Deadlock risk: Circular wait conditions can cause permanent blocking
- Fairness: Wait queue ordering determines which transaction proceeds next
Timestamp-Based Conflict Resolution: Abort and Restart
In timestamp protocols, conflicts are resolved through transaction abort:
- Conflict Detection: Timestamp comparison reveals out-of-order access
- Immediate Abort: Violating transaction is aborted without waiting
- Rollback: All changes made by aborted transaction are undone
- Restart: Transaction is assigned a new timestamp and begins fresh
This approach has different implications:
- Wasted work: Completed operations must be rolled back
- No waiting: Other transactions can proceed immediately
- No deadlock: Circular wait is impossible—no one waits
- Repeated aborts: High-contention scenarios may cause livelock
- •Wait on Conflict — Requesting transaction blocks
- •No Rollback — Work done so far is preserved
- •Deadlock Detection — Required to handle circular waits
- •Queue Management — Fair ordering of waiters
- •Resource Holding — Locks held during wait
- •Abort on Conflict — Violating transaction restarts
- •Rollback Required — Undo completed operations
- •Deadlock-Free — No waiting means no circular wait
- •Repeated Restarts — Possible under contention
- •Resource Recycling — Data items immediately available
Cost Analysis of Conflict Resolution
The choice between blocking and aborting has measurable cost implications:
Blocking Cost (Lock-Based):
- CPU underutilization while waiting
- Connection/memory resources held by waiting transaction
- Potential cascade if multiple transactions wait on the same resource
- Deadlock detection overhead
Restart Cost (Timestamp-Based):
- CPU cycles for work that gets discarded
- I/O for logging undo information and performing rollback
- Transaction latency increase (must complete work twice or more)
- Potential starvation if same transaction repeatedly aborts
Break-Even Analysis: If Twork is the time to complete transaction work, Twait is average wait time under locks, and Prestart is the probability of restart:
- Lock-based expected time: Twork + Twait
- Timestamp expected time: Twork / (1 - Prestart) (geometric series for retries)
When contention is low (Prestart is small), timestamp protocols win because Twait can still be significant in lock-based systems due to lock overhead. When contention is high (Prestart approaches 1), lock-based protocols win because waiting is still forward progress.
There exists a workload-specific "contention threshold" where the expected cost of restarts equals the expected cost of waiting. Below this threshold, timestamp protocols tend to outperform; above it, lock-based protocols are superior. Sophisticated systems may dynamically switch strategies based on observed contention.
Deadlock Characteristics
One of the most significant differences between these protocol families is their relationship to deadlock—a condition where transactions are permanently blocked waiting for resources held by each other.
Deadlock in Lock-Based Protocols
Lock-based protocols are inherently susceptible to deadlock. Consider a classic scenario:
- Transaction T₁ holds lock on item X, waits for lock on Y
- Transaction T₂ holds lock on item Y, waits for lock on X
Neither can proceed—both are permanently blocked. This circular wait is the essence of deadlock.
Deadlock Management Strategies:
- Prevention: Structure access patterns to prevent cycles (e.g., acquire locks in a global order)
- Detection: Periodically scan for cycles in the wait-for graph, abort victims
- Timeout: Abort transactions that have waited too long
All strategies carry overhead:
- Prevention constrains application design and may reduce parallelism
- Detection requires graph construction and cycle-finding algorithms
- Timeout may abort transactions unnecessarily or too late
Deadlock in Timestamp Protocols
Timestamp protocols achieve a remarkable property: deadlock is impossible by construction.
Since transactions never wait for resources—conflicts are resolved by aborting, not blocking—there can be no wait-for graph, and hence no cycles. This is a fundamental architectural advantage in systems where deadlock handling is complex or expensive.
The Trade-Off: Deadlock vs Livelock
While timestamp protocols eliminate deadlock, they introduce the possibility of livelock—a situation where transactions repeatedly conflict and abort each other, making no forward progress.
Consider:
- T₁ (timestamp 100) and T₂ (timestamp 150) both access items X and Y
- T₁ writes X, T₂ reads X → T₂ aborts (T₂'s timestamp > W-timestamp set by T₁)
- T₂ restarts with new timestamp 200
- T₂ writes X, but now T₁ tries to read X → T₁ aborts
- T₁ restarts with timestamp 250
- Cycle may continue indefinitely
Livelock differs from deadlock:
- Deadlock: No transaction does any work—complete standstill
- Livelock: Transactions do work but keep discarding it—wasted effort
Both prevent forward progress, but livelock is generally considered less severe because:
- The system is still "active" and responsive
- Eventually, one transaction may succeed by chance
- External intervention (timeout, priority boost) can break livelock more easily
Modern database systems often combine strategies. For example, MySQL's InnoDB uses locking with deadlock detection but incorporates wait-timeout to bound waiting. PostgreSQL's MVCC (Multi-Version Concurrency Control) uses timestamp-like mechanisms that largely avoid blocking while maintaining lock compatibility for write conflicts. The pure forms we study here inform but don't constrain practical implementations.
Throughput and Latency Characteristics
The performance characteristics of these protocols differ substantially under varying workload conditions. Understanding these differences is crucial for system design and capacity planning.
Throughput Behavior
Lock-Based Protocols:
- Low Contention: Throughput scales well with concurrency. Lock overhead is manageable.
- Medium Contention: Throughput begins to plateau as blocking increases. Some transactions wait.
- High Contention: Throughput may dramatically decrease. Lock convoys form where transactions queue behind hot resources.
Timestamp-Based Protocols:
- Low Contention: Throughput scales excellently. No blocking overhead, minimal restarts.
- Medium Contention: Throughput remains high but restart rate increases.
- High Contention: Throughput can collapse as restart rate dominates. Work is repeatedly discarded.
Latency Behavior
Lock-Based Protocols:
- Average Case: Latency includes lock acquisition time plus any waiting time
- Worst Case: Latency unbounded without timeouts—transactions can wait indefinitely for deeply contested resources
- Variance: High variance under contention due to unpredictable wait times
Timestamp-Based Protocols:
- Average Case: Latency is work time divided by success probability
- Worst Case: Repeated restarts can cause very high latency for individual transactions
- Variance: Can be extremely high for "unlucky" transactions under contention
| Workload | Lock-Based Throughput | Timestamp Throughput | Better Choice |
|---|---|---|---|
| Low Contention, Read-Heavy | Very High | Very High (slightly better) | Timestamp (no lock overhead) |
| Low Contention, Write-Heavy | High | High | Either (marginal differences) |
| Medium Contention, Short Txns | High | High | Timestamp (avoids blocking) |
| Medium Contention, Long Txns | Medium | Medium-Low | Lock (restart cost higher) |
| High Contention, Short Txns | Medium | Low | Lock (restart overhead severe) |
| High Contention, Long Txns | Low | Very Low | Lock with deadlock prevention |
| Distributed System | Complex | Simpler | Timestamp (avoids distributed locks) |
The Transaction Length Factor
Transaction length significantly affects protocol performance:
Short Transactions (few operations, quick completion):
- Lock overhead is proportionally higher (acquiring/releasing locks takes measurable time)
- Restart cost is lower (less work to redo)
- Timestamp protocols often win
Long Transactions (many operations, extended duration):
- Lock holding time is longer, increasing blocking for others
- Restart cost is substantial (much work may be discarded)
- Lock protocols often win because restarts are too expensive
Mixed Workloads:
- Short transactions may suffer starvation waiting for long transaction locks
- Long transactions in timestamp systems may repeatedly fail against active short transactions
- Priority mechanisms or protocol hybrids are often necessary
Long-running transactions are problematic for both protocol families but for different reasons. In lock-based systems, they hold locks for extended periods, blocking others. In timestamp systems, their old timestamps may cause repeated aborts of newer transactions that complete faster. Neither protocol handles long transactions gracefully without additional mechanisms.
Implementation Complexity
The practical deployment of these protocols requires substantial infrastructure. Understanding the implementation burden helps explain why certain systems choose specific approaches.
Lock-Based Protocol Implementation Requirements
Lock Manager Component:
- Data structures for lock table (hash table from data item → lock info)
- Lock request queues per locked item
- Deadlock detection mechanism (wait-for graph or timeout)
- Lock upgrade/downgrade logic (S → X conversion)
- Intention locks for hierarchical locking
Memory Overhead:
- Lock table entry per locked item
- Queue entry per waiting transaction
- Wait-for graph nodes and edges
CPU Overhead:
- Lock acquisition: hash lookup, queue manipulation
- Lock release: queue management, waiter notification
- Deadlock detection: periodic graph traversal
Distributed Considerations:
- Distributed lock manager (DLM) required
- Network round-trips for remote locks
- Complex failure handling (lock holder crashes)
123456789101112131415161718192021222324252627
// LOCK MANAGER: Core Data Structuresstruct LockManager { HashMap<DataItem, LockTableEntry> lockTable; Graph<Transaction, Transaction> waitForGraph; // For deadlock detection} struct LockTableEntry { LockMode currentMode; // SHARED, EXCLUSIVE, or NONE Set<Transaction> holders; // Current lock holders Queue<LockRequest> waitQueue; // Waiting requests} // LOCK MANAGER: Lock Acquisitionfunction acquireLock(txn: Transaction, item: DataItem, mode: LockMode) { entry = lockTable.getOrCreate(item); if (isCompatible(entry.currentMode, mode) && entry.waitQueue.isEmpty()) { entry.holders.add(txn); entry.currentMode = combine(entry.currentMode, mode); return SUCCESS; } else { entry.waitQueue.enqueue(LockRequest{txn, mode}); waitForGraph.addEdge(txn, entry.holders); // txn waits for holders checkDeadlock(txn); // May abort if cycle detected return BLOCKED; }}Timestamp Protocol Implementation Requirements
Timestamp Generation:
- Monotonically increasing timestamp source (logical counter or clock)
- Unique timestamps across all transactions
- Distributed: must handle clock synchronization or logical timestamps
Per-Data-Item Metadata:
- W-timestamp: updated on each write
- R-timestamp: updated on each read (max of current and transaction's)
- Storage overhead per data item
Abort/Restart Infrastructure:
- Undo logging for rollback
- Transaction restart mechanism
- New timestamp assignment
Memory Overhead:
- Two timestamps per data item (much simpler than lock table)
- Transaction metadata
CPU Overhead:
- Timestamp comparison on each access
- Rollback execution for aborted transactions
- •Lock table with dynamic sizing
- •Wait queue management per item
- •Deadlock detection/prevention logic
- •Lock escalation policies
- •Intention lock hierarchy
- •Distributed lock coordination
- •Timestamp generator (simpler)
- •Per-item timestamp storage
- •Abort/restart handler
- •Undo log for rollback
- •Timestamp comparison logic
- •Clock synchronization (distributed)
In distributed databases, timestamp protocols have a significant implementation advantage. Each node can independently validate operations using local timestamps without coordinating a global lock table. This aligns well with the decentralized nature of distributed systems and helps explain why many distributed databases favor optimistic or timestamp-based concurrency control.
KEEP LEARNING
There’s more to understand.
You’re reading the introduction. Create a free account to read the complete lesson, save notes and keep track of your progress.