
마이크로서비스 환경에서 주문 처리 시스템을 개발 중, 다음과 같은 데드락이 발생하는 상황
// Transaction A
@Transactional
public void updateInventory(Long productId, int quantity) {
// 1. product 테이블 락 획득
productRepository.findByIdForUpdate(productId);
// 2. inventory 테이블 락 시도
inventoryRepository.updateQuantity(productId, quantity);
}
// Transaction B (동시 실행)
@Transactional
public void updateProductPrice(Long productId, BigDecimal price) {
// 1. inventory 테이블 락 획득
inventoryRepository.findByProductIdForUpdate(productId);
// 2. product 테이블 락 시도
productRepository.updatePrice(productId, price);
}
@Transactional
public void updateInventoryAndProduct(Long productId, int quantity, BigDecimal price) {
// 항상 product 테이블 -> inventory 테이블 순서로 락 획득
productRepository.findByIdForUpdate(productId);
inventoryRepository.findByProductIdForUpdate(productId);
// 실제 업데이트 수행
if (quantity != 0) {
inventoryRepository.updateQuantity(productId, quantity);
}
if (price != null) {
productRepository.updatePrice(productId, price);
}
}