# SQL Server Locking, Blocking & Deadlocks
Blocking là bình thường. Deadlock mới là tình huống cần xử lý. Hai khái niệm này rất hay bị nhầm trong phỏng vấn.
## Shared Lock
Dùng khi đọc dữ liệu.
“`text
Reader
-> Shared Lock
“`
Nhiều shared lock có thể cùng tồn tại.
## Exclusive Lock
Dùng khi update hoặc delete.
“`text
Writer
-> Exclusive Lock
“`
Exclusive lock chặn các operation không tương thích.
## Update Lock
Update lock được SQL Server sử dụng trong một số flow để giảm deadlock khi một row được đọc với ý định sắp update.
## Intent Lock
Intent lock cho biết một object cấp cao hơn có lock ở cấp thấp hơn.
Ví dụ:
“`text
Table: Intent Exclusive
Page: Intent Exclusive
Row: Exclusive
“`
## Blocking
“`text
Transaction A holds lock
Transaction B needs same resource
Transaction B waits
“`
Khi A commit hoặc rollback, B tiếp tục.
Blocking không đồng nghĩa với lỗi.
## Deadlock
“`text
Transaction A:
locks User
needs Wallet
Transaction B:
locks Wallet
needs User
“`
Ta có:
“`text
A waits for B
B waits for A
“`
SQL Server phải chọn một transaction làm **deadlock victim**.
Error phổ biến:
“`text
1205
“`
## Cách giảm deadlock
### 1. Access resource theo cùng thứ tự
Không tốt:
“`text
A: User -> Wallet
B: Wallet -> User
“`
Tốt hơn:
“`text
A: User -> Wallet
B: User -> Wallet
“`
### 2. Giữ transaction ngắn
Không nên:
“`text
BEGIN TRANSACTION
Call external API
Wait
Update DB
COMMIT
“`
### 3. Tối ưu index
Query scan quá nhiều rows có thể giữ nhiều lock hơn và chạy lâu hơn.
### 4. Retry deadlock victim
“`csharp
for (var retry = 0; retry < 3; retry++)
{
try
{
await ExecuteTransactionAsync();
break;
}
catch (SqlException ex) when (ex.Number == 1205)
{
await Task.Delay(100 * (retry + 1));
}
}
```
## Interview questions
### Blocking vs deadlock?
> Blocking means one transaction waits for another to release a resource. A deadlock is a circular dependency where transactions wait on each other and SQL Server must terminate one.
### How do you troubleshoot deadlocks?
> I inspect the deadlock graph, identify resource ordering and transaction duration, optimize indexes, standardize access order, and add retry logic where appropriate.
## Key takeaways
Deadlock handling không chỉ là retry. Cần tìm root cause:
“`text
Resource ordering
Transaction duration
Indexing
Query plan
Concurrency level
“`
**Next:** Part 4 — SQL Index Fundamentals