빙응의 공부 블로그
[UniP]MySQL InnoDB 동시성 문제 해결하기 본문
📝배경
파티 프로젝트 UniP 진행 중에 파티에 대한 인원 수를 갱신하는 과정에서 동시성 문제가 발생했습니다.
📌문제 설명
여러 사용자가 동시에 파티에 가입을 하여 파티 인원을 갱신 과정에서 트랜잭션 교착 상태(DeadLock)가 발생했습니다.
교착 상태가 발생하여 한 명의 사용자를 제외한 나머지 사용자가 파티에 가입이 안된 것을 발견했습니다.
Failed to join party: could not execute statement [Deadlock found when trying to get lock; try restarting transaction]
그래서 다시 간단하게 테스트를 진행했습니다.
@Test
void testConcurrencyOnJoinParty() throws InterruptedException {
// Thread 배열 생성
int threadCount = 4;
Thread[] threads = new Thread[threadCount];
for (int i = 0; i < threadCount; i++) {
long id = i + 1;
threads[i] = new Thread(() -> {
try {
pmListService.createJoinParty(PartyRole.USER, id, 1L);
} catch (Exception e) {
System.err.println("Failed to join party: " + e.getMessage());
}
});
}
// When
for (Thread thread : threads) {
thread.start(); // 스레드 시작
}
for (Thread thread : threads) {
thread.join(); // 모든 스레드가 종료될 때까지 대기
}
// Then
Party updatedParty = partyRepository.findById(1L)
.orElseThrow(() -> new IllegalStateException("Party not found"));
System.out.println("People Count in Party: " + updatedParty.getPeopleCount());
// Assertions
assertThat(threadCount).isEqualTo(updatedParty.getPeopleCount());
}
스레드를 이용해서 동시에 가입하는 상황을 연출하였습니다.
동시에 4명의 사람이 한 파티에 가입하는 경우입니다. 다음 테스트를 실행하면 다음과 같은 오류가 발생합니다.
Failed to join party: could not execute statement [Deadlock found when trying to get lock; try restarting transaction] [update party set content=?,end_time=?,is_closed=?,member_id=?,party_limit=?,party_type=?,people_count=?,start_time=?,title=? where id=?]; SQL [update party set content=?,end_time=?,is_closed=?,member_id=?,party_limit=?,party_type=?,people_count=?,start_time=?,title=? where id=?]
Failed to join party: could not execute statement [Deadlock found when trying to get lock; try restarting transaction] [update party set content=?,end_time=?,is_closed=?,member_id=?,party_limit=?,party_type=?,people_count=?,start_time=?,title=? where id=?]; SQL [update party set content=?,end_time=?,is_closed=?,member_id=?,party_limit=?,party_type=?,people_count=?,start_time=?,title=? where id=?]
Failed to join party: could not execute statement [Deadlock found when trying to get lock; try restarting transaction] [update party set content=?,end_time=?,is_closed=?,member_id=?,party_limit=?,party_type=?,people_count=?,start_time=?,title=? where id=?]; SQL [update party set content=?,end_time=?,is_closed=?,member_id=?,party_limit=?,party_type=?,people_count=?,start_time=?,title=? where id=?]
org.opentest4j.AssertionFailedError:
expected: 4
but was: 1
필요:4
실제 :1
해당 사진을 보면 스레드 3,4,5,6이 직접 파티에 대한 업데이트 문을 날리지만 데드락이 발생하는 것을 알 수 있습니다.
그래서 처음에 요청한 스레드 3을 제외한 나머지 스레드가 예외가 발생해 가입이 되지 않습니다.
더 자세하게 분석해봅시다.
아래는 MySQL의 InnoDB 엔진의 내역을 확인할 수 있는 명령어입니다.
SHOW ENGINE InnoDB STATUS;
해당 정보는 트랜잭션이 공유 잠금과 베타 작업을 획득하거나 대기한 정보를 포함하여 로그 또한 포함하고 있습니다.
------------------------
LATEST DETECTED DEADLOCK
------------------------
2025-01-03 17:59:13 0x2534
*** (1) TRANSACTION:
TRANSACTION 139652, ACTIVE 0 sec starting index read
mysql tables in use 1, locked 1
LOCK WAIT 7 lock struct(s), heap size 1128, 3 row lock(s), undo log entries 1
MySQL thread id 221, OS thread handle 3240, query id 2043257 localhost 127.0.0.1 root updating
update party set content='content0',end_time='2025-11-03 17:59:13.178382',is_closed=0,member_id=5,party_limit=10,party_type=2,people_count=1,start_time='2025-01-03 17:59:13.178382',title='title0' where id=1
*** (1) HOLDS THE LOCK(S):
RECORD LOCKS space id 2688 page no 4 n bits 72 index PRIMARY of table `unip`.`party` trx id 139652 lock mode S locks rec but not gap
Record lock, heap no 2 PHYSICAL RECORD: n_fields 12; compact format; info bits 0
0: len 8; hex 8000000000000001; asc ;;
1: len 6; hex 000000022183; asc ! ;;
2: len 7; hex 82000001080110; asc ;;
3: len 8; hex 636f6e74656e7430; asc content0;;
4: len 8; hex 99b8071ecd02b8ce; asc ;;
5: len 1; hex 00; asc ;;
6: len 4; hex 8000000a; asc ;;
7: len 1; hex 82; asc ;;
8: len 4; hex 80000000; asc ;;
9: len 8; hex 99b5871ecd02b8ce; asc ;;
10: len 6; hex 7469746c6530; asc title0;;
11: len 8; hex 8000000000000005; asc ;;
*** (1) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 2688 page no 4 n bits 72 index PRIMARY of table `unip`.`party` trx id 139652 lock_mode X locks rec but not gap waiting
Record lock, heap no 2 PHYSICAL RECORD: n_fields 12; compact format; info bits 0
0: len 8; hex 8000000000000001; asc ;;
1: len 6; hex 000000022183; asc ! ;;
2: len 7; hex 82000001080110; asc ;;
3: len 8; hex 636f6e74656e7430; asc content0;;
4: len 8; hex 99b8071ecd02b8ce; asc ;;
5: len 1; hex 00; asc ;;
6: len 4; hex 8000000a; asc ;;
7: len 1; hex 82; asc ;;
8: len 4; hex 80000000; asc ;;
9: len 8; hex 99b5871ecd02b8ce; asc ;;
10: len 6; hex 7469746c6530; asc title0;;
11: len 8; hex 8000000000000005; asc ;;
*** (2) TRANSACTION:
TRANSACTION 139653, ACTIVE 0 sec starting index read
mysql tables in use 1, locked 1
LOCK WAIT 7 lock struct(s), heap size 1128, 3 row lock(s), undo log entries 1
MySQL thread id 224, OS thread handle 3940, query id 2043256 localhost 127.0.0.1 root updating
update party set content='content0',end_time='2025-11-03 17:59:13.178382',is_closed=0,member_id=5,party_limit=10,party_type=2,people_count=1,start_time='2025-01-03 17:59:13.178382',title='title0' where id=1
*** (2) HOLDS THE LOCK(S):
RECORD LOCKS space id 2688 page no 4 n bits 72 index PRIMARY of table `unip`.`party` trx id 139653 lock mode S locks rec but not gap
Record lock, heap no 2 PHYSICAL RECORD: n_fields 12; compact format; info bits 0
0: len 8; hex 8000000000000001; asc ;;
1: len 6; hex 000000022183; asc ! ;;
2: len 7; hex 82000001080110; asc ;;
3: len 8; hex 636f6e74656e7430; asc content0;;
4: len 8; hex 99b8071ecd02b8ce; asc ;;
5: len 1; hex 00; asc ;;
6: len 4; hex 8000000a; asc ;;
7: len 1; hex 82; asc ;;
8: len 4; hex 80000000; asc ;;
9: len 8; hex 99b5871ecd02b8ce; asc ;;
10: len 6; hex 7469746c6530; asc title0;;
11: len 8; hex 8000000000000005; asc ;;
*** (2) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 2688 page no 4 n bits 72 index PRIMARY of table `unip`.`party` trx id 139653 lock_mode X locks rec but not gap waiting
Record lock, heap no 2 PHYSICAL RECORD: n_fields 12; compact format; info bits 0
0: len 8; hex 8000000000000001; asc ;;
1: len 6; hex 000000022183; asc ! ;;
2: len 7; hex 82000001080110; asc ;;
3: len 8; hex 636f6e74656e7430; asc content0;;
4: len 8; hex 99b8071ecd02b8ce; asc ;;
5: len 1; hex 00; asc ;;
6: len 4; hex 8000000a; asc ;;
7: len 1; hex 82; asc ;;
8: len 4; hex 80000000; asc ;;
9: len 8; hex 99b5871ecd02b8ce; asc ;;
10: len 6; hex 7469746c6530; asc title0;;
11: len 8; hex 8000000000000005; asc ;;
공유 잠금은 다른 트랜잭션이 데이터를 수정할 수 없도록 하는 잠금입니다.
배타 잠금은 트랜잭션이 데이터를 수정하기 위해 획득하는 잠금입니다.
여기서 중요한 것은 공유 잠금은 여러 트랜잭션이 보유 가능하며 다른 트랜잭션이 공유 잠금을 가지고 있을 경우 배타 잠금을 얻지 못합니다.
해당 정보를 요약해보면
1. 트랜잭션 1(TRANSACTION 139652) : party 테이블의 id=1인 행을 업데이트 요청
2. 트랜잭션 1가 클러스터링 인덱스에서 공유 잠금을 보유 (배타 잠금 요청 중)
3. 트랜잭션 2(TRANSACTION 139653) : party 테이블의 id=1인 행을 업데이트 요청
4. 트랜잭션 2가 클러스터링 인덱스에서 공유 잠금을 보유 (배타 잠금 요청 중)
이 상황은 둘다 배타 잠금을 요청 중이며 공유 잠금을 보유하기에 배타 잠금을 얻을 수 없는 데드락이 발생합니다.
📝해결 방안
지금까지 왜 교착상태가 발생했는지 설명했습니다. 이제 해결 방법을 알아봅시다.
일단 3가지 방법을 생각해보았습니다.
- 파티에서 파티 인원 수 제거 후 파티인원 테이블에서 조회하기
- Synchronized를 이용하기
- 낙관적 락 사용하기
- 비관적 락 사용하기
📌파티에서 파티 인원 수 제거 후 파티인원 테이블에서 조회하기 실패
해당 방법은 일단 테이블을 바꾸고 서브쿼리를 이용해서 파티 인원 수를 추가해주는 작업이였습니다.
해당 방법을 사용하지 않은 이유는 2가지입니다.
- 파티의 인원 수는 우리 어플에서 많이 조회되는 내역이기에 서브 쿼리로 조회 시 너무 많은 오버헤드를 가져갑니다.
- 이미 만들어진 서비스에서 테이블을 바꾸고 쿼리 또한 수정하는 작업 자체가 거부감이 들었습니다.
📌Synchronized를 이용하기 보류
synchronized는 자바에서 지원하는 동시성을 제어하기 위한 키워드로 메서드에 사용될 수 있고, 블록을 지정해서 사용할 수 있습니다.
저는 이 중에서 메서드에 사용하였습니다.
@PostMapping("/{id}")
@Operation(summary = "파티 가입", description = "주어진 ID의 파티에 가입합니다.")
public synchronized ResponseEntity<?> joinParty(@PathVariable Long id,
@AuthenticationPrincipal AuthMember authMember) {
pmListService.createJoinParty(PartyRole.USER, authMember.getId(), id);
return ResponseEntity.ok().body(ResponseDto.of("파티 가입 성공", id));
}
우선 이렇게 바꾸고 사용하였습니다.
Controller에 사용하는 이유는 다음과 같습니다.
- Serivce 코드는 @Transactional이 붙어있기에 AOP 후처리로 인해 제대로 동시성이 지켜지지 않을 수 있습니다.
하지만 synchronized를 사용하지 않는 이유가 있습니다.
- 동시성 제어는 일반적으로 서비스 레벨에서 처리하는 것이 좋습니다. 컨트롤러는 클라이언트의 요청을 처리하는 역할만 맡는 것이 맞는 것 같습니다.
- synchronized를 컨트롤러에 직접 사용하는 경우 확장성에 문제가 생길 수 있습니다.
- 예를 들어 다른 서비스와의 상호작용이나 이벤트 처리가 필요한 경우 컨트롤러 동시성 제어는 불가능합니다.
📌낙관적 락 사용하기 보류
낙관적 락은 테이블에서 추가적인 버전 컬럼을 사용하여 관리합니다.
애플리케이션 수준에서 UPDATE, DELETE 시 WHERE 절에 이전에 조회했을 때 버전과 일치하는지 여부를 조건 문에 추가하는 방식입니다.
UPDATE party
SET pepleCount = 2 AND version = 2
WHERE id = 1
AND version = 1;
처음에 했던 예제에 낙관적 락을 추가해서 한번 테스트해봅시다.
public class Party {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
...
@Version // 낙관적 락을 위한 버전 필드 추가
private int version;
private boolean isClosed;
2025-01-03T18:27:20.837+09:00 WARN 7324 --- [ Thread-4] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1213, SQLState: 40001
2025-01-03T18:27:20.837+09:00 WARN 7324 --- [ Thread-5] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1213, SQLState: 40001
2025-01-03T18:27:20.838+09:00 ERROR 7324 --- [ Thread-4] o.h.engine.jdbc.spi.SqlExceptionHelper : Deadlock found when trying to get lock; try restarting transaction
2025-01-03T18:27:20.838+09:00 WARN 7324 --- [ Thread-3] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1213, SQLState: 40001
2025-01-03T18:27:20.838+09:00 ERROR 7324 --- [ Thread-3] o.h.engine.jdbc.spi.SqlExceptionHelper : Deadlock found when trying to get lock; try restarting transaction
2025-01-03T18:27:20.839+09:00 ERROR 7324 --- [ Thread-5] o.h.engine.jdbc.spi.SqlExceptionHelper : Deadlock found when trying to get lock; try restarting transaction
결과는 똑같이 데드락이 발생했습니다.
낙관적 락은 데드락에 효과적이지만 일반적으로 경쟁 상태를 최소화하고 충돌이 발생했을 때만 처리하는 방식입니다.
그렇기에 데드락이 발생할 수 있습니다.
이는 트랜잭션 격리 수준, 외래키 유무에 따라 달라질 수 있습니다.
낙관적 락이 데드락을 방지하는 법
- 트랜잭션 격리 수준을 READ COMMITTED로 바꾼다.
- 외래키 제약 조건을 제거한다.
📌비관적 락 사용하기 성공
마지막 방법은 비관적 락을 사용하는 방법입니다.
이 방식은 충돌이 자주 일어나는 상황을 가정하는 방식이기에
DB에서 원하는 record에 배타 잠금을 걸어서 다른 스레드에서 내가 이후 수정하고자 하는 record에 대해 접근할 수 없게 합니다.
PartyRepository
@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("select p from Party p where p.id = :id")
Optional<Party> findByIdPessimisticLock(Long id);
PmListSerivce
@Transactional
public void createJoinParty(PartyRole partyRole, Long memberId, Long partyId) {
Party party = partyService.findByIdPessimisticLock(partyId);
Member member = memberService.findById(memberId);
if (pmListRepository.existsByPartyAndMember(party, member)) {
throw new CustomException(PartyErrorCode.ALREADY_JOINED);
}
party.joinParty(); // 파티 인원 수 증가
PMList pmList = PMList.builder()
.party(party)
.member(member)
.role(partyRole)
.build();
pmListRepository.save(pmList); // 파티 멤버 리스트에 저장
}
성공하였습니다.
비관적 락을 이용해서 여러 사용자에 대한 동일 파티 가입에 대한 트랜잭션 교착 상태를 해결 가능하였습니다.
하지만 비관적 락은 배타 잠금을 이용해서 데이터 접근을 차단하기 때문에 동시성 효율이 떨어집니다.
그렇기에 꼭 중요한 칼럼에 사용해야 합니다. 만약 게시글의 조회수같은 경우 사실 굳이 정확한 정보가 필요한게 아니므로 비관적락은 피하는게 좋습니다.
저의 프로젝트의 경우 파티 인원 수가 매우 중요하기에 비관적 락이 효율이 좋습니다.
🧷추가적인 고려 사항
비관적 락의 성능 저하
비관적 락도 배타 잠금을 사용하기에 성능이 저하됩니다.
그렇기에 만약 향후 트래픽이 급증하면 성능 문제의 체감이 커질 것입니다. 그래서 Redis 같은 외부 캐시 시스템을 활용하거나 할 수 있습니다.
서비스 확장 면에서
서비스 확장면에서 비관적 락을 전파하는 방법도 있습니다. Redis 분산 락을 이용하면 여러 인스턴스에서 실행되는 서비스나 마이크로서비스 환경에서 데이터의 동시성 문제 해결에 유용합니다.
'Project > UniP' 카테고리의 다른 글
[UniP] Real MySQL로 배우는 무한 페이징 & 복합 인덱스 설계 전략 (0) | 2025.01.01 |
---|---|
[UniP]무한 페이징 기능 구현 및 성능 개선 (0) | 2024.11.16 |
[UniP] 인증 메일 발송 비동기 처리하기 (1) | 2024.11.11 |
[UniP]QueryDSL로 조회 최적화하기 (0) | 2024.11.07 |
[UniP]Redis를 통한 RefreshToken 관리하기 (0) | 2024.11.06 |