Skip to content

#35 공동구매 참여 API 구현 - #38

Merged
KimMonkey2945 merged 4 commits into
mainfrom
feature/35
Nov 26, 2026
Merged

KimMonkey2945 merged 4 commits into
mainfrom
feature/35

Conversation

@KimMonkey2945

Copy link
Copy Markdown
Collaborator

close #35

작업 내용

  • POST /api/group-purchases/{id}/participants (구매자 전용, quantity 1~10)
  • participation 엔티티 추가 (인덱스는 조회 API PR에서 EXPLAIN 후 추가)
  • Redis Lua 먼저 → 성공한 경우만 DB INSERT (몰릴 때 실패 요청이 DB로 가지 않음)
  • FK는 getReferenceById로 넣어 INSERT 한 번만, Lua 호출 중 DB 커넥션을 잡지 않도록 서비스에 트랜잭션 없음
  • 결과별 409: GROUP_PURCHASE_NOT_OPEN / GROUP_PURCHASE_FULL / ALREADY_JOINED, Redis 미초기화 + DB에 없으면 404

알려진 임시 상태 (다음 PR에서 처리)

  • 등록은 됐지만 Redis 초기화가 실패한 공동구매는 500 → lazy init
  • Redis 참여 성공 후 DB 저장 실패 시 Redis가 되돌려지지 않음 → 보상 처리

테스트

  • 201·DB 저장값, Lua 거절 시 409(대표: ALREADY_JOINED)·DB 미저장, Redis·DB 모두 없으면 404, 판매자 403

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

coderabbitai Bot commented Nov 13, 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: 56d04852-ce51-4dff-934f-d0b398ff4686
  • 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

if (!groupPurchaseRepository.existsById(groupPurchaseId)) {
return new BusinessException(ErrorCode.GROUP_PURCHASE_NOT_FOUND);
}
return new IllegalStateException("Redis가 초기화되지 않은 공동구매입니다. id=" + 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.

meta 키는 마감 하루 뒤에 만료돼요. 그래서 오래전에 마감된 공동구매에 참여를 요청하면 NOT_INITIALIZED 가 오고, 여기서 500 이 나요. 지금 원인이 Redis 초기화 실패인지 이미 마감된 것인지 구분하지 않아서 생기는 문제예요. DB 의 마감 시각과 상태를 보고, 마감됐으면 409 GROUP_PURCHASE_NOT_OPEN 을 돌려주면 좋겠어요

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(#36 lazy init·보상)에서 반영했습니다. NOT_INITIALIZED가 오면 DB에서 공동구매를 조회해, 없으면 404, 상태가 OPEN이 아니거나 마감 시각이 지났으면 409 GROUP_PURCHASE_NOT_OPEN을 돌려주도록 했습니다. 그래서 meta가 만료된 오래전 마감 공동구매나 판매자가 취소한 공동구매는 409로 응답하고, 참여 가능한 상태인데 Redis 키만 없는 경우에는 키를 다시 만든 뒤 참여를 재시도합니다.

@Entity
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class Participation extends BaseTimeEntity {

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 의 SISMEMBER 로만 막고 있어요. 다음 PR의 lazy init 이나 보상 처리로 Redis 값이 다시 만들어지면, 같은 회원의 참여 행이 DB 에 두 번 들어갈 수 있어요. (group_purchase_id, member_id) 유니크 제약을 마지막 방어선으로 두면 좋겠어요. 취소 후 재참여를 허용할 계획이라면, 그때 이 제약을 어떻게 할지도 함께 정해 주세요.

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의 SISMEMBER로만 막고 있어서, Redis 키가 사라진 뒤 lazy init으로 참여자 Set이 비어 있는 채로 다시 만들어지면 같은 회원의 JOINED 행이 DB에 두 번 들어갈 수 있습니다. 그래서 DB에도 마지막 방어선이 필요하다고 생각합니다.
다만 취소는 행을 지우지 않고 CANCELED로 바꾸고 재참여는 새 행을 만드는 구조라, (group_purchase_id, member_id)에 단순 유니크 제약을 걸면 재참여가 막힙니다. 막아야 하는 건 같은 회원의 JOINED 행이 두 개가 되는 경우라서, status가 JOINED일 때만 member_id 값을 갖고 그 외에는 NULL인 생성 컬럼을 두고 (group_purchase_id, 이 컬럼)에 유니크 제약을 걸려고 합니다. MySQL 유니크 인덱스는 NULL끼리 중복으로 보지 않아 취소 기록은 여러 개 남길 수 있고, JOINED 행만 하나로 제한됩니다. 제약에 걸리면 지금은 500이 나가서, 제약 위반을 잡아 ALREADY_JOINED로 응답하도록 함께 처리하겠습니다.

@NotNull
@Min(1)
@Max(10)
Integer quantity

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

수량을 1~10개로 받는데, 할인 단계는 수량이 아니라 참여 인원으로만 계산돼요. 그래서 10개를 사는 사람도 인원 1명으로 세져요. 의도가 맞는지 확인해 주세요.

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.

네, 의도한 동작입니다. 이 서비스는 사람이 많이 모일수록 가격이 내려가는 공동구매라서, 할인 단계와 정원은 모두 참여한 사람 수로 계산하도록 명세에서 정했습니다. 수량으로 세면 한 명이 여러 개를 사서 혼자 할인 단계를 올릴 수 있어, 사람을 모으는 공동구매의 의미가 사라진다고 판단했습니다. 수량은 할인 계산에는 쓰지 않고, 정산 때 수량 × 확정 단가로 결제 금액을 계산하는 데만 사용합니다.


private ParticipationCreateResponse saveParticipation(Long groupPurchaseId, Long memberId,
int quantity, JoinResult result) {
participationRepository.save(Participation.builder()

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 에만 참여가 남아요. 적어도 그동안은 예외를 잡아 공동구매 id 와 회원 id 를 에러 로그로 남겨 주세요.

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(#36 lazy init·보상)에서 보상 처리와 함께 반영했습니다. DB 저장이 실패하면 예외를 잡아 rollbackJoin으로 Redis의 참여를 되돌리고, 되돌릴 참여가 없으면 공동구매 id와 회원 id를 WARN 로그로, 되돌리기 자체가 실패하면 두 id를 담아 ERROR 로그로 남기며 되돌리기 실패 예외를 원래 예외에 suppressed로 붙여 함께 던지도록 했습니다. PR을 기능 단위로 나누다 보니 이 PR만 보면 저장 실패 시 Redis에만 참여가 남는 구간이 있는데, 두 PR이 순서대로 함께 머지될 예정이라 그대로 두었습니다.

@SpringBootTest
@AutoConfigureMockMvc
@Import(TestcontainersConfig.class)
class ParticipationIntegrationTest {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

이 PR의 핵심은 동시에 몰려도 정원을 넘지 않는 거예요. 그런데 동시 요청 테스트가 없어요.

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에 넣지 않고 다음 PR(#37 동시성 테스트)로 분리했습니다. 참여 기능을 Lua → API → lazy init·보상 → 동시성 테스트 순서로 나눠 PR 크기를 맞추다 보니, 정원 초과를 막는 동시 요청 검증은 기능이 모두 붙은 뒤 한 번에 확인하도록 마지막 PR에 두었습니다.

private ParticipationStatus status;

@Column(nullable = false)
private LocalDateTime joinedAt;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

BaseTimeEntity 의 createdAt 과 joinedAt 이 사실상 같은 값이에요. 두 값이 달라질 수 있는 경우가 없다면 하나만 써도 돼요.

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.

말씀해 주신 대로 지금은 joinedAt을 저장 직전에 같은 Clock으로 넣고, createdAt은 저장 시점에 Auditing이 넣어서 값은 사실상 같습니다. 다만 createdAt은 행이 DB에 만들어진 시각을 남기는 감사용 값이고, joinedAt은 회원이 참여한 시각이라는 비즈니스 값이라 의미가 다르다고 생각했습니다. 지금은 행을 만드는 순간이 곧 참여한 순간이라 같지만, 나중에 데이터를 이관하거나 참여 행을 뒤늦게 보정해 만드는 경우가 생기면 두 값이 갈라질 수 있습니다.
그래서 참여 시각이 Auditing 같은 인프라 값에 기대지 않도록 joinedAt을 따로 두었고, 이미 canceledAt을 비즈니스 시각으로 따로 두고 있어 joinedAt과 짝을 맞추는 것이 일관적이라고 판단했습니다.


private ParticipationCreateResponse saveParticipation(Long groupPurchaseId, Long memberId,
int quantity, JoinResult result) {
participationRepository.save(Participation.builder()

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 는 하나의 트랜잭션으로 묶을 수 없어요. 그래서 둘 중 하나만 성공하면 데이터가 어긋나요. 보상 처리와 아웃박스 패턴은 이 문제를 각각 어떻게 풀까요?

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 Lua로 먼저 참여시키고 DB 저장이 실패하면 rollbackJoin으로 Redis의 인원과 참여자를 되돌립니다. 요청 안에서 바로 맞춰지는 대신 되돌리기도 실패할 수 있어서, 그 경우는 로그를 남기고 정산 때 Redis 참여자 Set과 DB JOINED 참여를 대조해 정리하도록 했습니다.
아웃박스는 첫 작업과 함께 "해야 할 두 번째 작업"을 같은 DB 트랜잭션에 메모처럼 저장해 두고, 스케줄러가 나중에 그 메모를 보고 실행하는 방식입니다. 실행에 실패하면 메모가 남아 있어 다시 시도하기 때문에 할 일이 사라지지 않습니다. 대신 실행은 성공했는데 완료 표시 전에 앱이 꺼지면 같은 작업이 한 번 더 실행될 수 있어서, 받는 쪽은 같은 요청이 두 번 와도 한 번만 처리되도록 만들어야 합니다. 알림이라면 같은 알림을 같은 회원에게 두 번 저장하지 못하도록 유니크 제약을 거는 방식입니다.
참여는 정원과 중복 여부를 Redis Lua가 판단해 요청 안에서 바로 결과를 정해야 해서, DB에 먼저 저장하고 Redis를 나중에 반영하는 아웃박스로는 선착순 판단을 할 수 없습니다. 그래서 참여·취소는 보상 처리와 정산 시 대조로, 결과에 영향을 주지 않고 늦어도 반드시 보내져야 하는 새 공동구매 알림은 아웃박스로 처리하도록 나눴습니다.

@sonarqubecloud

Copy link
Copy Markdown

@KimMonkey2945
KimMonkey2945 changed the base branch from feature/33 to main November 26, 2026 10:27
@KimMonkey2945
KimMonkey2945 merged commit b5bc318 into main Nov 26, 2026
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.

공동구매 참여 API

2 participants