OpenRun Project - 비관적 락 적용해서 동시성 문제 해결 하기

Ango·2023년 8월 11일
0

Project

목록 보기
14/16

비관적 락 적용 전

<유저 50명 >

50개 요청중 47개 성공 (Error : 6%)

초기 재고 624

주문 후 579

재고 45개 빠짐 ⇒ 동시성 문제로 예상 됨

비관적 락 적용 후

@Lock(LockModeType.PESSIMISTIC_WRITE)
Optional<Product> findWithLockById(Long productId);
@Transactional
public void postOrders(Long productId, OrderRequestDto orderRequestDto, Member member) {

    Product product = productRepository.findWithLockById(productId).orElseThrow(
      () -> new ResponseStatusException(NOT_FOUND_DATA.getStatus(), NOT_FOUND_DATA.formatMessage("상품"))
    );

     Order order = Order.builder()
             .member(member)
             .product(product)
             .count(orderRequestDto.count())
             .totalPrice(product.getPrice() * orderRequestDto.count())
             .build();

     product.decreaseQuantity(orderRequestDto.count());

     orderRepository.save(order);

}

<유저 200명 >

상품 재고 정확히 업데이트 된 것 확인 .

초당 처리량인 Throughput이 87.9%가 나왔는데 더 많은 유저에 대한 테스트를 거친 후 목표치를 설정하는 것이 중요해 보임.

알게된 점

Lock은 Transaction이 끝날때 까지 유지됨. 그러므로 해당 상품을 조회하고 업데이트 하는 부분(상품 count 수만 큼 재고 -)을 완전히 마친 후 다음 락을 풀어줌. => 동시성 문제를 해결 할 수 있었던 이유

% 주문취소, 관심상품 등록 및 취소에 대한 부분도 동시성 문제를 해결함.

profile
웹 벡엔드 개발자가 되어보자!

0개의 댓글

관련 채용 정보