Skip to content

Conversation

@NCookies
Copy link
Collaborator

@NCookies NCookies commented Aug 2, 2025

작업 내용

  • 발생하는 오버헤드에 비해 얻을 수 있는 성능적 이점이 적은 캐시를 제거함
  • 대신 mongodb에 복합 인덱스를 적용하고, TTL(6개월)을 설정했다.
  • 파이썬 스크립트로 데이터를 삽입하고 프론트 페이지에서 성능을 측정했다.
    • 백만 건의 알림 데이터 삽입 후 테스트 진행
    • 캐시를 사용했을 때와 사용하지 않았을 때의 성능 차이가 크게 나타나지 않음

참고 사항

  • 구현 및 테스트는 오래 전에 했었으나 우선순위가 밀려서 이제서야 적용함
  • 5분 기록 보드

Summary by CodeRabbit

  • 신규 기능

    • 알림 목록을 수동으로 요청하고 WebSocket 지연 시간을 측정하는 기능이 추가되었습니다.
    • MongoDB에 알림 데이터를 대량으로 생성하는 테스트용 스크립트가 추가되었습니다.
  • 버그 수정

    • 알림 서비스에서 Redis 캐시 및 관련 캐시 무효화 로직이 제거되었습니다.
  • 성능 개선

    • 알림 문서에 복합 인덱스와 만료 인덱스가 추가되어 조회 최적화 및 데이터 자동 삭제가 지원됩니다.

- 발생하는 오버헤드에 비해 얻을 수 있는 성능적 이점이 적은 캐시를 제거함
- 대신 mongodb에 복합 인덱스를 적용하고, TTL(6개월)을 설정했다.
- 파이썬 스크립트로 데이터를 삽입하고 프론트 페이지에서 성능을 측정했다.
@NCookies NCookies self-assigned this Aug 2, 2025
@NCookies NCookies added the enhancement New feature or request label Aug 2, 2025
@coderabbitai
Copy link

coderabbitai bot commented Aug 2, 2025

Walkthrough

Redis 캐싱 관련 구성, 서비스, 설정 코드가 모두 제거되었습니다. NotificationDocument에 MongoDB 복합 인덱스와 만료 인덱스가 추가되었습니다. chat-page.html에 알림 요청 및 지연 측정 기능이 도입되었습니다. 테스트용 MongoDB 알림 데이터를 생성하는 Python 스크립트가 새로 추가되었습니다.

Changes

Cohort / File(s) Change Summary
Redis 캐싱 구성 및 서비스 코드 제거
.../notification/config/NotificationRedisCacheConfig.java,
.../notification/service/NotificationService.java
Redis 캐시 설정 파일 및 관련 Bean, 서비스 내 RedisTemplate, 캐시 어노테이션, 캐시 무효화 로직 삭제.
MongoDB 인덱스 추가
.../notification/model/NotificationDocument.java
복합 인덱스(@CompoundIndexes) 및 createdAt 필드에 180일 만료 인덱스(@indexed(expireAfter="180d")) 추가.
알림 요청 및 지연 측정 기능 추가
src/main/resources/templates/chat-page.html
알림 요청 함수(requestNotifications) 및 WebSocket 알림 수신 시 지연 측정/로깅 기능 추가.
테스트 데이터 생성 스크립트 추가
src/test/resources/send_notifications.py
MongoDB에 알림 데이터 샘플을 생성/삽입하는 Python 스크립트 신규 추가.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Browser
    participant Server
    participant MongoDB

    User->>Browser: requestNotifications() 호출
    Browser->>Server: GET /api/notifications (with Auth)
    Server->>MongoDB: 알림 목록 쿼리
    MongoDB-->>Server: 알림 목록 반환
    Server-->>Browser: 알림 목록 응답
    Browser->>Browser: wsLatencyStart로 지연 측정
    Server-->>Browser: WebSocket으로 알림 전송
    Browser->>Browser: wsLatencyStart로 round-trip latency 계산 및 로그 출력
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested reviewers

  • Kimminu7
  • pokerbearkr

Poem

🐇
캐시를 걷어내고 인덱스를 더해,
알림의 흐름은 한결 가벼워졌죠.
지연 측정도 척척,
테스트 데이터도 뚝딱!
토끼는 오늘도 코드밭에서
깡충깡충,
변화의 발자국을 남깁니다.

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/notification-perf-test

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
src/test/resources/send_notifications.py (1)

21-24: 테스트 데이터 다양성 개선 제안

현재 이메일 생성 로직이 단순하여 실제 사용자 분포를 제대로 시뮬레이션하지 못할 수 있습니다.

더 현실적인 테스트 데이터를 위해 다음과 같이 개선할 수 있습니다:

+import string
+
 def random_email():
-    # 1부터 10까지 랜덤, 1일 때는 [email protected]
-    idx = random.randint(1, 10)
-    return "[email protected]" if idx == 1 else f"ttest{idx}@test.com"
+    # 더 다양한 이메일 패턴 생성
+    if random.random() < 0.1:  # 10% 확률로 고정 이메일
+        return "[email protected]"
+    
+    username = ''.join(random.choices(string.ascii_lowercase, k=random.randint(5, 10)))
+    domains = ["test.com", "example.org", "demo.net"]
+    domain = random.choice(domains)
+    return f"{username}@{domain}"
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fc99e55 and a0f5b5e.

📒 Files selected for processing (5)
  • src/main/java/org/ezcode/codetest/infrastructure/notification/config/NotificationRedisCacheConfig.java (0 hunks)
  • src/main/java/org/ezcode/codetest/infrastructure/notification/model/NotificationDocument.java (3 hunks)
  • src/main/java/org/ezcode/codetest/infrastructure/notification/service/NotificationService.java (2 hunks)
  • src/main/resources/templates/chat-page.html (2 hunks)
  • src/test/resources/send_notifications.py (1 hunks)
💤 Files with no reviewable changes (1)
  • src/main/java/org/ezcode/codetest/infrastructure/notification/config/NotificationRedisCacheConfig.java
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: chat26666
PR: ezcode-my/backend#37
File: src/main/java/org/ezcode/codetest/infrastructure/elasticsearch/repository/ProblemElasticsearchRepositoryDsl.java:10-10
Timestamp: 2025-06-06T19:56:27.759Z
Learning: When user chat26666 mentions that code was implemented in a previous PR but explanation was missing, they may submit a follow-up PR just to add documentation/explanation without the actual implementation code.
📚 Learning: in the ezcode-my/backend codebase, skills are managed by admin user chat26666 and skill changes happ...
Learnt from: chat26666
PR: ezcode-my/backend#74
File: src/main/java/org/ezcode/codetest/infrastructure/persistence/repository/game/mysql/skill/SkillRepositoryImpl.java:45-60
Timestamp: 2025-06-18T15:25:27.923Z
Learning: In the ezcode-my/backend codebase, skills are managed by admin user chat26666 and skill changes happen infrequently. Therefore, using `@CacheEvict(value = "skill", allEntries = true)` in SkillRepositoryImpl is acceptable despite the cache rebuild cost, as the performance impact is minimal due to low update frequency.

Applied to files:

  • src/main/java/org/ezcode/codetest/infrastructure/notification/service/NotificationService.java
🔇 Additional comments (7)
src/main/java/org/ezcode/codetest/infrastructure/notification/model/NotificationDocument.java (2)

24-26: 우수한 인덱스 설계

principalNamecreatedAt 필드에 대한 복합 인덱스는 알림 목록 조회 성능을 크게 향상시킬 것입니다. 사용자별 최신 알림 조회 패턴에 최적화된 설계입니다.


41-41: 적절한 데이터 보관 정책

180일 TTL 설정으로 약 6개월간 알림 데이터를 보관하는 것은 합리적입니다. 자동 정리를 통해 데이터베이스 크기를 관리하고 성능을 유지할 수 있습니다.

src/main/resources/templates/chat-page.html (2)

188-204: 우수한 성능 측정 구현

WebSocket을 통한 알림 요청-응답 지연시간 측정 기능이 잘 구현되었습니다. performance.now()를 사용한 정확한 시간 측정과 콘솔에서 직접 호출 가능한 전역 함수 노출이 개발자 경험을 향상시킵니다.


227-231: 정확한 지연시간 계산

WebSocket 콜백에서 라운드트립 지연시간을 정확히 계산하고 로깅하는 구현이 성능 분석에 도움이 될 것입니다. 측정 후 wsLatencyStart를 0으로 리셋하는 것도 적절합니다.

src/main/java/org/ezcode/codetest/infrastructure/notification/service/NotificationService.java (3)

24-28: 깔끔한 의존성 정리

Redis 캐시 의존성을 완전히 제거하고 MongoDB 저장소만 남긴 것이 PR 목표와 일치합니다. 캐시 오버헤드 대비 성능 이득이 미미하다는 분석 결과를 반영한 적절한 결정입니다.


30-46: MongoDB 직접 조회로 단순화

@Cacheable 어노테이션을 제거하고 MongoDB에서 직접 조회하도록 변경한 것이 올바릅니다. 복합 인덱스 추가와 함께 충분한 성능을 제공할 것으로 예상됩니다.


48-61: 캐시 무효화 로직 제거 확인

알림 생성과 읽음 처리에서 캐시 무효화 로직이 완전히 제거되어 코드가 단순해졌습니다. MongoDB 인덱스 기반 성능 최적화 전략과 일관성 있는 변경입니다.

@NCookies NCookies merged commit d712e78 into dev Aug 2, 2025
2 checks passed
@NCookies NCookies deleted the feature/notification-perf-test branch August 2, 2025 00:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants