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
- Detect: Alerts fire for RSS > threshold or GC major count spike.
- Capture: Take heap dump (`ObjectSpace.dump_all`) and gather GC stats before mitigation.
- Mitigate: Scale horizontally or restart leak-prone workers while investigation continues.
- Analyse: Load dumps into
heapy/derailed, identify class growth, fix root cause. - 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.compactinbefore_forkto shrink heaps. - Monitor `RUBY_GC_HEAP_GROWTH_FACTOR` and adjust in small increments while watching CPU usage.
- Document changes in
doc/performance.mdso future incidents understand current GC settings.