Skip to content

feat: add resource utilization middleware to monitor CPU and memory u… #1352

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from

Conversation

vkhinvasara
Copy link
Contributor

@vkhinvasara vkhinvasara commented Jun 17, 2025

Resource Utilization Thresholds: Sending 503 response if CPU/Memory thresholds exceed.

Description

This PR enhances our ingestion pipeline by implementing an overload protection mechanism during peak usage. Specifically, when CPU or memory utilization crosses predefined thresholds, the system will proactively reject further ingestion requests with an HTTP 503 (Service Unavailable) status. This prevents uncontrolled resource consumption and cascading failures.


File Changes

  • resource_check.rs: This is a middleware which checks resource utilization before every ingestion request.
  • modal/mod.rs : To wrap the above middleware.
  • http/mod.rs: To expose said middleware.

Summary by CodeRabbit

  • New Features
    • Introduced system resource monitoring that evaluates CPU and memory usage before processing HTTP requests, returning a 503 error when resources are over-utilized to maintain server stability.
    • Added configurable CPU and memory utilization thresholds accessible via command-line options and environment variables.
    • Enabled automatic startup and graceful shutdown of the resource monitor integrated with server lifecycle management.

Copy link
Contributor

coderabbitai bot commented Jun 17, 2025

Walkthrough

A new middleware for resource utilization checking was added to the HTTP handlers. The middleware monitors CPU and memory usage before processing requests, returning a 503 error if thresholds are exceeded. The middleware is registered in the HTTP server pipeline, and the necessary module declarations and imports were updated. Additionally, command-line options for configuring CPU and memory thresholds were introduced, and the resource monitor runs concurrently during server operation with proper startup and shutdown handling.

Changes

File(s) Change Summary
src/handlers/http/mod.rs Declared new public submodule resource_check.
src/handlers/http/modal/mod.rs Imported resource_check and inserted check_resource_utilization_middleware into middleware chain.
src/handlers/http/resource_check.rs Added middleware and background task to monitor CPU and memory usage, rejecting requests when thresholds exceeded.
src/cli.rs Added CLI options for CPU and memory utilization thresholds with validation and environment variable support.
src/handlers/http/modal/ingest_server.rs Initialized and shut down resource monitor within IngestServer lifecycle.
src/handlers/http/modal/server.rs Initialized and shut down resource monitor within server lifecycle alongside other background tasks.
src/option.rs Added validate_percentage function to validate percentage input for resource thresholds.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant ActixServer
    participant ResourceCheckMiddleware
    participant NextHandler

    Client->>ActixServer: Sends HTTP request
    ActixServer->>ResourceCheckMiddleware: Pass request to middleware
    ResourceCheckMiddleware->>ResourceCheckMiddleware: Check CPU & memory usage flag
    alt Usage within threshold
        ResourceCheckMiddleware->>NextHandler: Forward request
        NextHandler-->>Client: Respond
    else Usage exceeds threshold
        ResourceCheckMiddleware-->>Client: Return 503 Service Unavailable
    end
Loading
sequenceDiagram
    participant Server
    participant ResourceMonitorTask
    participant ShutdownSignal

    Server->>ResourceMonitorTask: spawn_resource_monitor(shutdown_rx)
    ResourceMonitorTask->>ResourceMonitorTask: Periodically check CPU & memory usage
    ResourceMonitorTask->>ResourceMonitorTask: Update global flag based on thresholds
    Server->>ShutdownSignal: Send shutdown signal on server stop
    ShutdownSignal->>ResourceMonitorTask: Terminate monitoring task
Loading

Poem

🐇 In tunnels deep where servers hum,
I watch the CPU and memory run.
If usage climbs, I gently say,
"Hold on, friend, no more today!"
With thresholds set and watchful eyes,
The server breathes, no overload sighs.
Hop, hop, hooray for balance wise! 🥕✨

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

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
Contributor

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

🧹 Nitpick comments (3)
src/handlers/http/resource_check.rs (2)

29-30: Hard-coded thresholds → move to configuration

CPU_UTILIZATION_THRESHOLD and MEMORY_UTILIZATION_THRESHOLD are compile-time constants.
Making them environment- or config-driven (e.g. PARSEABLE.options) allows tuning without redeploying.


57-58: Include Retry-After header for back-pressure friendliness

When returning 503 Service Unavailable, consider adding Retry-After to hint clients when to attempt again:

-return Err(ErrorServiceUnavailable(error_msg));
+let mut err = ErrorServiceUnavailable(error_msg);
+err.response_mut().headers_mut().insert(
+    http::header::RETRY_AFTER,
+    http::HeaderValue::from_static("30"), // seconds
+);
+return Err(err);

Small change, big UX improvement.

src/handlers/http/modal/mod.rs (1)

48-48: Import grouping

resource_check is added to the gigantic super::{…} list. No functional issue, but grouping related imports (middleware modules together) would aid readability.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 97e5d42 and 4fb2da7.

📒 Files selected for processing (3)
  • src/handlers/http/mod.rs (1 hunks)
  • src/handlers/http/modal/mod.rs (2 hunks)
  • src/handlers/http/resource_check.rs (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/handlers/http/modal/mod.rs (1)
src/handlers/http/resource_check.rs (1)
  • check_resource_utilization_middleware (34-76)
⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: Build Default aarch64-apple-darwin
  • GitHub Check: Quest Smoke and Load Tests for Standalone deployments
  • GitHub Check: coverage
  • GitHub Check: Quest Smoke and Load Tests for Distributed deployments
  • GitHub Check: Build Default x86_64-pc-windows-msvc
  • GitHub Check: Build Default x86_64-unknown-linux-gnu
  • GitHub Check: Build Default aarch64-unknown-linux-gnu
  • GitHub Check: Build Kafka aarch64-apple-darwin
  • GitHub Check: Build Kafka x86_64-unknown-linux-gnu
🔇 Additional comments (3)
src/handlers/http/resource_check.rs (1)

61-63: refresh_cpu_usage needs a delay between calls

sysinfo computes CPU load as a delta between two successive calls. When you perform refresh_cpu_usage() and immediately read global_cpu_usage() without any pause, the value is often ~0 %. If the static System suggestion above is not adopted, you’ll need at minimum:

sys.refresh_cpu();
tokio::time::sleep(Duration::from_millis(200)).await;
sys.refresh_cpu();
let cpu_usage = sys.global_cpu_usage();

Failing to do so will under-report utilisation and the middleware might never trigger.

src/handlers/http/mod.rs (1)

39-40: Module export looks good

Publicly exposing resource_check integrates the new middleware cleanly; no further action required.

src/handlers/http/modal/mod.rs (1)

115-118: To verify the relative cost and early‐exit behavior of each middleware, let’s locate their implementations:

#!/bin/bash
# Find the shutdown‐check middleware implementation
rg -n "fn check_shutdown_middleware" -n .

# Find the resource‐utilization middleware implementation
rg -n "fn check_resource_utilization_middleware" -n .

Copy link
Contributor

@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

♻️ Duplicate comments (1)
src/handlers/http/modal/ingest_server.rs (1)

129-132: Same duplication issue as in server.rs

See earlier comment – ensure the resource monitor is started exactly once per process.

🧹 Nitpick comments (5)
src/option.rs (1)

178-188: Unify percentage-validation helpers and numeric types

validate_percentage duplicates most of validate_disk_usage but returns f32 while the earlier helper uses f64.
Consider consolidating both into a single generic routine and sticking to one float type (prefer f64 throughout for higher precision and consistency).

src/handlers/http/modal/server.rs (2)

142-145: Guard against spawning multiple resource-monitor tasks

spawn_resource_monitor() is invoked here and again in ingest_server.rs.
If both server roles coexist in the same binary this will start two background loops polling the same SYS_INFO, doubling load and causing racy log noise.
Add a OnceCell/Lazy flag inside resource_check so the monitor is spawned only once.


158-159: Silently dropping the monitor task handle

The oneshot signal is sent, but the spawned task’s JoinHandle is not awaited. On orderly shutdown this may leak warnings if the task panics.
Store the handle and await it after sending the shutdown signal, similar to startup_sync_handle.

src/cli.rs (1)

320-338: Align threshold types with existing options

CPU and memory thresholds use f32 whereas --max-disk-usage-percent uses f64.
For a consistent public API (and to avoid accidental precision loss) consider switching these to f64 as well.

src/handlers/http/resource_check.rs (1)

33-34: Use AtomicBool for cheap lock-free reads

RESOURCE_CHECK_ENABLED is a single boolean read on every request. An AtomicBool with Ordering::Relaxed would avoid the async RwLock overhead and allocation per request.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4fb2da7 and 5ce1ab9.

📒 Files selected for processing (5)
  • src/cli.rs (1 hunks)
  • src/handlers/http/modal/ingest_server.rs (2 hunks)
  • src/handlers/http/modal/server.rs (3 hunks)
  • src/handlers/http/resource_check.rs (1 hunks)
  • src/option.rs (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (10)
  • GitHub Check: Build Default x86_64-unknown-linux-gnu
  • GitHub Check: Build Default x86_64-pc-windows-msvc
  • GitHub Check: Quest Smoke and Load Tests for Distributed deployments
  • GitHub Check: Build Default x86_64-apple-darwin
  • GitHub Check: Quest Smoke and Load Tests for Standalone deployments
  • GitHub Check: Build Default aarch64-apple-darwin
  • GitHub Check: Build Default aarch64-unknown-linux-gnu
  • GitHub Check: Build Kafka x86_64-unknown-linux-gnu
  • GitHub Check: Build Kafka aarch64-apple-darwin
  • GitHub Check: coverage

coderabbitai[bot]
coderabbitai bot previously approved these changes Jun 18, 2025
@vkhinvasara vkhinvasara requested a review from parmesant June 18, 2025 09:05
Copy link
Contributor

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

🧹 Nitpick comments (5)
src/handlers/http/resource_check.rs (5)

41-45: Thresholds captured once – runtime config changes are ignored

cpu_threshold and memory_threshold are read before the loop and never refreshed.
If these values are expected to be hot-reloaded (e.g. via SIGHUP or admin API), the monitor will keep using the stale numbers. Consider moving the reads inside the tick branch:

-        let cpu_threshold = PARSEABLE.options.cpu_utilization_threshold;
-        let memory_threshold = PARSEABLE.options.memory_utilization_threshold;
+        // fetched on every iteration to pick up dynamic config changes

51-58: spawn_blocking each tick is avoidable overhead

Sampling three numeric fields from sysinfo is cheap and already guarded by a Mutex.
Spawning a blocking task every 30 s creates overhead and needless thread context switches.

-                    let (used_memory, total_memory, cpu_usage) = tokio::task::spawn_blocking(|| {
-                        let sys = SYS_INFO.lock().unwrap();
-                        ...
-                    }).await.unwrap();
+                    let (used_memory, total_memory, cpu_usage) = {
+                        let sys = SYS_INFO.lock().unwrap();
+                        (sys.used_memory() as f32,
+                         sys.total_memory() as f32,
+                         sys.global_cpu_usage())
+                    };

If you still worry about blocking, wrap the initial /proc scan in a background task and keep subsequent reads cheap.


70-73: Promote heavy log line to debug! (or throttle)

Emitting a full resource report at info on every 30-second tick can flood production logs.
Either:

  1. change to debug!, or
  2. log only on state changes (already handled below), or
  3. throttle with tracing::info!(rate = ...).

Minor, but keeps logs actionable.


70-73: Prefer f64 for GB conversion to avoid precision loss

used_memory / total_memory are cast to f32, then divided by 1024³. Large byte counts can exceed f32’s 24-bit mantissa and lose precision (especially on >128 GiB hosts).

-                          used_memory / 1024.0 / 1024.0 / 1024.0, 
-                          total_memory / 1024.0 / 1024.0 / 1024.0);
+                          (used_memory as f64) / 1024f64.powi(3),
+                          (total_memory as f64) / 1024f64.powi(3));

89-90: Acquire write lock once to read & update flag

Two separate lock calls (read then write) introduce an avoidable race window.
Capture the previous value while holding the write lock:

-                    let previous_state = *RESOURCE_CHECK_ENABLED.read().await;
-                    *RESOURCE_CHECK_ENABLED.write().await = resource_ok;
+                    let mut guard = RESOURCE_CHECK_ENABLED.write().await;
+                    let previous_state = *guard;
+                    *guard = resource_ok;
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b58212f and f6a2517.

📒 Files selected for processing (1)
  • src/handlers/http/resource_check.rs (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
src/handlers/http/resource_check.rs (1)
Learnt from: vkhinvasara
PR: parseablehq/parseable#1352
File: src/handlers/http/resource_check.rs:70-74
Timestamp: 2025-06-18T08:43:30.100Z
Learning: The sysinfo crate (version 0.30+) returns memory values from `used_memory()` and `total_memory()` in bytes, not kilobytes. Converting bytes to GiB requires dividing by 1024³ (1,073,741,824). In older versions (pre-0.30), the methods returned kilobytes.
⏰ Context from checks skipped due to timeout of 90000ms (10)
  • GitHub Check: coverage
  • GitHub Check: Build Default aarch64-apple-darwin
  • GitHub Check: Build Default x86_64-pc-windows-msvc
  • GitHub Check: Build Kafka aarch64-apple-darwin
  • GitHub Check: Build Default x86_64-apple-darwin
  • GitHub Check: Build Default aarch64-unknown-linux-gnu
  • GitHub Check: Build Kafka x86_64-unknown-linux-gnu
  • GitHub Check: Build Default x86_64-unknown-linux-gnu
  • GitHub Check: Quest Smoke and Load Tests for Distributed deployments
  • GitHub Check: Quest Smoke and Load Tests for Standalone deployments
🔇 Additional comments (1)
src/handlers/http/resource_check.rs (1)

33-34: ```shell
#!/bin/bash
set -e

echo "=== Cargo.toml entries for Tokio ==="
rg -n '^\stokio\s=' --glob 'Cargo.toml' || echo "No direct Tokio entry in Cargo.toml"

echo
echo "=== Cargo.lock entries for Tokio ==="
rg -n '^tokio ' --glob 'Cargo.lock' || echo "No Tokio entries found in Cargo.lock"


</details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->

@vkhinvasara
Copy link
Contributor Author

vkhinvasara commented Jun 18, 2025

Example usage: cargo run local-store --cpu-utilization-threshold 80.0 --memory-utilization-threshold 80.0

@parmesant @nikhilsinhaparseable

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