The project is in a healthy, maintained state
Thread-safe time-windowed rate tracker that records values into bucketed time slots. Supports rate calculation, sum, count, average, and percentile queries over a sliding window.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
 Dependencies
 Project Readme

philiprehberger-rate_window

Tests Gem Version Last updated

Time-windowed rate tracker with configurable resolution

Requirements

  • Ruby >= 3.1

Installation

Add to your Gemfile:

gem "philiprehberger-rate_window"

Or install directly:

gem install philiprehberger-rate_window

Usage

require "philiprehberger/rate_window"

tracker = Philiprehberger::RateWindow.new(window: 60, resolution: 1)

tracker.record(1)
tracker.record(5)
tracker.record(3)

tracker.rate      # => events per second over the window
tracker.sum       # => 9.0
tracker.count     # => 3
tracker.average   # => 3.0

Percentiles

tracker = Philiprehberger::RateWindow.new(window: 60, resolution: 1)
100.times { |i| tracker.record(i) }

tracker.percentile(50)   # => median value (with linear interpolation)
tracker.percentile(95)   # => 95th percentile
tracker.percentile(99)   # => 99th percentile
tracker.median           # => shortcut for percentile(50)

Min / Max

tracker = Philiprehberger::RateWindow.new(window: 60, resolution: 1)
tracker.record(5)
tracker.record(20)
tracker.record(3)

tracker.min   # => 3.0
tracker.max   # => 20.0

Histogram

tracker = Philiprehberger::RateWindow.new(window: 60, resolution: 1)
100.times { |i| tracker.record(i) }

tracker.histogram(buckets: 5)
# => [
#   { range: 0.0..20.0, count: ... },
#   { range: 20.0..40.0, count: ... },
#   ...
# ]

Custom Resolution

# 5-minute window with 10-second buckets
tracker = Philiprehberger::RateWindow.new(window: 300, resolution: 10)
tracker.record(42)
tracker.rate    # => rate per second over 5 minutes

Reset

tracker.reset
tracker.sum     # => 0.0
tracker.count   # => 0

API

Method Description
.new(window:, resolution:) Create a tracker with window (seconds) and bucket resolution
#record(value = 1) Record a value in the current time bucket
#rate Calculate rate per second over the window
#sum Sum of all values in the window
#count Number of recordings in the window
#average Average value per recording
#percentile(p) Calculate percentile (0-100) with linear interpolation
#median Shortcut for percentile(50)
#min Minimum recorded value in the window
#max Maximum recorded value in the window
#histogram(buckets: 10) Value distribution as array of { range:, count: } hashes
#reset Clear all recorded data

Development

bundle install
bundle exec rspec
bundle exec rubocop

Support

If you find this project useful:

Star the repo

🐛 Report issues

💡 Suggest features

❤️ Sponsor development

🌐 All Open Source Projects

💻 GitHub Profile

🔗 LinkedIn Profile

License

MIT