Suppose we are booking a room on the hotel and there is only 1 room available. Customer A opens booking page. Hotel immediately reserves the room. Room 101 Locked Customer B tries to book Please Wait Room Currently Reserved Customer B must wait. This is exactly how SQL Server locks work. This is Pessimistic Concurrency.
Customer A opens booking page. Customer
B also opens booking page. Both seen Room Available. No lock is taken. When
Customer A confirms booking success. When Customer B confirms booking Sorry,
room already booked. Conflict detected later. This is Optimistic Concurrency.
SQL Server Mapping
|
Concurrency Model |
SQL Server Feature |
|
Pessimistic |
READ COMMITTED |
|
Pessimistic |
REPEATABLE READ |
|
Pessimistic |
SERIALIZABLE |
|
Optimistic |
SNAPSHOT |
|
Optimistic |
RCSI (Read Committed
Snapshot Isolation) |
Comparison Table
|
Feature |
Pessimistic
Concurrency |
Optimistic
Concurrency |
|
Assumption |
Conflicts are common |
Conflicts are rare |
|
Uses Locks |
Yes |
Minimal |
|
Blocking |
High |
Low |
|
Deadlocks |
Possible |
Rare |
|
Concurrency |
Lower |
Higher |
|
TempDB Usage |
No |
Yes |
|
Update Conflict |
No |
Yes (3960) |
|
Reader-Writer Blocking |
Yes |
No |
|
Performance |
Lower |
Higher |
|
Best For |
OLTP with
frequent updates |
Reporting,
High-Concurrency Systems |
Pessimistic Concurrency assumes that data conflicts are likely, so SQL Server acquires locks before reading or modifying data. This prevents other transactions from making conflicting changes but can cause blocking and deadlocks. Isolation levels such as READ COMMITTED, REPEATABLE READ, and SERIALIZABLE use pessimistic concurrency. Optimistic Concurrency assumes conflicts are rare. Instead of locking rows for reads, SQL Server uses row versioning stored in TempDB. Transactions work on snapshots of data and conflicts are checked when updates occur. SNAPSHOT Isolation and RCSI are examples of optimistic concurrency. If another transaction changes a row after the snapshot transaction begins, SQL Server raises error 3960 and aborts the transaction. Pessimistic concurrency provides stronger immediate protection but lower concurrency, while optimistic concurrency provides higher scalability and lower blocking at the cost of possible update conflicts and additional TempDB usage.
No comments:
Post a Comment
If you have any doubt, please let me know.