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.
The 60-second answer
Section titled “The 60-second answer”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.
Mark and sweep
Section titled “Mark and sweep”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 cyclea = nil # the cycle is now unreachableGC.start # force a major collection (rarely appropriate in app code)Generational collection
Section titled “Generational collection”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 collectionsold_array << "fresh" # write barrier fires: old_array joins the remembered setThis 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 and compaction
Section titled “Incremental marking and compaction”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 mattersGC.count # number of collections so farGC.disable # dangerous: short benchmark scripts onlyGC.start # force a full collectionThe 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.
Memory bloat
Section titled “Memory bloat”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 insteadRSS 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 and the symbol table
Section titled “Symbols and the symbol table”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 tableSymbol.all_symbols.size # should be stable after bootStill avoid interning untrusted input; prefer string keys for data.
Follow-up questions
Section titled “Follow-up questions”- Why can’t MRI use reference counting?
- What is a write barrier and what breaks without one?
- How would you prove a Rails app leaks rather than fragments?
- What does
GC.compactdo, and when is it unsafe? - Why does RSS stay high after objects are collected?
Common traps
Section titled “Common traps”- Calling
GC.startin application code. It forces a full collection and kills throughput. - Assuming
GC.disableis safe. Memory grows without bound; micro-benchmarks only. - Blaming the GC for bloat it did not cause. Check
heap_live_slotsbefore tuning. - Thinking cycles leak. Mark and sweep handles cycles by design.
- Confusing heap slots with OS memory. Freeing slots does not return pages.