๐ Concurrency & Locking in Distributed Systems
Welcome back to The Code Hut Distributed Systems series! In this post, we explore one of the core challenges in distributed systems: concurrency control.
Why Concurrency Control Matters
In distributed systems, multiple nodes or services often need to read and write the same data concurrently. Without proper control:
- Data may become inconsistent
- Two services may overwrite each other's changes
- Unexpected errors or crashes can occur
Optimistic Locking
Optimistic locking assumes that conflicts are rare. Changes are made without locking, but before committing, the system checks if the data was modified by another transaction.
In Java (JPA/Hibernate), we use a @Version
field:
@Entity
public class Account {
@Id
@GeneratedValue
private Long id;
private double balance;
@Version
private Long version; // Hibernate checks this on update
}
If two transactions modify the same row concurrently, Hibernate throws OptimisticLockException
. We can handle this with **retries**.
Pessimistic Locking
Pessimistic locking assumes conflicts are likely. The database locks the row when a transaction reads it, preventing other transactions from updating it until the first one completes.
// Using JPA EntityManager
Account account = em.find(Account.class, 1L, LockModeType.PESSIMISTIC_WRITE);
account.setBalance(account.getBalance() + 100);
Other transactions attempting to lock the same row will wait until the lock is released. This avoids conflicts but can cause **blocking or deadlocks**.
---When to Use Which?
- ✅ Optimistic Locking: Low contention, high scalability, retries acceptable.
- ✅ Pessimistic Locking: High contention, critical operations (e.g., financial transactions).
Example: Retry with Optimistic Locking
int retries = 3;
boolean success = false;
while(!success && retries > 0) {
try {
transferMoney(fromId, toId, amount); // method using @Version entity
success = true;
} catch (OptimisticLockException e) {
retries--;
if(retries == 0) throw e;
}
}
---
Next in the Series
In the next post, we’ll explore Consensus & Coordination, including Raft, Paxos, and leader election in distributed systems.
Don’t forget to check the Series Index to follow all posts in the Distributed Systems series! ๐
Comments
Post a Comment