Skip to content

fix: process memory usage method high cpu utilization - #4455

Merged
atzoum merged 1 commit into
developfrom
fix.memoryFencingCpu
Jul 4, 2025
Merged

atzoum merged 1 commit into
developfrom
fix.memoryFencingCpu

Conversation

@atzoum

@atzoum atzoum commented Jul 4, 2025

Copy link
Copy Markdown
Contributor

Description

Updating memory usage every 100ms to avoid increased cpu utilization

@atzoum
atzoum requested review from a team and sivashanmukh as code owners July 4, 2025 08:34
@atzoum
atzoum requested review from a team, koladilip and sandeepdsvs July 4, 2025 08:34
@coderabbitai

coderabbitai Bot commented Jul 4, 2025 •

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • New Features
    • Introduced a configurable refresh period for memory usage checks, allowing users to adjust how frequently memory usage is sampled via an environment variable.
  • Tests
    • Added tests to verify periodic memory usage checks and correct behavior of the new refresh period setting.

Walkthrough

A configurable memoryUsageRefreshPeriod option was introduced to the memory fencing middleware, allowing control over how frequently memory usage is sampled. The middleware now caches memory usage and only refreshes it after the specified interval. Corresponding tests were added to verify the periodic sampling behavior.

Changes

File(s) Change Summary
src/index.ts Added support for MEMORY_FENCING_MEMORY_USAGE_REFRESH_PERIOD environment variable and passed new config.
src/middlewares/memoryFencing.ts Introduced memoryUsageRefreshPeriod option, updated middleware to cache memory usage and refresh periodically.
src/middlewares/tests/memoryFencing.test.ts Added a test verifying periodic memory usage checks based on the new refresh period configuration.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Middleware
    participant Process

    Client->>Middleware: Incoming request
    alt If refresh period elapsed
        Middleware->>Process: process.memoryUsage()
        Process-->>Middleware: heapUsed
        Middleware->>Middleware: Cache heapUsed and timestamp
    else If within refresh period
        Middleware->>Middleware: Use cached heapUsed
    end
    Middleware-->>Client: Allow or block request based on heapUsed
Loading

Possibly related PRs

Suggested reviewers

  • sivashanmukh

Suggestions for improvement:

  • Consider documenting the new environment variable in the project’s configuration documentation for clarity.
  • Monitor the impact of the refresh period on performance under high request rates to ensure optimal settings.
✨ Finishing Touches
  • 📝 Generate Docstrings

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 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.

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.

@atzoum atzoum changed the title chore: process.memoryUsage utilizing cpu chore: process memory usage method high cpu utilization Jul 4, 2025

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
src/middlewares/memoryFencing.ts (1)

14-14: Add JSDoc documentation for the new parameter.

The memoryUsageRefreshPeriod parameter lacks documentation, which breaks consistency with the existing interface documentation pattern.

 interface MemoryFenceOptions {
+  /**
+   * The interval in milliseconds between memory usage checks. 
+   * Defaults to 100ms to reduce CPU overhead from frequent memory sampling.
+   */
   memoryUsageRefreshPeriod?: number; // default 100ms
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between abd3d47 and 26c9405.

📒 Files selected for processing (3)
  • src/index.ts (1 hunks)
  • src/middlewares/__tests__/memoryFencing.test.ts (1 hunks)
  • src/middlewares/memoryFencing.ts (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (10)
  • GitHub Check: Check PR Title
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image ARM64
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image ARM64
  • GitHub Check: Code Coverage
  • GitHub Check: test_and_publish
  • GitHub Check: UT Tests
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (go)
🔇 Additional comments (3)
src/middlewares/memoryFencing.ts (1)

39-46: Well-implemented caching mechanism.

The caching logic correctly stores memory usage state outside the request handler, creating proper closure-based caching that persists across requests. The time-based refresh logic ensures memory usage is only sampled after the configured period, effectively reducing CPU overhead.

src/index.ts (1)

39-43: Clean configuration integration.

The environment variable parsing follows the established pattern and correctly defaults to 100ms, matching the middleware's default behavior. The configuration is properly integrated into the existing middleware setup.

src/middlewares/__tests__/memoryFencing.test.ts (1)

149-176: Comprehensive test coverage for the new caching functionality.

The test effectively validates the periodic memory checking behavior by:

  • Mocking time control to simulate passage of time
  • Verifying memory usage is cached and not called on every request
  • Testing the exact refresh threshold boundary (99ms vs 100ms)
  • Ensuring proper initialization behavior

This provides excellent coverage for the new optimization feature.

@atzoum atzoum changed the title chore: process memory usage method high cpu utilization fix: process memory usage method high cpu utilization Jul 4, 2025
@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@codecov

codecov Bot commented Jul 4, 2025 •

Copy link
Copy Markdown

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 91.21%. Comparing base (915d0bb) to head (26c9405).
Report is 5 commits behind head on develop.

Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #4455      +/-   ##
===========================================
- Coverage    91.22%   91.21%   -0.01%     
===========================================
  Files          639      639              
  Lines        33588    33615      +27     
  Branches      7931     7935       +4     
===========================================
+ Hits         30640    30662      +22     
- Misses        2681     2686       +5     
  Partials       267      267              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@sonarqubecloud

sonarqubecloud Bot commented Jul 4, 2025

Copy link
Copy Markdown

Comment thread src/middlewares/memoryFencing.ts Resolved
@atzoum
atzoum requested a review from koladilip July 4, 2025 08:46
@atzoum
atzoum enabled auto-merge (squash) July 4, 2025 10:28
@atzoum
atzoum merged commit d2bc6e7 into develop Jul 4, 2025
@atzoum
atzoum deleted the fix.memoryFencingCpu branch July 4, 2025 12:51
vinayteki95 pushed a commit that referenced this pull request Jul 8, 2025
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.

4 participants