Skip to content

Repository files navigation

maxprocs-ruby CIGem Version

A lightweight Ruby gem that detects CPU quota from Linux cgroups and returns the appropriate number of processors.

This is a Ruby equivalent of Go's uber-go/automaxprocs.

Problem

Ruby's Etc.nprocessors does not consider cgroup CPU quota - it returns the host's CPU count. In container environments (e.g., Docker/Kubernetes), the actual available CPU count differs from the host's CPU count.

For example, this causes Puma/Sidekiq worker counts to be excessive, leading to CPU throttling.

# On a 64-core host with 2 CPU limit containerEtc.nprocessors# => 64 (host CPUs, not what you want)Maxprocs.count# => 2 (container limit, what you want)

Installation

Add this line to your application's Gemfile:

gem'maxprocs'

And then execute:

$ bundle install

Or install it yourself as:

$ gem install maxprocs

Synopsis

require'maxprocs'# Get CPU count considering cgroup quota (Integer)Maxprocs.count# => 2# Get raw quota value (Float or nil)Maxprocs.quota# => 2.5 (nil if unlimited)# Check if CPU is limitedMaxprocs.limited?# => true/false# Get cgroup versionMaxprocs.cgroup_version# => :v1, :v2, or :none# Clear cache (for testing)Maxprocs.reset!# Rounding optionsMaxprocs.count(round: :floor)# => 2Maxprocs.count(round: :ceil)# => 3

API Reference

MethodReturn TypeDescription
Maxprocs.count(round:)IntegerCPU count (minimum 1). round: :floor (default) or :ceil
Maxprocs.quotaFloat or nilRaw quota value, nil if unlimited
Maxprocs.limited?Booleantrue if CPU quota is set
Maxprocs.cgroup_versionSymbol:v1, :v2, or :none
Maxprocs.reset!voidClear cached values

Use maxprocs when you only need cgroup-aware CPU count detection and want to minimize dependencies.

Limitations

  • On macOS/Windows, always falls back to Etc.nprocessors
  • cpu.shares not supported: Only cpu.cfs_quota_us/cpu.max are read (shares are relative weights, not absolute limits)
  • Direct cgroup only: Does not traverse parent cgroups
  • Some platforms return -1: Some environments may return unlimited quota

Requirements

  • Ruby 3.2+

Development

bundle install
bundle exec rake

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/moznion/maxprocs-ruby.

Related Projects

About

A lightweight Ruby gem that detects CPU quota from Linux cgroups and returns the appropriate number of processors

Resources

Stars

4 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages