STUDY/database

[DB] MVCC 설명_2 (쉬운코드)

까미이모 2023. 12. 19. 16:29

MySQL 에서 lost update 해결

예시1) x = 50, y = 10

Transaction 1 : x가 y에 40을 이체한다

Transaction 2 : x에 30을 입금한다

Transaction 1 (repeatable read) Transaction 2(repeatable read)
  read(x) = 50 Locking read
read(x) = 50 (기다림)  
  write(x = 80)
  commit (lock 해제)
read(x) = 80 Locking read  
write(x = 40)  
read(y) = 10 Locking read  
write(y = 50)  
commit (lock 해제)  

Locking read

Locking read 란 read 할때 lock을 획득 하는 것으로 쿼리로 적용 시킬 수 있다

  • SELECT 문 끝에 FOR UPDATE : write lock과 같은 exclusive lock 획득
  • SELECT 문 끝에 FOR SHARE : shared lock 획득
  • locking read는 가장 최근의 commit된 데이터를 읽는다

 

repeatable read에서 write shew 문제

예시) x = 20, y = 20

Transaction 1 : x와 y를 더해서 x에 쓴다

Transaction 2 : x와 y를 더해서 y에 쓴다

Transaction 1 (repeatable read) Transaction 2(repeatable read)
read(x) = 10  
  read(x) = 10
read(y) = 10  
  read(y) = 10
write(x = 20)  
  write(y = 20)
commit  
  commit

정상적으로 되면 x = 30, y = 20 이 되어야 하는데 둘다 20이 되었다 이러한 경우를 write skew 라 한다

 

MySQL에서 write skew해결 → locking read

Transaction 1 (repeatable read)  Transaction 2(repeatable read)
read(x) = 10 🔒 Locking read  
  read(x) = 10 (기다림)
read(y) = 10  
write(x = 20)  
commit  
  read(x) = 20 🔒
  read(y) = 10 🔒
  write(y = 30)
  commit

 

PostgreSql 에서 write skew 해결

repeatable read 특징인 first-updater-win 으로 뒤의 tx는 rollback된다

Transaction 1 (repeatable read) Transaction 2(repeatable read)
read(x) = 10 🔒 Locking read  
  read(x) = 10 (기다림)
read(y) = 10  
write(x = 20)  
commit  
  read(x) = 20 🔒
  rollback

 

Serializable level 에서는?

MySQL : repeatable read 와 유사, tx의 모든 평범한 select문은 암묵적으로 select … for share 처럼 동작한다

PostgreSql : SSI로 구현, first-committer-winner

 

 

출처: 쉬운코드