Skip to content

feat: LLM 선택 미션 생성 및 Outbox 전송 파이프라인 안정화 (V4) - #173

Merged
heeun98 merged 15 commits into
mainfrom
feature/PICK-247-llm-mission-generate
Aug 2, 2026
Merged

heeun98 merged 15 commits into
mainfrom
feature/PICK-247-llm-mission-generate

Conversation

@heeun98

@heeun98 heeun98 commented Aug 2, 2026 •

Copy link
Copy Markdown
Collaborator

🛠️ 작업 내용

LLM 선택 미션 생성 (PICK-247)

  • 오늘 첫 선택 사용자 전용 LLM 미션 생성 API — 태그 필수 검증, 기존 선택 시 409
  • 전용 가상 스레드 실행기 기반 비동기 처리 (@Async + CompletableFuture, ASYNC 재디스패치 401 수정 포함)
  • 사용자별 분산 락(따닥 방어) + unique 제약 최종 방어선, Mission ID 채번을 auto increment + admin_mission_id 매핑으로 전환
  • Gemini 모델 gemini-3.1-flash-lite 고정, thinking 비활성화로 응답 속도 개선

Outbox 전송 파이프라인 V4

  • 상태 머신 확장(READY/PROCESSING/SENT/FAILED): 성공·실패 모두 삭제 대신 마킹으로 보존 — 대사(reconciliation) 대비, 수동 재전송 가능
  • next_retry_at 백오프(5/10/15분) + 재시도 상한 3회 → 초과 시 FAILED 승격 + 알림 (30분 이상 장애는 수동 복구로 전환)
  • SendResult를 성공/실패 2분류로 단순화 — 수신 측 멱등키 dedup 전제, 비즈니스 거절이 없는 도메인이라 모든 실패가 재시도로 수렴
  • 폴러를 1분 주기 + 호출당 한 배치(30건, fixedDelay) 구조로 전환, claim 인덱스 (status, next_retry_at) 교체
  • Admin 멱등 저장의 rollback-only 500 버그 수정, stuck PROCESSING 복구 threshold 재계산(600초)

미션 로그 completedDate 추가

  • 일 단위 집계·보상 기준을 로그 도착 시각 → 완료 날짜로 변경 (자정 경계 재시도 시 실적 날짜 어긋남 방지)
  • Flyway V3: user_mission_log.completed_date 추가 + 기존 row 백필 + NOT NULL 전환

전역 피드 캐시 v2

  • TTL+분산락 → 상주 캐시 + 30초 스케줄러 동기화 전환 (p99 약 90ms → 20ms), rebuild는 RENAME 원자 교체
  • Lettuce 커맨드 타임아웃 1초 설정 (장애 시 요청 스레드 블로킹 방지)

🎯 리뷰 포인트

  • outbox 스키마 변경: retry_count/last_error/next_retry_at(NOT NULL)/sent_at 컬럼 추가 — 배포 시 outbox 테이블에 기존 row가 남아 있으면 next_retry_at = created_at 백필 필요
  • 재시도 상한 3회(총 30분 커버): FAILED 알림이 사람에게 즉시 닿는다는 전제의 선택 — 알림 채널 구축 전까지는 30분 이상 장애 건이 수동 복구 대기로 쌓임
  • SendResult 2분류의 전제: 수신 측(Admin) 멱등성. 보상 지급 등 비멱등 작업이 outbox를 타게 되면 "알 수 없음" 상태 분리 필요 (SendResult 주석 참조)
  • Flyway V3 마이그레이션: prod(MySQL) 전용 문법 — admin 배포 순서 확인
  • 성공 건을 삭제하지 않고 SENT로 보존하므로 추후 purge 배치 필요 (후속 작업)

⏳ 작업 시간

  • 추정 시간:
  • 실제 시간:

Summary by CodeRabbit

  • 개선 사항

    • 전역 피드가 주기적으로 최신 상태와 동기화되어 누락·삭제된 항목을 최대 30초 내 복구합니다.
    • 미션 완료일이 정확히 기록되어 날짜별 통계가 개선됩니다.
    • 외부 전송 실패 항목을 자동 재시도하여 이벤트 누락 가능성을 줄였습니다.
    • 장시간 처리 중인 이벤트를 자동 복구합니다.
  • 문서

    • 전역 피드 캐시 및 이벤트 처리 방식의 변경 사항과 운영 전략을 문서화했습니다.

heeun98 added 15 commits July 15, 2026 22:51
- 버전별 구조, 개선 목표, 남은 문제를 claim(소유권) 장치의 변천 관점으로 정리
- V1 커넥션 점유 수치, V2 PROCESSING 상태의 존재 이유와 timeout 복구의 약점, V3 SET/latch 설계 근거와 트레이드오프 포함
- v1(짧은 TTL + single-flight)은 TTL 만료마다 나머지 읽기가 락 대기에 묶여 500 req/s 부하에서 p99 약 90ms spike 발생
- TTL 제거로 캐시 상주(20건이라 메모리 부담 없음) → 주기 만료·재캐싱 경쟁이 사라져 분산락 제거, p99 약 20ms로 평탄화
- write-through(AFTER_COMMIT, 원자 ZADD, 콜드 스킵)는 유지, 불일치 복구는 30초 주기 스케줄러의 DB 전체 재적재가 담당(최대 30초 내 복구)
- rebuild는 임시 키 적재 후 RENAME 원자 교체로 변경 — 만료가 없어진 뒤 DB에서 사라진 항목의 캐시 잔존 방지, 교체 순간 빈 캐시 미노출
- 조회/쓰기/스케줄러 3주체가 캐시를 만지는 전체 그림과 경로별 상세 흐름
- addItem(끼워넣기) vs rebuild(통째 교체) 구분, 병합 대신 교체·DEL 대신 RENAME인 이유, 덮어쓰기 트레이드오프 타임라인 포함
- 6장 권장 설계는 v1 기준임을 명시
- 커스텀 LettuceConnectionFactory 빈이라 spring.data.redis.timeout 프로퍼티가 무시되므로 LettuceClientConfiguration으로 직접 지정
- Redis 행(hang) 시 피드 조회·write-through가 최대 60초 블로킹되던 노출을 1초로 제한 — 조회는 DB 폴백, 쓰기는 예외 삼킴 후 스케줄러(≤30초)가 복구하는 전제라 fail-fast가 안전
- 기존: 리스너가 completion 재조회 후 멱등키·payload를 재생성 — 서비스와 동일 로직이 두 벌 존재
- 멱등키 생성이 한쪽만 수정되면 리스너와 폴러가 다른 키를 전송해 Admin dedup이 깨지는 잠재 결함
- outbox row의 JSON을 역직렬화해 전송(폴러와 동일 경로)함으로써 payload 생성 지점을 서비스 한 곳으로 통일
- completion 조회·LAZY 프록시 접근 제거, 파싱 실패 건은 폴러가 영구 실패로 정리하도록 위임
- V2 claim 쿼리(READY 필터 + created_at 정렬 + LIMIT)가 filesort 플랜을 타면 LIMIT이 정렬 후 적용되어 READY 전건에 락이 걸림
- 복합 인덱스로 정렬 없는 스트리밍 플랜을 보장 → 스캔 경로가 곧 락 범위이므로 잠기는 행이 반환되는 n건으로 최소화
- 단일 status 인덱스는 복합의 leftmost prefix로 커버되어 제거 (findStuckProcessing의 status 필터 포함)
- 상태 확장(READY/PROCESSING/SENT/FAILED): 성공·영구실패 모두 하드 딜리트 대신 마킹으로 보존 — 대사(reconciliation) 대비, 원인 수정 후 수동 재전송 가능
- retry_count·last_error·next_retry_at·sent_at 컬럼 추가, claim 인덱스를 (status, next_retry_at)로 교체
- 일시 실패는 5분×n(상한 30분) 백오프 예약 — 재시도 폭풍 방지 + 실패 건의 배치 슬롯 독점(starvation) 해소, 15회 초과 시 FAILED 승격으로 운영자 호출
- 폴러 주기 5분 + 사이클 내 배수 루프(배치 30건): 해피 패스는 리스너 즉시 전송이 담당하므로 폴러는 실패 수거 전용, Admin 장애 복구 후 적체는 한 사이클에 배수
- stuck PROCESSING 복구 threshold를 실제 설정 기준으로 재계산(배치 30 × 타임아웃 10초 × 2 = 600초)
- 리스너는 성공 시 SENT 마킹만 수행, 실패 분류·백오프는 폴러 Tx2 단일 책임 유지
- V1 폴러(@scheduled) 비활성화
- 기존: 409 외 모든 4xx를 영구 실패로 분류 → 재시도 대상인 408(타임아웃)·429(과부하)까지 삭제되던 결함
- 분류 기준을 "원인이 어디에 있는가"로 재정의: 시간이 해결하는 실패(5xx·408·429·409)는 일시, payload 문제(400)·환경 문제(401/403/404 등)는 영구
- Admin이 409를 반환하는 경로가 없어 죽은 코드였던 Conflict 전용 분기를 상태코드 판정으로 통합
- 영구 실패도 이제 삭제가 아닌 FAILED 보존이므로(V4), 환경 문제 오분류가 데이터 유실로 이어지지 않음
- 기존: @transactional 안에서 unique 제약 위반 → 트랜잭션이 rollback-only로 오염 → 예외를 잡아도 커밋 시 UnexpectedRollbackException(500) → API 폴러가 일시 실패로 재시도하고서야 200
- saveMissionLog에서 @transactional 제거: exists 조회·save는 원자성이 필요 없고(레이스는 unique 제약이 담당), save는 리포지토리 자체 트랜잭션으로 충분 → catch 후 정상 200(멱등 처리) 응답 가능
- catch에서 existsByIdempotencyKey 재확인 가드 추가: not-null 등 다른 제약 위반을 중복으로 오인해 삼키지 않도록 진짜 중복일 때만 false, 아니면 rethrow
- findById().orElse(null) 후 null 체크하던 안티패턴 제거 — Optional을 반환 타입 그대로 유지
- parsePayload가 null 대신 Optional을 반환하도록 변경
- 조회/파싱/전송을 단계별 메서드로 분리해 handle()이 "찾으면 전송, 없으면 경고" 한 문장으로 읽히도록 개선
- EC2 IP 변경(13.124.36.181 → 13.124.180.92)에 따른 기본값 갱신
- prod는 api.base-url(도메인)이 덮어쓰므로 로컬/미설정 환경용 fallback
- 이 도메인(통계 로그)에는 비즈니스 거절 응답이 없고(Admin은 사실상 200/500만 응답) 수신 측이 멱등키로 dedup하므로, 모든 실패의 대응이 "재시도" 하나로 수렴 — 분류를 유지할 실익이 없음
- poison 건은 재시도 상한(15회 초과 시 FAILED 승격)이 백스톱 — 유실·무한 재시도 없음
- 수신 측 멱등성이 전제임을 SendResult 주석에 명시: 보상 지급 등 비멱등 작업이 outbox를 타면 "알 수 없음"을 1급 상태로 분리해야 함
- 비활성 구버전 폴러(V1·V2·V3)는 컴파일 유지를 위한 기계적 치환만 적용
- 기존에는 완료 날짜가 멱등키 문자열 안에만 있고 Admin이 가진 시각은 로그 도착 시각(created_at)뿐 — 자정 직전 완료 건이 리스너 실패 후 폴러 재시도로 자정 넘어 도착하면 다음 날 실적으로 잡혀 일 단위 랭킹·보상이 어긋나는 문제
- payload·UserMissionLog에 completed_date를 명시적 필드로 추가, 일 단위 집계는 이 값 기준으로 (인덱스 포함)
- 구버전 payload(completedDate 없음) 호환: 배포 전환기 outbox 잔여 건은 도착일로 대체 저장 + 경고 로그 (not-null 위반 재시도 루프 방지)
- Flyway V3: 컬럼 추가 후 기존 row는 도착일로 백필하고 NOT NULL 전환
- 30분 이상의 장애는 자동 복구 대신 FAILED 승격 → 알림 → 수동 재전송으로 전환
- FAILED 알림이 사람에게 즉시 닿는다는 전제 위의 선택임을 주석에 명시 — 알림 채널이 깨지면 장애 건이 조용히 수동 복구 대기로 쌓이므로 알림 인프라와 함께 유지보수 필요
- 기존: 5분 주기 + 빌 때까지 while 배수 → 변경: 1분 주기(fixedDelay) + 호출당 30건, 적체 해소는 스케줄러 반복이 담당 (분당 30건, 적체 300건도 10분 내 배수)
- 리스너 실패 건의 첫 폴러 재시도가 최대 5분 → 최대 1분으로 단축, while 루프 제거로 종료 조건 추론 불필요
- fixedDelay라 장애 시 호출이 길어져도(최대 300초) 다음 호출과 겹치지 않음
- 백오프(5/10/15분)·재시도 상한(3회)·stuck threshold(600초)는 폴러 주기와 독립인 값이므로 변경 없음 — 근거를 주석으로 명시
@coderabbitai

coderabbitai Bot commented Aug 2, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

전역 피드 캐시는 TTL과 single-flight를 제거하고 30초 주기 DB 동기화와 원자적 Redis 교체를 사용한다. 미션 완료일은 payload, 관리자 요청, 엔티티와 데이터베이스에 저장된다. Outbox 실패 유형은 Failure로 통합된다. Outbox V4는 배치 claim, 외부 전송, 결과 반영과 PROCESSING 복구를 수행한다.

Estimated code review effort: 4 (Complex) | ~60 minutes

Poem

캐시는 서른 초마다 새로 깨어나고
완료일은 payload를 타고 흐르며
Outbox는 실패를 품고 다시 달린다
V4 폴러가 배치를 건네면
상태는 READY에서 SENT로 노를 젓는다.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 32.50% 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 제목은 LLM 선택 미션 생성과 Outbox V4 전송 파이프라인 안정화라는 PR의 주요 변경 사항을 명확하고 간결하게 요약합니다.
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/PICK-247-llm-mission-generate

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.

@heeun98
heeun98 merged commit f32e9af into main Aug 2, 2026
4 of 5 checks passed

@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: 9

🧹 Nitpick comments (3)
docs/outbox-poller-evolution.md (1)

8-8: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

코드 블록 언어를 지정하세요.

각 코드 블록 시작 줄에 text를 추가하세요. 현재 markdownlint MD040 경고가 발생합니다.

Also applies to: 40-40, 76-76, 131-131

🤖 Prompt for 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.

In `@docs/outbox-poller-evolution.md` at line 8, Update every fenced code block in
outbox-poller-evolution.md, including the blocks at the referenced locations, to
specify the text language identifier after the opening fence. Ensure each block
begins with ```text to resolve the markdownlint MD040 warnings.

Source: Linters/SAST tools

peektime-api/src/main/java/com/team/peektime_api/global/outbox/entity/OutboxStatus.java (1)

3-21: 🚀 Performance & Scalability | 🔵 Trivial

상태 머신 문서화는 훌륭합니다. SENT 데이터 정리 배치를 언제 붙일지 계획해 두세요.

상태 전이도와 각 상태의 책임을 명확히 적어주셔서 다음 담당자가 코드를 열어보지 않고도 흐름을 이해할 수 있겠네요. 좋은 습관입니다.

다만 주석대로 SENT는 어떤 스케줄러도 읽지 않고 영구 보존됩니다. PR 설명에서도 "SENT 데이터 정리 배치"를 핵심 검토 사항으로 언급하고 있으니, 이 PR 범위에서는 의도적으로 제외한 것인지, 아니면 후속 작업 티켓이 이미 있는지 확인해 주세요. 정리 배치 없이 운영이 오래 지속되면 테이블 크기와 인덱스 비대화로 claim 쿼리 성능에도 영향을 줄 수 있습니다.

🤖 Prompt for 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.

In
`@peektime-api/src/main/java/com/team/peektime_api/global/outbox/entity/OutboxStatus.java`
around lines 3 - 21, Document the planned cleanup of SENT records in the
OutboxStatus follow-up work, including whether it is intentionally out of scope
for this change and referencing the existing tracking ticket if one exists. Do
not alter the state transitions; ensure the retention and purge plan is
explicitly recorded for future implementation.
peektime-api/src/main/java/com/team/peektime_api/global/outbox/scheduler/v4/OutboxPollerV4.java (1)

43-59: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

동시 스케줄러 실행을 위한 TaskScheduler 설정을 추가해 주세요.

OutboxPollerV4의 장애 구간은 최대 300초까지 갈 수 있습니다. 현재 설정에는 ThreadPoolTaskScheduler가 없고 spring.task.scheduling.pool.size도 없으므로, @EnableScheduling의 기본 TaskScheduler가 사용되어 다른 @Scheduled가 같은 스레드에서 순차 실행됩니다. 이 폴러가 길어지면 ProcessingRecoverySchedulerV4나 GlobalFeedCacheSyncScheduler의 동작이 지연될 수 있습니다. spring.task.scheduling.pool.size를 늘리거나 커스텀 TaskScheduler 빈으로 스케줄러 실행 주기를 분리하는 구성을 추가하면 좋습니다. 관련 개념: Spring Boot 태스크 스케줄링/TaskScheduler 문서를 함께 참고하세요.

🤖 Prompt for 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.

In
`@peektime-api/src/main/java/com/team/peektime_api/global/outbox/scheduler/v4/OutboxPollerV4.java`
around lines 43 - 59, Configure concurrent scheduled-task execution for
OutboxPollerV4 by adding an appropriate TaskScheduler/ThreadPoolTaskScheduler
setup or increasing spring.task.scheduling.pool.size. Ensure `@Scheduled` jobs
such as ProcessingRecoverySchedulerV4 and GlobalFeedCacheSyncScheduler can run
independently while pollAndProcess may block for up to 300 seconds.
🤖 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 `@docs/global-feed-design.md`:
- Around line 42-45: The decision log marks the L1 local cache as required, but
GlobalFeedService#getRecentFeed currently only uses
feedCacheRepository.findRecent(). Either add a global-feed L1 lookup and
population path at the service or repository layer using the project’s
established in-memory caching mechanism, ensuring hot-key reads are absorbed
before Redis/DB access, or revise the decision log to remove the mandatory L1
requirement if it is out of scope.

In
`@peektime-admin/src/main/java/com/team/peektime_admin/global/config/RestClientConfig.java`:
- Line 11: Update the api.base-url injection in RestClientConfig to remove the
insecure public HTTP fallback. Require the active profile to explicitly define a
TLS-protected HTTPS endpoint, allowing startup to fail when the configuration is
missing.

In
`@peektime-api/src/main/java/com/team/peektime_api/domain/feed/cache/GlobalFeedCacheRepository.java`:
- Around line 64-66: 캐시 조회에서 HIT(empty), MISS, FAILURE를 구분하지 않아 유효한 빈 피드가 이전 데이터
또는 반복 DB 조회로 처리됩니다.
peektime-api/src/main/java/com/team/peektime_api/domain/feed/cache/GlobalFeedCacheRepository.java#L64-L66의
rebuild()가 빈 스냅샷에서도 기존 ZSET을 삭제하고 초기화 마커를 저장하도록 수정하고,
peektime-api/src/main/java/com/team/peektime_api/domain/feed/service/GlobalFeedService.java#L41-L46의
getRecentFeed()가 빈 List가 아닌 캐시 상태를 기준으로 DB 폴백을 결정하게 하세요.
docs/global-feed-design.md#L582-L586의 복구 설명에도 마지막 항목 삭제로 빈 피드가 되는 경우를 반영하세요.

In
`@peektime-api/src/main/java/com/team/peektime_api/domain/feed/scheduler/GlobalFeedCacheSyncScheduler.java`:
- Around line 12-15: Replace the unconditional “within 30 seconds” recovery
guarantee with wording that reflects fixedDelay scheduling and possible
synchronization or retry failures. In GlobalFeedCacheSyncScheduler.java lines
12-15, describe recovery as occurring on the next successful synchronization
cycle; update the related guarantee references in
GlobalFeedWriteThroughListener.java lines 20-21 and docs/global-feed-design.md
lines 582-595 and 698-707 consistently, without adding execution limits, failure
alerts, or retry policy unless implementing those explicitly.

In
`@peektime-api/src/main/java/com/team/peektime_api/domain/feed/service/GlobalFeedService.java`:
- Around line 41-46: Limit cold-cache rebuilding to a single coordinated
execution shared with scheduled rebuilds: in GlobalFeedService at
peektime-api/src/main/java/com/team/peektime_api/domain/feed/service/GlobalFeedService.java:41-46,
guard the loadFromDb and rebuild flow with the common coordinator. In
GlobalFeedCacheRepository at
peektime-api/src/main/java/com/team/peektime_api/domain/feed/cache/GlobalFeedCacheRepository.java:72-75,
replace REBUILD_KEY for temporary rebuild data with a per-invocation unique key
and clean it up on failure. In docs/global-feed-design.md:538-547, scope the
lock-free statement to cache-hit requests only.

In
`@peektime-api/src/main/java/com/team/peektime_api/global/outbox/entity/OutboxEvent.java`:
- Around line 51-63: 기존 outbox_event 테이블을 보정하는 마이그레이션과 백필 SQL을 추가하세요.
retry_count, last_error, next_retry_at, sent_at 컬럼을 엔티티 매핑과 일치시키고,
next_retry_at을 NOT NULL로 적용하기 전에 기존 READY/PROCESSING 행에 안전한 기본값을 채우세요. 백필된
next_retry_at은 현재 시각 이하로 설정해 기존 이벤트도 즉시 claim 대상이 되도록 하며, 관련 데이터 백필을 PR의 마이그레이션
흐름에 포함하세요.
- Around line 24-25: Update OutboxEvent.LISTENER_GRACE_SECONDS to align with the
Admin RestClient’s maximum connection-plus-read timeout of 10 seconds, or
explicitly document the separate grace-period assumption alongside the constant.
Ensure the value and documentation prevent claimBatch() from taking an event
before the listener request can complete.
- Around line 73-101: OutboxEvent lacks optimistic locking, allowing concurrent
applyResults and recoverStuckProcessing updates to overwrite retry data. Add a
Hibernate `@Version` field to OutboxEvent, ensure its persistence mapping
participates in version checks, and handle the resulting optimistic-lock
exception in the relevant processing flow by logging the failure or applying the
existing retry strategy; keep the V4 short transaction boundaries unchanged.

In
`@peektime-api/src/main/java/com/team/peektime_api/global/outbox/scheduler/v4/OutboxV4TransactionManager.java`:
- Around line 77-87: Update recoverStuckProcessing in OutboxV4TransactionManager
so repeated PROCESSING-to-READY recovery cannot bypass the retry limit
indefinitely. Track stuck-recovery attempts separately or apply an absolute
age-based expiration, and transition events that exceed the configured safety
threshold to FAILED while preserving the current READY recovery behavior for
eligible events.

---

Nitpick comments:
In `@docs/outbox-poller-evolution.md`:
- Line 8: Update every fenced code block in outbox-poller-evolution.md,
including the blocks at the referenced locations, to specify the text language
identifier after the opening fence. Ensure each block begins with ```text to
resolve the markdownlint MD040 warnings.

In
`@peektime-api/src/main/java/com/team/peektime_api/global/outbox/entity/OutboxStatus.java`:
- Around line 3-21: Document the planned cleanup of SENT records in the
OutboxStatus follow-up work, including whether it is intentionally out of scope
for this change and referencing the existing tracking ticket if one exists. Do
not alter the state transitions; ensure the retention and purge plan is
explicitly recorded for future implementation.

In
`@peektime-api/src/main/java/com/team/peektime_api/global/outbox/scheduler/v4/OutboxPollerV4.java`:
- Around line 43-59: Configure concurrent scheduled-task execution for
OutboxPollerV4 by adding an appropriate TaskScheduler/ThreadPoolTaskScheduler
setup or increasing spring.task.scheduling.pool.size. Ensure `@Scheduled` jobs
such as ProcessingRecoverySchedulerV4 and GlobalFeedCacheSyncScheduler can run
independently while pollAndProcess may block for up to 300 seconds.
🪄 Autofix (Beta)

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: b16a6f79-c579-4c47-9cfd-da6ea63659f6

📥 Commits

Reviewing files that changed from the base of the PR and between a32c3e3 and a236671.

📒 Files selected for processing (27)
  • docs/global-feed-design.md
  • docs/outbox-poller-evolution.md
  • peektime-admin/src/main/java/com/team/peektime_admin/domain/stats/dto/MissionLogRequest.java
  • peektime-admin/src/main/java/com/team/peektime_admin/domain/stats/entity/UserMissionLog.java
  • peektime-admin/src/main/java/com/team/peektime_admin/domain/stats/service/StatsService.java
  • peektime-admin/src/main/java/com/team/peektime_admin/global/config/RestClientConfig.java
  • peektime-admin/src/main/resources/db/migration/V3__add_completed_date_to_user_mission_log.sql
  • peektime-api/src/main/java/com/team/peektime_api/domain/feed/cache/GlobalFeedCacheRepository.java
  • peektime-api/src/main/java/com/team/peektime_api/domain/feed/event/GlobalFeedWriteThroughListener.java
  • peektime-api/src/main/java/com/team/peektime_api/domain/feed/scheduler/GlobalFeedCacheSyncScheduler.java
  • peektime-api/src/main/java/com/team/peektime_api/domain/feed/service/GlobalFeedService.java
  • peektime-api/src/main/java/com/team/peektime_api/domain/mission/event/MissionCompletedEventListener.java
  • peektime-api/src/main/java/com/team/peektime_api/domain/mission/event/MissionLogPayload.java
  • peektime-api/src/main/java/com/team/peektime_api/domain/mission/service/UserMissionCompletionService.java
  • peektime-api/src/main/java/com/team/peektime_api/global/config/RedisConfig.java
  • peektime-api/src/main/java/com/team/peektime_api/global/infra/admin/AdminClient.java
  • peektime-api/src/main/java/com/team/peektime_api/global/outbox/SendResult.java
  • peektime-api/src/main/java/com/team/peektime_api/global/outbox/entity/OutboxEvent.java
  • peektime-api/src/main/java/com/team/peektime_api/global/outbox/entity/OutboxStatus.java
  • peektime-api/src/main/java/com/team/peektime_api/global/outbox/repository/OutboxRepository.java
  • peektime-api/src/main/java/com/team/peektime_api/global/outbox/scheduler/OutboxPoller.java
  • peektime-api/src/main/java/com/team/peektime_api/global/outbox/scheduler/OutboxPollerV2.java
  • peektime-api/src/main/java/com/team/peektime_api/global/outbox/scheduler/PollProcesser.java
  • peektime-api/src/main/java/com/team/peektime_api/global/outbox/scheduler/v3/OutboxConsumer.java
  • peektime-api/src/main/java/com/team/peektime_api/global/outbox/scheduler/v4/OutboxPollerV4.java
  • peektime-api/src/main/java/com/team/peektime_api/global/outbox/scheduler/v4/OutboxV4TransactionManager.java
  • peektime-api/src/main/java/com/team/peektime_api/global/outbox/scheduler/v4/ProcessingRecoverySchedulerV4.java

Comment on lines +42 to +45
- ~~✅ **single-flight** (R3 stampede)~~ → **v2에서 제거.** TTL이 없어 주기 만료 = 전체 동시 MISS 자체가 사라짐(TS2)
- ✅ **L1 로컬 캐시** (R4 hot key) — 전역 키 하나에 전 트래픽 집중
- ✅ **원자적 ZADD** (R5 lost update) — 동시 완료가 흔함
- ✅ **짧은 TTL + 재시도** (R2 dual-write 완화)
- ✅ ~~짧은 TTL~~ → **30초 주기 스케줄러 동기화** (R2 dual-write 복구, v2)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🚀 Performance & Scalability | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

# 전역 피드 조회 경로의 로컬 캐시 구현 여부를 확인합니다.
rg -n -i -C 3 '`@Cacheable`|Caffeine|CacheManager|GlobalFeedService|getRecentFeed' peektime-api

Repository: depromeet/18th-team5-server

Length of output: 7137


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

echo "== docs/global-feed-design.md relevant lines =="
sed -n '1,90p' docs/global-feed-design.md | cat -n

echo
echo "== global feed service =="
sed -n '1,180p' peektime-api/src/main/java/com/team/peektime_api/domain/feed/service/GlobalFeedService.java | cat -n

echo
echo "== search for local/cache implementations =="
rg -n -i --glob '!*.class' 'inmemory|caffeine|guava|Cacheable|cache manager|Caffeine|loadingcache|loading cache|threadlocal|concurrentmap|ConcurrentHashMap|local' peektime-api/docs peektime-api/src/main/java 2>/dev/null | head -200

Repository: depromeet/18th-team5-server

Length of output: 32656


L1 로컬 캐시의 구현 범위를 맞춰 주세요.

이 문서의 결정 로그(line 43)는 L1 로컬 캐시를 필수 장치로 정의합니다. 현재 GlobalFeedService#getRecentFeed는 feedCacheRepository.findRecent()로 Redis/메모리 계층만 사용하고, @Cacheable, Caffeine/Guava, LoadingCache, 인메모리 Map 같은 전역 피드용 L1 조회 경로는 없습니다. L1이 이번 범위에 포함된다면 서비스/리포지토리 계층에 추가하고, 포함되지 않는다면 해당 문서 필수 요구사항을 정리해 주세요. 참고: 전역 hot key는 Redis/DB가 아니라 애플리케이션 내부 로컬 캐시부터 흡수해야 합니다. :)

🤖 Prompt for 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.

In `@docs/global-feed-design.md` around lines 42 - 45, The decision log marks the
L1 local cache as required, but GlobalFeedService#getRecentFeed currently only
uses feedCacheRepository.findRecent(). Either add a global-feed L1 lookup and
population path at the service or repository layer using the project’s
established in-memory caching mechanism, ensuring hot-key reads are absorbed
before Redis/DB access, or revise the decision log to remove the mandatory L1
requirement if it is out of scope.

public class RestClientConfig {

@Value("${api.base-url:http://13.124.36.181:8080}")
@Value("${api.base-url:http://13.124.180.92:8080}")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift

HTTP 기본 엔드포인트를 제거하세요.

api.base-url이 없으면 공인 IP의 HTTP 엔드포인트를 사용합니다. 이 경로에서는 미션 로그 요청을 가로채거나 변조할 수 있습니다. TLS 엔드포인트를 활성 프로필에 명시하고, 기본값을 제거해서 설정 누락 시 안전하게 기동 실패하게 하세요.

수정 예시
-    `@Value`("${api.base-url:http://13.124.180.92:8080}")
+    `@Value`("${api.base-url}")
     private String apiBaseUrl;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
@Value("${api.base-url:http://13.124.180.92:8080}")
`@Value`("${api.base-url}")
🤖 Prompt for 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.

In
`@peektime-admin/src/main/java/com/team/peektime_admin/global/config/RestClientConfig.java`
at line 11, Update the api.base-url injection in RestClientConfig to remove the
insecure public HTTP fallback. Require the active profile to explicitly define a
TLS-protected HTTPS endpoint, allowing startup to fail when the configuration is
missing.

Comment on lines 64 to +66
public void rebuild(List<FeedCacheItem> items) {
if (items.isEmpty()) {
return;
return; // DB 결과가 비면 교체하지 않음 (일시 오류로 피드를 비우는 것 방지)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

유효한 빈 피드와 캐시 MISS를 구분하세요.

DB에 피드 항목이 없을 수 있습니다. 현재 rebuild()는 이 경우 기존 캐시를 유지합니다. 따라서 마지막 사진이 삭제 또는 차단되면 이전 사진이 캐시에 남습니다.

또한 getRecentFeed()는 빈 결과를 항상 MISS로 처리합니다. 초기 DB가 비어 있으면 모든 요청이 DB를 다시 조회합니다.

캐시 조회 결과를 HIT(empty), MISS, FAILURE로 구분하세요. 정상적인 빈 스냅샷에서는 기존 ZSET을 제거하고 초기화 마커를 저장하세요.

  • peektime-api/src/main/java/com/team/peektime_api/domain/feed/cache/GlobalFeedCacheRepository.java#L64-L66: 빈 스냅샷도 현재 캐시를 대체하도록 변경하세요.
  • peektime-api/src/main/java/com/team/peektime_api/domain/feed/service/GlobalFeedService.java#L41-L46: 빈 List 대신 캐시 상태를 기준으로 DB 폴백을 결정하세요.
  • docs/global-feed-design.md#L582-L586: 마지막 항목이 삭제된 경우까지 포함하도록 복구 설명을 수정하세요.
📍 Affects 3 files
  • peektime-api/src/main/java/com/team/peektime_api/domain/feed/cache/GlobalFeedCacheRepository.java#L64-L66 (this comment)
  • peektime-api/src/main/java/com/team/peektime_api/domain/feed/service/GlobalFeedService.java#L41-L46
  • docs/global-feed-design.md#L582-L586
🤖 Prompt for 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.

In
`@peektime-api/src/main/java/com/team/peektime_api/domain/feed/cache/GlobalFeedCacheRepository.java`
around lines 64 - 66, 캐시 조회에서 HIT(empty), MISS, FAILURE를 구분하지 않아 유효한 빈 피드가 이전
데이터 또는 반복 DB 조회로 처리됩니다.
peektime-api/src/main/java/com/team/peektime_api/domain/feed/cache/GlobalFeedCacheRepository.java#L64-L66의
rebuild()가 빈 스냅샷에서도 기존 ZSET을 삭제하고 초기화 마커를 저장하도록 수정하고,
peektime-api/src/main/java/com/team/peektime_api/domain/feed/service/GlobalFeedService.java#L41-L46의
getRecentFeed()가 빈 List가 아닌 캐시 상태를 기준으로 DB 폴백을 결정하게 하세요.
docs/global-feed-design.md#L582-L586의 복구 설명에도 마지막 항목 삭제로 빈 피드가 되는 경우를 반영하세요.

Comment on lines +12 to +15
* 캐시가 TTL 없이 상주하므로, write-through 실패(dual-write)나 DB 측 변경(삭제 등)으로 생긴 불일치는
* 만료로 자가 치유되지 않는다. 대신 30초 주기로 DB 기준 전체 재적재를 수행해 최대 30초 내 복구를 보장한다.
* 상위 20건 조회 쿼리 1회/30초라 DB 부하는 무시할 수준이며, 실패 여부와 무관하게 무조건 동기화한다
* (인스턴스별 실패 플래그 추적보다 단순하고, 이벤트 유실 등 추적 불가능한 불일치까지 복구).

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

# 스케줄러 실행 방식과 별도 스케줄러 설정을 확인합니다.
rg -n -C 3 '`@Scheduled`|fixedDelay|fixedRate|TaskScheduler|SchedulingConfigurer|spring\.task\.scheduling' peektime-api

Repository: depromeet/18th-team5-server

Length of output: 12461


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

echo "## Candidate files"
fd 'GlobalFeedCacheSyncScheduler\.java|GlobalFeedWriteThroughListener\.java|global-feed-design\.md' .

echo "## Scheduler outline"
ast-grep outline peektime-api/src/main/java/com/team/peektime_api/domain/feed/scheduler/GlobalFeedCacheSyncScheduler.java --view compact || true

echo "## Listener outline"
ast-grep outline peektime-api/src/main/java/com/team/peektime_api/domain/feed/event/GlobalFeedWriteThroughListener.java --view compact || true

echo "## Relevant scheduler file"
cat -n peektime-api/src/main/java/com/team/peektime_api/domain/feed/scheduler/GlobalFeedCacheSyncScheduler.java | sed -n '1,140p'

echo "## Relevant listener file"
cat -n peektime-api/src/main/java/com/team/peektime_api/domain/feed/event/GlobalFeedWriteThroughListener.java | sed -n '1,140p'

echo "## Relevant docs sections"
cat -n docs/global-feed-design.md | sed -n '560,610p'
cat -n docs/global-feed-design.md | sed -n '688,712p'

Repository: depromeet/18th-team5-server

Length of output: 7727


🌐 Web query:

Spring Framework @scheduled fixedDelay interval includes task duration documentation

💡 Result:

The Spring Framework @Scheduled fixedDelay attribute defines the time interval that must elapse between the completion of one task execution and the start of the next [1][2][3]. Because the delay is measured starting from when the method finishes, the total time between the start of two consecutive executions is the sum of the task's execution duration and the configured fixedDelay interval [4]. Key points regarding fixedDelay behavior: - Execution Gap: It guarantees a fixed period of silence between the end of one invocation and the start of the next [1][5][4]. - Task Duration: The task duration is not included in the 'delay' itself, but it effectively increases the cycle time (the period between starts) [3][4]. - Sequential Execution: Because the next execution cannot begin until the current one finishes, fixedDelay inherently ensures that tasks do not overlap [3][4]. - Threading Note: If the task is long-running or the scheduling thread pool is congested, the next execution might be delayed beyond the specified fixedDelay period because the scheduler thread must be available to trigger the task [6][3]. In contrast, fixedRate schedules tasks at a fixed interval measured from the start of each invocation, meaning it does not wait for the previous task to complete [3][4].

Citations:


30초 내 복구 보장값을 실제 동작과 일치하게 수정하세요.

@Scheduled(fixedDelay = 30_000)은 이전 동기화 종료부터 다음 실행을 시작합니다. DB/Redis 소요 시간이 포함되면 전체 복구 시간은 30초가 넘을 수 있고, 실패와 재시도만 남기는 현재 구조는 장애 반복 시 보장한 복구 SLA를 제공할 수 없습니다. Spring scheduling의 fixedDelay 동작을 참고해, “다음 성공 동기화 주기”로 문구를 바꾸거나 30초 보장 자체를 요구하느니 실행 시간 제한, 실패 알림, 재시도 정책을 추가하세요.

  • peektime-api/src/main/java/com/team/peektime_api/domain/feed/scheduler/GlobalFeedCacheSyncScheduler.java#L12-L15
  • peektime-api/src/main/java/com/team/peektime_api/domain/feed/event/GlobalFeedWriteThroughListener.java#L20-L21
  • docs/global-feed-design.md#L582-L595
  • docs/global-feed-design.md#L698-L707
📍 Affects 3 files
  • peektime-api/src/main/java/com/team/peektime_api/domain/feed/scheduler/GlobalFeedCacheSyncScheduler.java#L12-L15 (this comment)
  • peektime-api/src/main/java/com/team/peektime_api/domain/feed/event/GlobalFeedWriteThroughListener.java#L20-L21
  • docs/global-feed-design.md#L582-L595
  • docs/global-feed-design.md#L698-L707
🤖 Prompt for 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.

In
`@peektime-api/src/main/java/com/team/peektime_api/domain/feed/scheduler/GlobalFeedCacheSyncScheduler.java`
around lines 12 - 15, Replace the unconditional “within 30 seconds” recovery
guarantee with wording that reflects fixedDelay scheduling and possible
synchronization or retry failures. In GlobalFeedCacheSyncScheduler.java lines
12-15, describe recovery as occurring on the next successful synchronization
cycle; update the related guarantee references in
GlobalFeedWriteThroughListener.java lines 20-21 and docs/global-feed-design.md
lines 582-595 and 698-707 consistently, without adding execution limits, failure
alerts, or retry policy unless implementing those explicitly.

Comment on lines 41 to +46
List<FeedCacheItem> items = feedCacheRepository.findRecent();
if (items.isEmpty()) {
items = loadWithSingleFlight(); // MISS → 한 요청만 DB 재적재
// 콜드 캐시(최초 기동/Redis 유실)에서만 도달 → DB 폴백 + 즉시 워밍.
// 첫 재적재가 수 ms 내 끝나 이후 요청은 캐시 HIT이므로 락 없이도 쇄도가 지속되지 않는다.
items = loadFromDb();
feedCacheRepository.rebuild(items);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

콜드 캐시 재구축을 단일 실행으로 제한하세요.

TTL 제거는 주기적 MISS만 제거합니다. 콜드 스타트 또는 Redis 키 유실 시에는 동시에 들어온 모든 요청이 loadFromDb()와 rebuild()를 실행합니다.

이때 모든 호출이 REBUILD_KEY를 공유합니다. 한 호출이 다른 호출의 임시 키를 삭제하거나 rename할 수 있습니다. DB 조회 쇄도와 재구축 실패 로그가 발생할 수 있습니다.

콜드 재구축과 스케줄러 재구축에 공통 조정자를 적용하세요. 재구축 임시 키는 호출별 고유 키를 사용하세요.

  • peektime-api/src/main/java/com/team/peektime_api/domain/feed/service/GlobalFeedService.java#L41-L46: 콜드 MISS에서는 한 요청만 DB 조회와 재구축을 수행하도록 조정하세요.
  • peektime-api/src/main/java/com/team/peektime_api/domain/feed/cache/GlobalFeedCacheRepository.java#L72-L75: REBUILD_KEY 대신 호출별 고유 임시 키를 사용하고 실패 시 정리하세요.
  • docs/global-feed-design.md#L538-L547: 락이 불필요하다는 설명을 캐시 HIT 경로로 한정하세요.
📍 Affects 3 files
  • peektime-api/src/main/java/com/team/peektime_api/domain/feed/service/GlobalFeedService.java#L41-L46 (this comment)
  • peektime-api/src/main/java/com/team/peektime_api/domain/feed/cache/GlobalFeedCacheRepository.java#L72-L75
  • docs/global-feed-design.md#L538-L547
🤖 Prompt for 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.

In
`@peektime-api/src/main/java/com/team/peektime_api/domain/feed/service/GlobalFeedService.java`
around lines 41 - 46, Limit cold-cache rebuilding to a single coordinated
execution shared with scheduled rebuilds: in GlobalFeedService at
peektime-api/src/main/java/com/team/peektime_api/domain/feed/service/GlobalFeedService.java:41-46,
guard the loadFromDb and rebuild flow with the common coordinator. In
GlobalFeedCacheRepository at
peektime-api/src/main/java/com/team/peektime_api/domain/feed/cache/GlobalFeedCacheRepository.java:72-75,
replace REBUILD_KEY for temporary rebuild data with a per-invocation unique key
and clean it up on failure. In docs/global-feed-design.md:538-547, scope the
lock-free statement to cache-hit requests only.

Comment on lines +24 to +25
// 리스너(즉시 전송)에게 주는 선공 유예 — 이 시간 안에는 폴러가 잡지 않는다
private static final int LISTENER_GRACE_SECONDS = 3;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail
fd -a 'RestClientConfig.java' peektime-api/src --exec cat {}

Repository: depromeet/18th-team5-server

Length of output: 1317


🏁 Script executed:

#!/bin/bash
set -euo pipefail

fd -a 'OutboxEvent.java|OutboxPollerV4.java|RestClientConfig.java' peektime-api/src --exec sh -c 'echo "===== $1 ====="; wc -l "$1"; ast-grep outline "$1" 2>/dev/null || true; sed -n "1,140p" "$1"' sh {}

Repository: depromeet/18th-team5-server

Length of output: 8907


리스너 유예 시간을 Admin RestClient 타임아웃과 맞춰 주세요.

RestClientConfig의 연결 타임아웃 5초 + 읽기 타임아웃 5초는 최대 10초까지 걸릴 수 있습니다. 하지만 OutboxEvent 생성자는 리스너 전송이 시작되었어도 3초 뒤부터 next_retry_at이 지난 행이 claimBatch() 대상이 됩니다. Admin 응답이 3~10초 구간이면 리스너와 폴러가 같은 이벤ートを 전달할 수 있어요. 중복 요청의 멱등성이 있다면 중복은 가능하지만, 폴러 주기와 함께 LISTENER_GRACE_SECONDS를 실제 요청 지연/타임아웃과 명확히 분리해 조정하거나 doc으로 이 전제를 기록해 주세요.

🤖 Prompt for 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.

In
`@peektime-api/src/main/java/com/team/peektime_api/global/outbox/entity/OutboxEvent.java`
around lines 24 - 25, Update OutboxEvent.LISTENER_GRACE_SECONDS to align with
the Admin RestClient’s maximum connection-plus-read timeout of 10 seconds, or
explicitly document the separate grace-period assumption alongside the constant.
Ensure the value and documentation prevent claimBatch() from taking an event
before the listener request can complete.

Comment on lines +51 to +63
@Column(name = "retry_count", nullable = false)
private int retryCount = 0;

@Column(name = "last_error", length = LAST_ERROR_MAX_LENGTH)
private String lastError;

// 이 시각이 되기 전에는 폴러 claim 대상에서 제외된다
// (신규: 리스너 선공 유예, 일시 실패: 백오프 예약 시각)
@Column(name = "next_retry_at", nullable = false)
private LocalDateTime nextRetryAt;

@Column(name = "sent_at")
private LocalDateTime sentAt;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail
echo "--- peektime-api Flyway migrations ---"
fd -e sql . peektime-api/src/main/resources/db/migration --exec echo {} \; --exec cat {}
echo "--- grep outbox_event across migrations ---"
rg -n -i 'outbox_event' peektime-api/src/main/resources/db/migration 2>/dev/null || echo "no match"

Repository: depromeet/18th-team5-server

Length of output: 336


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "--- repository top-level files/dirs ---"
git ls-files | sed 's#/.*##' | sort -u | head -80

echo "--- locate OutboxEvent.java ---"
fd -a 'OutboxEvent.java' . || true

echo "--- locate migration/resource dirs ---"
git ls-files | rg '(^|/)src/main/resources|db/migration|migration|flyway|schema|sql$' || true

echo "--- grep outbox_event across repository ---"
rg -n -i 'outbox_event|retry_count|last_error|next_retry_at|sent_at|idx_outbox_status_next_retry' . || true

Repository: depromeet/18th-team5-server

Length of output: 5599


기존 outbox_event 마이그레이션·백필을 추가하세요.

OutboxEvent의 retry_count, last_error, next_retry_at, sent_at은 엔티티에 매핑되어 있지만 현재 마이그레이션에는 outbox_event 테이블 구조를 보정하는 SQL이 없습니다. next_retry_at NOT NULL이 새로 적용되면 기존 READY/PROCESSING 행을 채우지 않으면 MySQL이 마이그레이션 단계에서 중단되거나, 백필 값이 현재 시각 이하가 아니라 새로 생성된 이벤트들만 claim 대상이 됩니다. 안전 기본값을 먼저 채우고, PR에서도 이 데이터 백필을 공유해 주세요.

🤖 Prompt for 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.

In
`@peektime-api/src/main/java/com/team/peektime_api/global/outbox/entity/OutboxEvent.java`
around lines 51 - 63, 기존 outbox_event 테이블을 보정하는 마이그레이션과 백필 SQL을 추가하세요.
retry_count, last_error, next_retry_at, sent_at 컬럼을 엔티티 매핑과 일치시키고,
next_retry_at을 NOT NULL로 적용하기 전에 기존 READY/PROCESSING 행에 안전한 기본값을 채우세요. 백필된
next_retry_at은 현재 시각 이하로 설정해 기존 이벤트도 즉시 claim 대상이 되도록 하며, 관련 데이터 백필을 PR의 마이그레이션
흐름에 포함하세요.

Comment on lines 73 to +101
public void markProcessing() {
this.status = OutboxStatus.PROCESSING;
}

// stuck PROCESSING 복구용. stuck은 실패가 아니라 결과 불명이므로 retryCount를 깎지 않고,
// nextRetryAt도 갱신하지 않는다 (이미 지난 시각이라 다음 폴링에서 바로 잡힘)
public void markReady() {
this.status = OutboxStatus.READY;
}
} No newline at end of file

public void markSent() {
this.status = OutboxStatus.SENT;
this.sentAt = LocalDateTime.now();
}

// 전송 실패 기록: 백오프 예약, 상한 초과 시 FAILED 승격
public void recordFailure(String reason) {
this.retryCount++;
this.lastError = truncate(reason);

if (this.retryCount > MAX_RETRY_COUNT) {
this.status = OutboxStatus.FAILED;
return;
}

this.status = OutboxStatus.READY;
int backoffMinutes = Math.min(BACKOFF_BASE_MINUTES * this.retryCount, BACKOFF_MAX_MINUTES);
this.nextRetryAt = LocalDateTime.now().plusMinutes(backoffMinutes);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail
fd -a 'BaseEntity.java' peektime-api/src --exec cat {}

Repository: depromeet/18th-team5-server

Length of output: 911


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== candidate files =="
fd -a 'OutboxEvent\.java|OutboxV4TransactionManager\.java|application.*\.ya?*ml|pom\.xml|build\.gradle' peektime-api/src peektime-api --exec sh -c 'echo "--- $1"; sed -n "1,220p" "$1"' sh {}

echo
echo "== search outbox usages =="
rg -n "OutboxEvent|OutboxV4TransactionManager|markProcessing|markReady|m.arkSent|recordFailure|recoverStuckProcessing|claimBatch|applyResults" peektime-api/src || true

echo
echo "== persistence/config search for lock settings =="
rg -n "optimistic|`@Version`|hibernate|dynamic_update|dynamic-update|ddl-auto|retryTransaction|OptimisticLockException|JPA|Jdbc|TransactionManager" peektime-api/src --glob '!**/target/**' || true

Repository: depromeet/18th-team5-server

Length of output: 38815


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
from pathlib import Path

files = [
    Path("peektime-api/src/main/java/com/team/peektime_api/global/outbox/entity/OutboxEvent.java"),
    Path("peektime-api/src/main/java/com/team/peektime_api/global/common/BaseEntity.java")
]
for p in files:
    text = p.read_text()
    print(f"=== {p} ===")
    print("has_Version_annotation:", "`@Version`" in text)
    print("includes_updatedAt_annotation:", "`@LastModifiedDate`" in text or "`@Column`(updateExpression" in text or "`@Column`(name = \"updated_at\"" in text)
    print("includes_dynamic_update:", "`@DynamicUpdate`" in text or "`@DynamicInsert`" in text)
    print("includes_lock_mode_or_lock_query:", any(s in text for s in ["LockModeType", "FOR UPDATE", "SKIP LOCKED"]))

root_text = Path("peektime-api/src/main/java/com/team/peektime_api/global/outbox/entity/OutboxEvent.java").read_text()
root_base = Path("peektime-api/src/main/java/com/team/peektime_api/global/common/BaseEntity.java").read_text()
print("all_Version_annotations:", [
    (p.name, i+1)
    for p in files for i, line in enumerate(open(p, encoding="utf-8")) if "`@Version`" in line
])
PY

Repository: depromeet/18th-team5-server

Length of output: 650


🌐 Web query:

Hibernate 6 JPA @Version optimistic locking UPDATE only version column documentation

💡 Result:

In Hibernate 6, the @Version annotation is used to enable optimistic locking, which operates by including the version column in the WHERE clause of an UPDATE statement to prevent lost updates [1][2]. Regarding the behavior of the UPDATE statement: 1. Default Behavior: By default, Hibernate generates an UPDATE statement that includes all columns of the entity [2]. When optimistic locking is enabled via @Version, the version column is automatically incremented in the SET clause and checked in the WHERE clause [1][2]. 2. Dynamic Updates: To restrict the UPDATE statement to only include columns that have actually changed (in addition to the version column), you can use the @DynamicUpdate annotation at the entity level [2][3]. Even with @DynamicUpdate enabled, Hibernate will still include the version column in the SET clause to increment it and in the WHERE clause to perform the optimistic lock check [2]. 3. Technical Constraint: It is not standard practice or supported to configure Hibernate to perform an UPDATE that modifies only the version column while excluding all other entity state changes if those changes are present in the Persistence Context. If you wish to force an increment of the version without modifying other fields, you should use explicit locking mechanisms like LockModeType.OPTIMISTIC_FORCE_INCREMENT or LockModeType.PESSIMISTIC_FORCE_INCREMENT [1][2]. In summary, Hibernate is designed to ensure data integrity; therefore, the version column is consistently managed as part of any update operation to the entity state [1][2]. If an entity is considered "dirty" (i.e., its state has changed), those changes are included in the generated SQL UPDATE, and the version is incremented accordingly [2].

Citations:


@Version 기반 낙관적 잠금을 추가해 재시도 데이터 소멸을 막아 주세요.

OutboxEvent와 BaseEntity 모두 @Version이 없으므로, applyResults()가 recordFailure()로 retryCount, lastError, nextRetryAt을 갱신한 뒤 recoverStuckProcessing()이 같은 row를 load 후 markReady()로 status만 덮어썼을 때 Hibernate가 두 변경분을 충돌 없이 저장할 수 있습니다.

OutboxEvent에 @Version 필드를 추가하고, 낙관적 잠금 충돌이 발생하면 실패 로그만 남기거나 재시도 전략으로 처리해 주세요. Hibernate의 @Version 동작은 공식 Hibernate 문서의 Optimistic Locking 섹션을 참고하면 좋습니다. 트랜잭션 경계를 짧게 분리한 V4 설계는 유지하면서 “누가 마지막에 쓰는가”를 락으로 정리하자면 더 안전합니다 😄

🤖 Prompt for 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.

In
`@peektime-api/src/main/java/com/team/peektime_api/global/outbox/entity/OutboxEvent.java`
around lines 73 - 101, OutboxEvent lacks optimistic locking, allowing concurrent
applyResults and recoverStuckProcessing updates to overwrite retry data. Add a
Hibernate `@Version` field to OutboxEvent, ensure its persistence mapping
participates in version checks, and handle the resulting optimistic-lock
exception in the relevant processing flow by logging the failure or applying the
existing retry strategy; keep the V4 short transaction boundaries unchanged.

Comment on lines +77 to +87
// stuck PROCESSING → READY 복구. 중복 전송을 감수하는 동작이며 Admin 멱등키 dedup이 안전을 보장
@Transactional
public int recoverStuckProcessing(LocalDateTime threshold) {
List<OutboxEvent> stuckEvents = outboxRepository.findStuckProcessing(threshold);

for (OutboxEvent event : stuckEvents) {
event.markReady();
}

return stuckEvents.size();
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

반복적인 stuck 복구가 retryCount를 늘리지 않아 FAILED 승격을 영원히 우회할 수 있습니다.

recoverStuckProcessing()은 stuck 이벤트를 retryCount 변경 없이 READY로만 되돌립니다. 주석대로 stuck은 "실패가 아니라 결과 불명"이므로 합리적인 설계 선택입니다. 다만 이 로직은 recordFailure()를 한 번도 거치지 않으므로, 같은 이벤트가 (예: 배포 중 반복 크래시로) 계속 PROCESSING → stuck → READY를 반복하면 retryCount는 0에서 절대 증가하지 않고, MAX_RETRY_COUNT도 절대 넘지 않아 FAILED로 승격되지 않습니다. 결과적으로 이 이벤트는 운영자에게 알림 한 번 없이 영원히 자동 재시도 루프에 머물 수 있습니다.

PR 설명에서도 "재시도 상한 및 알림 전제"를 핵심 검토 사항으로 짚고 있는 만큼, stuck 복구 횟수를 별도로 세거나, 생성 시각 기준 절대 만료 시간을 두어 일정 시간 이상 지나면 무조건 FAILED로 넘기는 안전장치를 고려해 주세요. 지금 설계는 "정상적인 장애"에는 훌륭하게 대응하지만, "반복적으로 뻗는 장애"라는 틈새를 하나 남겨두고 있어요 — 그 틈만 메우면 완벽할 것 같습니다!

🤖 Prompt for 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.

In
`@peektime-api/src/main/java/com/team/peektime_api/global/outbox/scheduler/v4/OutboxV4TransactionManager.java`
around lines 77 - 87, Update recoverStuckProcessing in
OutboxV4TransactionManager so repeated PROCESSING-to-READY recovery cannot
bypass the retry limit indefinitely. Track stuck-recovery attempts separately or
apply an absolute age-based expiration, and transition events that exceed the
configured safety threshold to FAILED while preserving the current READY
recovery behavior for eligible events.

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.

1 participant