Ruby Logo

Memory Management & GC Tuning

Understand object allocation, tune Ruby’s garbage collector, and track down leaks.

Home Ruby Memory Management & GC Tuning

Memory Management & GC Tuning

Efficient memory usage keeps RubyDev services stable. Understand the Ruby garbage collector, track allocations, and respond quickly when memory consumption spikes.

GC metrics cheat sheet

Metric Meaning How we use it
`GC.stat(:heap_live_slots)` Number of live objects on the heap Track trend dashboards; rising slope hints at leaks
`GC.stat(:major_gc_count)` Old generation collections triggered High counts + CPU spikes → tune thresholds
`ObjectSpace.memsize_of(obj)` Approximate memory footprint of an object Audit large objects (JSON, binaries) before caching

Allocation tracking example

require 'objspace' ObjectSpace.trace_object_allocations do Recommendations::NextLessons.new(user).call end top_allocators = ObjectSpace.each_object(Class) .map { |cls| [cls, ObjectSpace.count_objects(T_HASH)[cls]] }

Use gems like memory_profiler or derailed_benchmarks hotspots for friendlier reports, then trace specific classes with ObjectSpace.

Incident response timeline

  1. Detect: Alerts fire for RSS > threshold or GC major count spike.
  2. Capture: Take heap dump (`ObjectSpace.dump_all`) and gather GC stats before mitigation.
  3. Mitigate: Scale horizontally or restart leak-prone workers while investigation continues.
  4. Analyse: Load dumps into heapy / derailed, identify class growth, fix root cause.
  5. Prevent: Add regression tests or memory alerts tied to the fix; update documentation.

GC tuning tips

  • Warm up application boots before traffic to populate caches and reduce first-request GC penalties.
  • For forked servers (Puma cluster), call GC.compact in before_fork to shrink heaps.
  • Monitor `RUBY_GC_HEAP_GROWTH_FACTOR` and adjust in small increments while watching CPU usage.
  • Document changes in doc/performance.md so future incidents understand current GC settings.

Quick Navigation

Related Topics

Video Tutorial

Watch and learn memory management & gc tuning

Pro Tip: After reading through the content above, watch this video to reinforce your understanding and see the concepts in action!