Skip to content

feat: add Idempotency-Key guard to prevent duplicate AI problem generation - #61

Merged
Junkov0 merged 4 commits into
developfrom
feature/problem-refactor
Aug 7, 2026
Merged

Junkov0 merged 4 commits into
developfrom
feature/problem-refactor

Conversation

@Junkov0

@Junkov0 Junkov0 commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator

작업 내용

문제 생성 / AI 문제 생성 API에 Idempotency-Key 기반 중복 요청 차단 추가.

변경 사항

  • 분산 환경(멀티 인스턴스) 전환 검토 중, POST /api/spaces/{spaceId}/problems/ai, POST /api/rooms/{roomId}/problems/ai 두 엔드포인트에 요청 식별자가 없어서 더블클릭/네트워크 재시도 시 AI API 중복 호출 및 문제 중복 저장이 가능한 상태였음.
  • 클라이언트가 보내는 Idempotency-Key 헤더(UUID)를 Redis setIfAbsent (TTL 10분)로 잠궈서, 같은 키로 들어온 재요청은 409 CONFLICT(DUPLICATE_AI_REQUEST)로 차단.
  • AI 생성/저장 도중 예외 발생 시엔 락을 즉시 해제해서 정상 재시도까지 막지 않도록 처리.
  • ProblemErrorCode, RoomProblemErrorCodeDUPLICATE_AI_REQUEST 에러코드 추가 (기존 GlobalExceptionHandlerErrorCode.getHttpStatus()로 범용 매핑하므로 핸들러 수정은 불필요).

체크리스트

  • 테스트 코드 작성 완료
  • 리뷰어 지정 완료

참고 사항

  • 프론트엔드에서 Idempotency-Key 헤더 미전송 시 모든 AI 생성 요청이 400으로 막힘 — 프론트 연동 별도 필요 (미착수).
  • 상세 트러블슈팅/설계 검토 내용: D:\project\문서\MoMoGo_문서\ai-problem-generation-idempotency-key.md

관련 이슈

Summary by CodeRabbit

  • 개선 사항

    • AI 문제 자동 생성 요청에 중복 방지 기능이 적용되었습니다.
    • 문제 및 방 단위의 AI 생성 요청은 고유한 Idempotency-Key를 사용합니다.
    • 동일한 요청이 처리 중이면 중복 생성을 방지하고 충돌 오류를 안내합니다.
    • 처리 중 오류가 발생한 경우 다시 시도할 수 있도록 상태가 정리됩니다.
  • 오류 처리

    • 이미 처리 중인 AI 요청에 대해 명확한 충돌 응답과 재시도 안내 메시지를 제공합니다.

…ation

Multi-instance migration exposes duplicate AI-generation requests
(double-click, network retry landing on a different instance) since
there was no way to detect a resubmitted request. Use Redis SETNX
with a 10min TTL, scoped per request, to reject retries while the
original is still in flight.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Aug 6, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@Junkov0, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 55 minutes

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 9e728725-47a2-4586-9a28-2426931bd8fa

📥 Commits

Reviewing files that changed from the base of the PR and between 18376e8 and e2b76c9.

📒 Files selected for processing (1)
  • momogo-frontend/src/pages/SpacePage.tsx
📝 Walkthrough

Walkthrough

AI 문제 생성 API가 필수 Idempotency-Key UUID 헤더를 받도록 변경되었습니다. 서비스는 Redis의 10분 TTL 잠금으로 동일한 진행 중 요청을 차단하고, 중복 요청에는 409 CONFLICT 오류를 반환합니다.

Changes

AI 문제 생성 멱등성

Layer / File(s) Summary
멱등성 키 API 계약
momogo-api/src/main/java/com/momogo/api/problem/ProblemController.java, momogo-api/src/main/java/com/momogo/api/room/RoomProblemController.java, momogo-core/src/main/java/com/momogo/core/domain/problem/service/ProblemService.java, momogo-core/src/main/java/com/momogo/core/domain/room/service/RoomProblemService.java
두 AI 문제 생성 엔드포인트가 필수 Idempotency-Key UUID 헤더를 받고 서비스 호출에 전달합니다. 서비스 메서드 시그니처가 변경되었습니다.
문제 생성 중복 잠금
momogo-core/src/main/java/com/momogo/core/domain/problem/exception/ProblemErrorCode.java, momogo-core/src/main/java/com/momogo/core/domain/problem/service/ProblemServiceImpl.java
ProblemServiceImpl이 Redis에 10분 TTL 잠금을 설정합니다. 동일 키가 있으면 DUPLICATE_AI_REQUEST를 발생시키며, 런타임 예외 발생 시 잠금을 삭제합니다.
방 문제 생성 중복 잠금
momogo-core/src/main/java/com/momogo/core/domain/room/exception/RoomProblemErrorCode.java, momogo-core/src/main/java/com/momogo/core/domain/room/service/RoomProblemServiceImpl.java
RoomProblemServiceImpl이 Redis에 10분 TTL 잠금을 설정합니다. 동일 키가 있으면 DUPLICATE_AI_REQUEST를 발생시키며, 런타임 예외 발생 시 잠금을 삭제합니다. 기존 문제 수정과 검증 로직은 유지됩니다.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant Controller
  participant Service
  participant Redis
  participant AI Generator
  Client->>Controller: Idempotency-Key 및 AI 문제 생성 요청
  Controller->>Service: idempotencyKey와 요청 데이터 전달
  Service->>Redis: 10분 TTL 잠금 설정
  Service->>AI Generator: 문제 생성 요청
  AI Generator-->>Service: 생성된 문제 반환
  Service->>Redis: 처리 실패 시 잠금 삭제
  Service-->>Controller: 생성 결과 또는 중복 요청 오류
Loading

Possibly related PRs

  • MoMoGo-QuizPlatform/MoMoGo#21: AI 문제 생성 엔드포인트와 ProblemService 흐름을 추가했으며, 본 변경이 해당 메서드에 멱등성 처리를 확장합니다.
  • MoMoGo-QuizPlatform/MoMoGo#24: 방 문제 AI 생성 흐름을 추가했으며, 본 변경이 같은 컨트롤러와 서비스를 확장합니다.
  • MoMoGo-QuizPlatform/MoMoGo#9: ProblemController, ProblemService, ProblemServiceImpl, ProblemErrorCode의 기반 API를 추가했으며, 본 변경이 문제 생성 경로를 수정합니다.

Suggested reviewers: idktomorrow, jaejo

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 75.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed 제목은 두 AI 문제 생성 API에 Idempotency-Key 중복 요청 방지를 추가하는 주요 변경 사항을 정확하고 간결하게 설명합니다.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/problem-refactor

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

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@momogo-core/src/main/java/com/momogo/core/domain/problem/service/ProblemServiceImpl.java`:
- Around line 306-335: Update the AI request locking flows in ProblemServiceImpl
(momogo-core/src/main/java/com/momogo/core/domain/problem/service/ProblemServiceImpl.java:306-335)
and RoomProblemServiceImpl
(momogo-core/src/main/java/com/momogo/core/domain/room/service/RoomProblemServiceImpl.java:135-164)
to generate a unique request token, store it as the lock value with the existing
TTL, and release the lock via Lua compare-and-delete so only the owner can
delete it. Also enforce or manage an AI-call timeout, retry, or cancellation
strategy so execution cannot silently outlive the fixed TTL and allow concurrent
generation.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: cfdf7912-60f4-4aaa-bdfe-f31bef70f6af

📥 Commits

Reviewing files that changed from the base of the PR and between bd4e5eb and 18376e8.

📒 Files selected for processing (8)
  • momogo-api/src/main/java/com/momogo/api/problem/ProblemController.java
  • momogo-api/src/main/java/com/momogo/api/room/RoomProblemController.java
  • momogo-core/src/main/java/com/momogo/core/domain/problem/exception/ProblemErrorCode.java
  • momogo-core/src/main/java/com/momogo/core/domain/problem/service/ProblemService.java
  • momogo-core/src/main/java/com/momogo/core/domain/problem/service/ProblemServiceImpl.java
  • momogo-core/src/main/java/com/momogo/core/domain/room/exception/RoomProblemErrorCode.java
  • momogo-core/src/main/java/com/momogo/core/domain/room/service/RoomProblemService.java
  • momogo-core/src/main/java/com/momogo/core/domain/room/service/RoomProblemServiceImpl.java

Backend now requires this header (see PR #61); without it the
space AI-generation call fails with 400 MissingRequestHeaderException.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
@Junkov0
Junkov0 requested review from idktomorrow and jaejo August 6, 2026 07:20

@idktomorrow idktomorrow left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

저는 별다른 문제점 찾을 수 없었습니다.
바쁜와중에도 작성하시느라 고생하셨습니다. ❤️

Junkov0 and others added 2 commits August 7, 2026 14:52
TTL 만료 후 다른 요청이 같은 키로 락을 재획득했을 때, 기존 요청의
실패 처리가 무조건 delete를 호출해 새 락을 지우는 문제가 있었음.
락 값을 요청별 토큰으로 바꾸고 Lua compare-and-delete로 소유자만
해제하도록 수정.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
catch(RuntimeException)만 처리해 성공 시 락이 TTL까지 남고,
Error 계열(OOM 등) 발생 시 락 누수가 있었음. finally로 바꿔
성공/실패/Error 모든 경로에서 락이 해제되도록 수정.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
@Junkov0
Junkov0 merged commit 0c095b1 into develop Aug 7, 2026
1 check 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.

3 participants