Skip to content

공동구매 정산 (Redis 스냅샷으로 마감, 참여 대조) - #47

Merged
KimMonkey2945 merged 6 commits into
mainfrom
feature/45
Nov 26, 2026
Merged

KimMonkey2945 merged 6 commits into
mainfrom
feature/45

Conversation

@KimMonkey2945

Copy link
Copy Markdown
Collaborator

close #45

작업 내용

  • 정산 스냅샷 Lua (no-writes): status·인원·단가·참여자를 한 시점에 읽음, meta가 없으면 빈 결과
  • SettlementSnapshot, findSettlementSnapshot (meta 없으면 Optional.empty())
  • GroupPurchaseRepository.closeOpen: WHERE status = 'OPEN' 조건부 UPDATE로 CLOSED + final_headcount·final_price·closed_at (멱등, 서버 여러 대여도 한 번만 반영)
  • ParticipationRepository.findJoinedMemberIds, cancelJoinedMembers (IN 벌크 UPDATE)
  • 정산 쿼리는 Propagation.MANDATORY: 마감과 대조가 반드시 한 트랜잭션에서만 실행되게 강제
  • GroupPurchaseSettlementService.settle
    • Redis status가 OPEN이면 건너뜀 (마감 판단을 Redis 시계 기준으로)
    • Redis 기준 마감 + 대조: DB에만 JOINED → CANCELED(warn), Redis에만 있음 → error 로그
    • Redis 키가 없으면 마감 시각이 지난 경우만 DB JOINED 수 + DiscountPolicy로 마감
    • DB 단계는 TransactionTemplate (Redis 읽기는 트랜잭션 밖)
  • GroupPurchase.discountPolicy() 추가
  • 정산 트리거(스케줄러, 정원 참 즉시 정산)는 다음 PR

테스트

  • 정상 마감(Redis 인원·단가 반영, 참여 유지), 대조(DB만 JOINED 정리·Redis만 있는 참여자 인원 포함), Redis OPEN이면 건너뜀, Redis 키 없을 때 DB 기준 마감

@KimMonkey2945 KimMonkey2945 self-assigned this Nov 18, 2026
@coderabbitai

coderabbitai Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

Important

  • Trigger review

This repository does not receive automatic reviews because it has fewer than 10 stars.

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 31ece287-1256-4563-93b1-d0cb831bb96a
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

private void settleWithRedis(Long groupPurchaseId, SettlementSnapshot snapshot, LocalDateTime now) {
if (snapshot.open()) {
return;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

정원이 차서 CLOSED 가 되면 바로 정산될 수 있어요. 그런데 마지막 참여자의 DB 저장이 실패하면 rollbackJoin 이 Redis 를 다시 OPEN 으로 바꿔요. 그러면 DB 는 CLOSED 인데 Redis 에서는 새 참여가 받아져요. 정원 즉시 정산을 붙일 때 이 순서를 어떻게 막을지 정해야 할 것 같아요.

@KimMonkey2945 KimMonkey2945 Nov 21, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

정산 트리거 PR에서 정원 즉시 정산은 마지막 참여자의 DB 저장이 성공한 뒤에만 실행하도록 했습니다. 저장이 실패하면 rollbackJoin으로 Redis를 되돌린 뒤 예외를 던져 정산까지 가지 않기 때문에, 마지막 참여자 본인의 저장 실패로는 말씀해 주신 순서가 생기지 않습니다. 다른 참여자의 저장이 진행 중일 때 마지막 참여자가 정산하고, 그 뒤 진행 중이던 저장이 실패하면 rollbackJoin이 CLOSED이면서 정원 미만인 것을 보고 OPEN으로 되돌려 같은 문제가 생깁니다. Redis에서는 정원이 찬 상태와 정산이 끝난 상태가 같은 CLOSED라 rollbackJoin이 구분하지 못하기 때문입니다. 정산 트리거 PR 리뷰에서 정리한 대로, 정산할 때 Redis meta에 정산 완료를 표시해 rollbackJoin이 그 표시를 보면 값을 바꾸지 않게 하고, 즉시 정산은 DB의 JOINED 수가 정원 이상일 때만 실행하도록 고치겠습니다.

if (!redisOnly.isEmpty()) {
log.error("정산 대조: DB에 참여 기록이 없는 Redis 참여자가 있음. groupPurchaseId={}, memberIds={}",
groupPurchaseId, redisOnly);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

마감 직전에 Redis 참여는 됐는데 DB INSERT 가 아직 안 끝난 정상 요청도 여기로 와요. 그러면 error 로그가 오탐이 돼요. 트리거를 붙일 때 마감 후 조금 기다렸다가 정산하면 어떨까요?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

마감 시각 스케줄러는 closeAt이 "지금 − 유예 시간"보다 이전인 공동구매만 정산하도록 threshold를 넘기고 있어서, 마감 직전 참여의 DB 저장이 끝날 시간을 두고 있습니다. 다만 정원이 차는 순간의 즉시 정산은 마지막 참여자의 저장 직후 바로 실행돼서, 거의 동시에 Lua를 통과한 다른 참여자의 INSERT가 아직 끝나지 않았다면 말씀해 주신 대로 정상 요청이 ERROR 로그로 잡힐 수 있습니다. Redis는 정원이 차는 순간 이미 CLOSED라 더 이상 참여를 받지 않으므로, 즉시 정산도 바로 실행하지 않고 유예 시간 뒤에 처리하도록 바꿔 오탐을 없애겠습니다.

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.*;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

java.util.* 대신 import 를 하나씩 쓰면 좋겠어요.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IntelliJ가 같은 패키지에서 5개 이상 import하면 자동으로 *로 합치는 설정 때문에 생긴 것 같습니다. 어떤 클래스를 쓰는지 바로 보이고 이름 충돌도 피할 수 있도록 하나씩 import하도록 고치고, 다시 합쳐지지 않게 IDE의 와일드카드 import 기준도 바꿔 두겠습니다.

if (snapshot.open()) {
return;
}
transactionTemplate.executeWithoutResult(status -> {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@transactional 을 붙인 private 메서드로 만들지 않고 TransactionTemplate 을 쓴 이유는 뭔가요? 같은 클래스 안에서 @transactional 메서드를 호출하면 어떻게 되나요?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@transactional은 스프링이 만든 프록시가 호출을 가로채 트랜잭션을 여는 방식이라, 같은 클래스 안에서 this로 호출하면 프록시를 거치지 않아 어노테이션이 무시됩니다. private 메서드는 프록시가 오버라이드할 수 없어 어디서 부르든 적용되지 않습니다. 이 코드에서 그렇게 했다면 트랜잭션 없이 closeOpen이 호출되고, closeOpen이 MANDATORY라서 바로 예외가 났을 것입니다.
TransactionTemplate은 프록시에 의존하지 않아 자기 호출 문제가 없고, 같은 메서드 안에서 Redis 스냅샷 읽기는 트랜잭션 밖에, 마감과 대조만 트랜잭션 안에 두도록 범위를 정확히 나눌 수 있어서 선택했습니다. 별도 빈으로 분리하는 방법도 있지만 클래스가 늘고 흐름이 두 파일로 나뉘어, 트랜잭션의 시작과 끝이 코드에 그대로 보이는 TransactionTemplate이 더 맞다고 판단했습니다.


public interface GroupPurchaseRepository extends JpaRepository<GroupPurchase, Long> {

@Transactional(propagation = Propagation.MANDATORY)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

기본값인 REQUIRED 와 MANDATORY 는 트랜잭션 없이 호출될 때 각각 어떻게 동작하나요? 여기서 MANDATORY 를 고른 이유는 뭔가요?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

REQUIRED는 바깥 트랜잭션이 있으면 합류하고 없으면 새로 만들어 실행하고, MANDATORY는 바깥 트랜잭션이 있으면 합류하지만 없으면 예외를 던집니다.
closeOpen은 정산에서 참여 대조와 같은 트랜잭션으로 묶여야 해서 MANDATORY를 골랐습니다. 같은 트랜잭션이면 대조가 실패할 때 마감도 롤백돼 공동구매가 OPEN으로 남고, 다음 스케줄러 주기에 다시 정산됩니다. 그런데 REQUIRED라면 나중에 누군가 트랜잭션 없이 closeOpen을 호출해도 혼자 새 트랜잭션으로 커밋되어, 대조가 실패하면 CLOSED로 확정된 채 남고 status = 'OPEN' 조건 때문에 다시 정산할 기회도 사라집니다. MANDATORY는 이런 잘못된 호출을 에러 없이 넘기지 않고 바로 예외로 드러냅니다. 반면 판매자 취소의 cancelOpen은 UPDATE 하나로 완결되는 작업이라 혼자 실행돼도 괜찮아서 기본값인 REQUIRED를 썼습니다.

g.closedAt = :now,
g.updatedAt = :now
where g.id = :groupPurchaseId
and g.status = com.ttuk.grouppurchase.GroupPurchaseStatus.OPEN

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

서버 두 대가 같은 공동구매를 동시에 정산하면 어떻게 되나요? 이 조건이 없으면요?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

두 서버가 동시에 정산하면 먼저 UPDATE를 실행한 쪽이 공동구매 행에 배타 잠금을 걸고 CLOSED로 바꾸며, 뒤의 서버는 잠금을 기다렸다가 최신 커밋 데이터로 조건을 다시 판단해 status가 이미 CLOSED라 0행이 됩니다. 0행이면 바로 반환하고, 참여 대조도 closeOpen이 1행일 때만 같은 트랜잭션에서 실행해서 정산과 대조는 한 번만 일어납니다.
status = 'OPEN' 조건이 없으면 두 서버 모두 UPDATE에 성공해 정산이 두 번 처리되고, closed_at이나 최종 인원·단가가 나중 서버의 값으로 덮어써질 수 있습니다. 한쪽은 Redis 스냅샷, 다른 쪽은 DB 기준으로 계산했다면 다른 값이 남을 수도 있습니다. 나중에 정산에 알림이나 결제를 붙이면 두 번 실행되는 문제도 생깁니다. 무엇보다 판매자가 이미 취소한 CANCELED 공동구매도 CLOSED로 덮어쓰게 되는데, 판매자 취소도 같은 조건을 써서 마감과 취소가 동시에 와도 먼저 바꾼 쪽만 반영되도록 했습니다.

groupPurchaseId, dbOnly, canceled);
}

Set<Long> joined = new HashSet<>(joinedMemberIds);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

List 를 HashSet 으로 바꾼 뒤 contains 를 쓴 이유는 뭔가요?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Redis 참여자마다 DB 참여자 목록에 있는지 확인하는데, List의 contains는 찾을 때마다 목록을 처음부터 하나씩 비교하고, HashSet의 contains는 해시값으로 위치를 계산해 바로 확인합니다. 확인을 참여자 수만큼 반복하기 때문에, List로 하면 참여자가 늘수록 비교 횟수가 크게 늘어나서 DB 참여자 목록을 한 번 HashSet으로 바꾼 뒤 확인하도록 했습니다. 앞의 반복문은 찾는 대상인 Redis 참여자가 이미 Set이라 그대로 두었습니다.

LocalDateTime now = LocalDateTime.now(clock);

Optional<SettlementSnapshot> snapshot =
groupPurchaseRedisRepository.findSettlementSnapshot(groupPurchaseId);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Redis 스냅샷 읽기를 transactionTemplate 안으로 옮기면 무엇이 나빠지나요?

@KimMonkey2945 KimMonkey2945 Nov 21, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Redis를 읽는 동안에도 DB 커넥션을 쥐고 기다리게 되는데, 그렇게 해서 얻는 건 없다고 생각합니다. 정상일 때는 차이가 작지만 Redis가 느려지거나 장애가 나면 그 시간만큼 커넥션이 묶여, 정산 스케줄러가 여러 공동구매를 처리할 때 커넥션 풀이 바닥나고 다른 API까지 영향을 받을 수 있습니다. 트랜잭션도 길어져 closeOpen이 거는 잠금을 오래 쥐고 있을 위험이 커집니다. 그리고 Redis 읽기는 트랜잭션 안에 넣어도 DB 트랜잭션의 일부가 되지 않아 원자성이나 일관성 이득이 없습니다.

# Conflicts:
#	src/main/java/com/ttuk/grouppurchase/redis/GroupPurchaseRedisRepository.java
#	src/main/java/com/ttuk/participation/ParticipationRepository.java
# Conflicts:
#	src/main/java/com/ttuk/participation/ParticipationRepository.java
@sonarqubecloud

Copy link
Copy Markdown

Quality Gate Failed Quality Gate failed

Failed conditions
3.5% Duplication on New Code (required ≤ 3%)

See analysis details on SonarQube Cloud

@KimMonkey2945
KimMonkey2945 changed the base branch from feature/42 to main November 26, 2026 10:30
@KimMonkey2945
KimMonkey2945 merged commit 5f344b8 into main Nov 26, 2026
2 of 3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

공동구매 정산

2 participants