Skip to content

Garbage Collector

Ruby allocates everything on the heap: every string, array and object. There is no manual free. The collector decides what is unreachable and returns it to the allocator. This matters when a Rails process grows to 1.5 GB and nobody changed any code.

MRI uses mark and sweep. Mark traverses from roots — stack, globals, constants, class hierarchy — and marks everything reachable; sweep frees the unmarked slots. Modern MRI adds generational collection: most objects die young, so a minor GC scans only the young generation and promotes survivors to old, while a major GC scans everything. Write barriers keep the remembered set correct when an old object starts pointing at a young one. Collection is also incremental, splitting marking into steps to shorten pauses.

Roots are the stack, globals, constants, the class table and C extension references. Mark walks everything reachable from them; sweep walks the heap and frees slots that were not marked. “Reachable” defines alive, so a cycle of objects that only reference each other is collected — there is no reference counting and no cycle leak.

a = []
a << a # self-reference, a cycle
a = nil # the cycle is now unreachable
GC.start # force a major collection (rarely appropriate in app code)

The weak generational hypothesis: most objects die young. A request allocates thousands of short-lived strings; config and connection pools live forever.

Generation Contents Collected by
Young (new) Recently allocated objects Minor GC, often
Old Objects that survived several minor GCs Major GC, rarely

A minor GC only scans young pages, so it must not miss references from old objects to young ones. The write barrier records every old object that stores a reference to a young object in a remembered set, which minor GC scans as extra roots.

old_array = [] # promoted to old after surviving collections
old_array << "fresh" # write barrier fires: old_array joins the remembered set

This is invisible but has a cost: writing into long-lived structures (global caches, class-level arrays) is more expensive than writing into short-lived ones.

Incremental marking (2.2+) interleaves marking with your code, shortening pauses. GC.compact (2.7+) defragments the heap, improving locality — but objects move, so C extensions holding raw pointers are at risk.

GC.stat
# => { count: 12, minor_gc_count: 9, major_gc_count: 3,
# heap_live_slots: 184320, heap_free_slots: 20211,
# total_allocated_objects: 2891233, ... }
GC.stat(:heap_live_slots) # objects currently alive — the number that matters
GC.count # number of collections so far
GC.disable # dangerous: short benchmark scripts only
GC.start # force a full collection

The metric to watch is heap_live_slots over time. If it climbs under steady traffic you have a leak: an unbounded cache, a class variable accumulating objects, a growing array of subscribers. If malloc_increase_bytes keeps triggering major GCs, you have malloc pressure from strings and buffers.

A process that grows and never shrinks is the common production complaint. Causes:

  • Unbounded caches keyed by user input.
  • Symbols from user input. GC-able since Ruby 2.2, but still a DoS vector.
  • Fragmentation. Free slots exist but are the wrong size; pages never return to the OS.
  • Large temporary strings. Reading a 200 MB file into memory, or building it with +=.
  • Retained references. A stored block captures self, keeping the whole object graph alive.
result = ""
lines.each { |l| result += l } # O(n²) allocation
result = +""
lines.each { |l| result << l } # mutate a buffer instead

RSS rarely shrinks after GC because malloc keeps free pages. That is why Puma and Sidekiq restart workers after N requests, and why jemalloc is a common LD_PRELOAD in Ruby deployments.

Symbols were immortal before Ruby 2.2, so "user_#{id}".to_sym in a loop leaked permanently. Since 2.2 dynamically created symbols are collected, and since 2.3 the symbol table is GC-managed.

params.keys.map(&:to_sym) # a request with random keys still churns the table
Symbol.all_symbols.size # should be stable after boot

Still avoid interning untrusted input; prefer string keys for data.

  1. Why can’t MRI use reference counting?
  2. What is a write barrier and what breaks without one?
  3. How would you prove a Rails app leaks rather than fragments?
  4. What does GC.compact do, and when is it unsafe?
  5. Why does RSS stay high after objects are collected?
  • Calling GC.start in application code. It forces a full collection and kills throughput.
  • Assuming GC.disable is safe. Memory grows without bound; micro-benchmarks only.
  • Blaming the GC for bloat it did not cause. Check heap_live_slots before tuning.
  • Thinking cycles leak. Mark and sweep handles cycles by design.
  • Confusing heap slots with OS memory. Freeing slots does not return pages.