Pessimistic vs Optimistic Locking
You'll learn the two fundamental strategies for preventing conflicts when multiple transactions access the same data simultaneously.
When multiple transactions try to modify the same data, you need a strategy to prevent conflicts. This choice comes down to a philosophical question: do you expect conflicts to happen often, or rarely?
Pessimistic Locking: Assume the Worst
Pessimistic locking assumes conflicts will happen, so it prevents them upfront by acquiring locks immediately when reading data. Think of it like reserving a conference room — you lock it as soon as you enter, blocking everyone else until you're done.
When a transaction reads data with pessimistic locking, it holds a lock that prevents other transactions from modifying (or sometimes even reading) that data. This guarantees no conflicts, but at a cost: other transactions must wait, reducing concurrency and potentially causing contention.
Use pessimistic locking when:
- Conflicts are frequent
- The cost of retrying is high
- You need guaranteed access to data
Optimistic Locking: Assume the Best
Optimistic locking assumes conflicts are rare, so it doesn't lock anything during reads. Instead, it checks at write-time whether the data changed since you read it. This is like editing a shared document — you make your changes freely, but before saving, you check if someone else edited it first.
Typically implemented using version numbers or timestamps, optimistic locking allows high concurrency but requires handling failures when conflicts do occur (usually by retrying the transaction).
Use optimistic locking when:
- Conflicts are rare
- High concurrency is critical
- Retrying failed transactions is acceptable
Key Takeaway: Pessimistic locking prevents conflicts by locking early (lower concurrency, no retries needed), while optimistic locking detects conflicts late (higher concurrency, requires retry logic). Choose based on your conflict frequency and performance priorities.