Spring Boot – @Transactional Part 3 (Isolation Level)

 


📘 Spring Boot – @Transactional Part 3 (Isolation Level)

 

🔹 What is Isolation Level?

Isolation level defines how visible one transaction’s changes are to other concurrent transactions.

@Transactional(
    propagation = Propagation.REQUIRED,
    isolation = Isolation.READ_COMMITTED
)
public void userOrder() {
    // some operations here
}

🔹 Isolation Levels vs Problems

Isolation Level Dirty Read Non-Repeatable Read Phantom Read Concurrency
READ_UNCOMMITTED Yes Yes Yes High
READ_COMMITTED No Yes Yes Medium
REPEATABLE_READ No No Yes Low
SERIALIZABLE No No No Very Low

Note:
Most relational DBs use READ_COMMITTED as default (e.g., Oracle, PostgreSQL).
MySQL (InnoDB) default = REPEATABLE_READ.


🔹 Dirty Read Problem

Definition:
Transaction A reads uncommitted data from Transaction B.
If B rolls back, A has read invalid data.

Timeline Example:

Time Transaction A Transaction B DB Status
T1 BEGIN BEGIN id:123, status: free
T2 Update row id=123 → booked (not committed) id:123, status: booked
T3 Read row → booked id:123, status: booked
T4 ROLLBACK id:123, status: free

👉 A read data that never actually existed!


🔹 Non-Repeatable Read

Definition:
Transaction A reads the same row twice, but gets different values because another transaction committed in between.

Example:

Time Transaction A DB
T1 BEGIN ID=1, status: free
T2 Read ID=1 → free
T3 Another txn updates & commits → booked
T4 Read ID=1 → booked
T5 COMMIT

🔹 Phantom Read

Definition:
Transaction A runs the same query twice, but second time gets extra rows (new inserts).

Example:

Time Transaction A DB
T1 BEGIN ID=1 free, ID=3 booked
T2 Read where ID>0 and ID<5 → 2 rows
T3 Another txn inserts ID=2 and commits
T4 Read same query → 3 rows
T5 COMMIT

🔹 DB Locking Types

Lock Type Another Shared Lock Another Exclusive Lock
Shared Lock (Read) Yes No
Exclusive Lock (Write) No No
  • Shared Lock = READ LOCK
  • Exclusive Lock = WRITE LOCK

🔹 Isolation Level Locking Strategy

Isolation Level Locking Strategy
READ_UNCOMMITTED No locks for read, no locks for write
READ_COMMITTED Read → shared lock (released immediately), Write → exclusive lock till commit
REPEATABLE_READ Read → shared lock till commit, Write → exclusive lock till commit
SERIALIZABLE Same as REPEATABLE_READ + Range locks to prevent phantom rows


🧠 Interview Notes (Important)

  • Dirty Read → Only possible in READ_UNCOMMITTED
  • Non-Repeatable Read → Solved in REPEATABLE_READ
  • Phantom Read → Solved only in SERIALIZABLE
  • Higher isolation = more locks = less concurrency = slower performance
  • In Spring Boot:
@Transactional(isolation = Isolation.REPEATABLE_READ)

 

Leave a Reply