Skip to content

fix(metrics): prevent unbounded growth of business_metrics#1262

Merged
LuigiGonnella merged 1 commit intomofa-org:mainfrom
ashnaaseth2325-oss:fix/metrics-business-metrics-unbounded-growth
Mar 17, 2026
Merged

fix(metrics): prevent unbounded growth of business_metrics#1262
LuigiGonnella merged 1 commit intomofa-org:mainfrom
ashnaaseth2325-oss:fix/metrics-business-metrics-unbounded-growth

Conversation

@ashnaaseth2325-oss
Copy link
Copy Markdown
Contributor

Summary

business_metrics was stored in a Vec where every call to record_business_metric() kept pushing new entries with no limit or cleanup.
Over time this could cause unbounded memory growth in long-running services.

This PR replaces the vector with a bounded VecDeque and adds MAX_BUSINESS_METRICS to cap the buffer size. When the limit is reached, the oldest metric is removed before inserting a new one.


Steps to Reproduce

  1. Run a service that records business metrics frequently.
  2. Call record_business_metric() repeatedly (e.g. per request).
  3. Memory usage keeps increasing because the metrics buffer never shrinks.

Fix

Use a bounded buffer instead of an unbounded vector.

if metrics.len() >= MAX_BUSINESS_METRICS {
    metrics.pop_front();
}
metrics.push_back(metric);

Also adds drain_business_metrics() so exporters can read and clear buffered metrics safely.


Verification

  • Ran cargo test -p mofa-foundation --lib metrics
  • Confirmed metrics are recorded correctly and buffer size stays within the defined limit.

Replace the unbounded Vec<BusinessMetrics> with a VecDeque capped at
10 000 entries. Oldest entries are evicted O(1) via pop_front() when
the limit is reached. Add drain_business_metrics() so exporters can
atomically read and clear the buffer each scrape interval.

Signed-off-by: ashnaaseth2325-oss <ashnaaseth2325@gmail.com>
@ashnaaseth2325-oss
Copy link
Copy Markdown
Contributor Author

Hi @mugiwaraluffy56 @LuigiGonnella.
Kindly take a look at this PR.
Thanks!

@LuigiGonnella
Copy link
Copy Markdown
Collaborator

good, concise PR.

@LuigiGonnella LuigiGonnella merged commit e2cd04d into mofa-org:main Mar 17, 2026
6 checks passed
@ashnaaseth2325-oss
Copy link
Copy Markdown
Contributor Author

Thank You!

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.

2 participants