Memory and garbage collection

suggest change

Ruby manages memory for you. You create objects, and the garbage collector (GC) frees them once nothing references them. You never call free, but memory still matters:

This article explains how CRuby (MRI) stores objects, how its GC works, which tools show what's going on, and how to avoid leaks and needless allocations. For finding which lines allocate the most, see Profiling. For measuring the speed of alternatives, see Benchmarks.

All examples were run with Ruby 4.0. Exact numbers depend on the Ruby version, platform and what was loaded before your code, so read them as illustrations.

How Ruby stores objects

Every Ruby object lives in a slot on a GC-managed heap page (64 KB). Since Ruby 3.2 there are several heaps with different slot sizes, so small objects (short strings, small arrays, objects with a few instance variables) fit entirely in their slot:

5.times { |i| puts "heap #{i}: #{GC.stat_heap(i, :slot_size)} bytes per slot" }
heap 0: 40 bytes per slot
heap 1: 80 bytes per slot
heap 2: 160 bytes per slot
heap 3: 320 bytes per slot
heap 4: 640 bytes per slot

Data that doesn't fit in the biggest slot (a 1,000 character string, an array with 10,000 elements) goes into a separate buffer allocated with malloc. The slot then holds a pointer to it.

Some values are not heap objects at all. nil, true, false, small integers (Integer values from -2**62 to 2**62 - 1 on 64-bit platforms), most Float values and static symbols are immediate values: they are encoded directly in the reference itself. Creating them allocates nothing:

def allocations
  before = GC.stat(:total_allocated_objects)
  yield
  GC.stat(:total_allocated_objects) - before
end
allocations { 1.times {} } # warm up

puts "integers: #{allocations { 1_000.times { |i| i * 2 } }}"
puts "floats:   #{allocations { 1_000.times { |i| i * 1.5 } }}"
puts "symbols:  #{allocations { 1_000.times { :ok } }}"
puts "bignums:  #{allocations { 1_000.times { |i| 2**64 + i } }}"
puts "strings:  #{allocations { 1_000.times { "item" } }}"
puts "arrays:   #{allocations { 1_000.times { |i| [i, i] } }}"
integers: 0
floats:   0
symbols:  0
bignums:  4001
strings:  1000
arrays:   1000

GC.stat(:total_allocated_objects) counts every object allocated since the process started, so the difference before and after a block is the number of objects the block created. We'll reuse this allocations helper below.

Each evaluation of a string literal like "item" creates a new String. With the # frozen_string_literal: true magic comment at the top of the file (or ruby --enable=frozen-string-literal), the literal is a single frozen object and the strings line drops to 0. See Immutability.

How the garbage collector works

CRuby uses a mark and sweep collector:

  1. Mark: starting from the roots (global variables, constants, the local variables of every live stack frame, and a few internal tables), follow every reference and mark each object reached.
  2. Sweep: walk the heap pages and free every slot that wasn't marked.

What counts is reachability, not whether your code will ever use the object again. An object referenced from a constant lives until the process exits.

On top of this basic scheme, the collector has three refinements:

You can watch the generational behavior. This loop creates half a million strings and keeps 1% of them:

keep = []
before = GC.stat.slice(:count, :minor_gc_count, :major_gc_count, :time)

500_000.times do |i|
  s = "temp #{i}"           # garbage right away
  keep << s if i % 100 == 0 # 1% survives
end

after = GC.stat.slice(:count, :minor_gc_count, :major_gc_count, :time)
after.each { |k, v| puts "#{k}: #{v - before[k]}" }
puts "kept: #{keep.size}"
p GC.latest_gc_info.slice(:major_by, :gc_by)
count: 146
minor_gc_count: 145
major_gc_count: 1
time: 15
kept: 5000
{major_by: nil, gc_by: :newobj}

146 collections took 15 ms in total, and all but one were cheap minor GCs. gc_by: :newobj says the last GC was triggered because the heap ran out of free slots for a new object. Other triggers are :malloc (too many bytes allocated with malloc since the last GC), :method (an explicit GC.start) and :stress.

Inspecting the GC with GC.stat

GC.stat returns a hash of counters for the whole process. You can also ask for a single key, as in GC.stat(:count), which allocates no hash. The most useful keys:

GC.start
s = GC.stat
puts "live objects:      #{s[:heap_live_slots]}"
puts "free slots:        #{s[:heap_free_slots]}"
puts "old objects:       #{s[:old_objects]}"
puts "heap pages:        #{s[:heap_eden_pages]}"
puts "allocated so far:  #{s[:total_allocated_objects]}"
puts "freed so far:      #{s[:total_freed_objects]}"
puts "GCs (minor/major): #{s[:minor_gc_count]}/#{s[:major_gc_count]}"
live objects:      18427
free slots:        8787
old objects:       14791
heap pages:        30
allocated so far:  40435
freed so far:      22008
GCs (minor/major): 2/3
Key Meaning
count, minor_gc_count, major_gc_count number of collections
time, marking_time, sweeping_time milliseconds spent in GC
heap_live_slots objects currently alive (including not yet collected garbage)
heap_free_slots empty slots ready for new objects
old_objects objects in the old generation
total_allocated_objects, total_freed_objects counters since process start
malloc_increase_bytes bytes allocated with malloc since the last GC

GC.stat_heap gives the same kind of numbers for each slot-size heap, and GC.latest_gc_info describes the most recent collection.

A steadily growing heap_live_slots after GC.start is the classic sign of a leak. A high time compared to the total run time means you should allocate less.

Controlling the GC

The GC runs automatically. A few methods let you intervene:

GC.start                     # full (major) GC right now
GC.start(full_mark: false)   # minor GC only
GC.count                     # number of GCs so far

GC.disable  # => false (returns true if it was already disabled)
GC.enable   # => true  (returns true if it was disabled)

You rarely need any of them in application code. GC.start is useful in tests and measurements (to start from a clean state) and in a forked server right before forking workers. GC.disable lets memory grow without limit, so use it only around short, measured sections and always re-enable it in an ensure.

Finalizers

ObjectSpace.define_finalizer registers a proc that runs after an object has been collected. The proc must not reference the object itself, otherwise the object stays reachable forever. Build the proc in a class method so it can't capture self:

class Resource
  def initialize(name)
    @name = name
    ObjectSpace.define_finalizer(self, self.class.finalizer(name))
  end

  # Build the proc in a class method so it doesn't capture self
  def self.finalizer(name)
    proc { |id| puts "finalizing #{name}" }
  end
end

3.times { |i| Resource.new("temp#{i}") }
kept = Resource.new("kept")
GC.start
puts "after GC.start"
finalizing temp1
finalizing temp2
after GC.start
finalizing temp0
finalizing kept

Notice that temp0 survived GC.start even though nothing references it. CRuby scans the machine stack conservatively: any word on the C stack that looks like a pointer to an object keeps that object alive. A stale copy of a recently used reference is enough. Remaining finalizers run when the process exits.

If the proc closes over self, Ruby warns you (run with -W):

# finalizer.rb
class Leaky
  def initialize
    # BAD: the block captures self, so the object is never collected
    ObjectSpace.define_finalizer(self, proc { puts "never runs early" })
  end
end
Leaky.new
finalizer.rb:5: warning: finalizer references object to be finalized
never runs early

Don't use finalizers to release resources such as files, sockets or locks. You don't know when, or in which order, they run. Use a block form that cleans up deterministically (File.open(path) { |f| ... }) or begin/ensure instead.

Weak references

A weak reference points to an object without keeping it alive. Ruby has three tools for this.

WeakRef

WeakRef (from the standard library) wraps an object and delegates method calls to it. Once the object is collected, calls raise WeakRef::RefError:

require "weakref"

kept = "x" * 1_000_000
strong = WeakRef.new(kept)        # `kept` also references this string
weak = Array.new(10) { WeakRef.new("y" * 1_000_000) }  # nothing else does

GC.start

puts "kept alive? #{strong.weakref_alive? ? "yes" : "no"}, size #{strong.size}"
puts "temporaries alive: #{weak.count(&:weakref_alive?)} of #{weak.size}"

begin
  weak.find { |w| !w.weakref_alive? }.size
rescue WeakRef::RefError => e
  puts "#{e.class}: #{e.message}"
end
kept alive? yes, size 1000000
temporaries alive: 0 of 10
WeakRef::RefError: Invalid Reference - probably recycled

Checking weakref_alive? and then calling a method is racy, because a GC can run in between. Rescue WeakRef::RefError instead.

ObjectSpace::WeakMap

ObjectSpace::WeakMap is a hash-like map where both keys and values are weak. An entry disappears when either one is collected. Keys are compared by identity (equal?), not by eql?, so it works best with symbols, frozen string literals or other objects you pass around by reference.

A typical use is handing out one shared instance per value without keeping unused instances alive forever:

# Hand out one shared instance per value, without keeping unused ones alive
class Color
  attr_reader :name

  REGISTRY = ObjectSpace::WeakMap.new

  def self.for(name)
    REGISTRY[name] ||= new(name)
  end

  def initialize(name) = @name = name
end

red = Color.for(:red)
puts red.equal?(Color.for(:red))

1000.times { |i| Color.for(:"tmp#{i}") }
puts "before GC: #{Color::REGISTRY.keys.size}"
GC.start
puts "after GC:  #{Color::REGISTRY.keys.size}"
p Color::REGISTRY.keys
true
before GC: 563
after GC:  2
[:red, :tmp999]

:red stays because the local variable red holds its Color. The automatic GCs during the loop already removed most temporary entries, and GC.start removed the rest except :tmp999, the last one created, which a stale reference on the stack still keeps alive. That's conservative stack scanning again, and it's why code using weak references must never depend on exactly when an object goes away.

ObjectSpace::WeakKeyMap

ObjectSpace::WeakKeyMap (Ruby 3.3+) has weak keys and strong values, and compares keys with eql? and hash like a regular Hash. Use it to attach extra data to objects you don't own, without preventing their collection:

METADATA = ObjectSpace::WeakKeyMap.new

kept = +"request-1"
METADATA[kept] = { started: 1 }
10.times { |i| METADATA[+"temp-#{i}"] = { started: i } }
GC.start

p METADATA[kept]
p METADATA[+"request-1"]   # keys are compared with eql?, like Hash
p (0...10).count { |i| METADATA.key?("temp-#{i}") }
{started: 1}
{started: 1}
0
Keys Values Key comparison
Hash strong strong eql?
ObjectSpace::WeakMap weak weak equal? (identity)
ObjectSpace::WeakKeyMap weak strong eql?

Memory leaks in a garbage-collected language

Ruby can't free an object that is still reachable. Leaks in Ruby are almost always a long-lived object that keeps collecting references.

Unbounded caches and registries

A hash in a constant, a class variable or a class-level instance variable lives as long as the process. If its keys are unbounded (user ids, URLs, request parameters), it grows forever:

class PriceService
  CACHE = {}   # lives as long as the class: forever

  def price(product_id, user_id)
    CACHE[[product_id, user_id]] ||= compute(product_id, user_id)
  end

  private def compute(p, u) = "price-#{p}-#{u}"
end

svc = PriceService.new
5.times do |round|
  20_000.times { |i| svc.price(i % 100, round * 20_000 + i) }  # new user ids
  GC.start
  puts "round #{round}: live objects #{GC.stat(:heap_live_slots)}, cache #{PriceService::CACHE.size}"
end
round 0: live objects 58465, cache 20000
round 1: live objects 98475, cache 40000
round 2: live objects 138475, cache 60000
round 3: live objects 178475, cache 80000
round 4: live objects 218475, cache 100000

Live objects grow by 40,000 per round (one key array and one string per entry) and never go down. Fix it with a size limit (LRU), a TTL or a cache scoped to a request. See Caching. Other common offenders are observer lists that subscribers never leave, @@class_variables collecting instances, and log or metrics buffers that are never flushed.

Closures that capture more than you think

A block, proc or lambda keeps its entire surrounding scope alive, not just the variables it uses:

require "weakref"

def counter_for(rows)
  count = rows.size
  -> { count }                 # also captures `rows`
end

def counter_for_fixed(rows)
  make_counter(rows.size)
end

def make_counter(count) = -> { count }

refs = []
counters = []
2.times do |i|
  rows = Array.new(100_000) { |j| j }
  refs << WeakRef.new(rows)
  counters << (i == 0 ? counter_for(rows) : counter_for_fixed(rows))
end
rows = nil
GC.start

puts "leaky lambda keeps rows alive: #{refs[0].weakref_alive? ? "yes" : "no"}"
puts "fixed lambda keeps rows alive: #{refs[1].weakref_alive? ? "yes" : "no"}"
p counters.map(&:call)
p counters[0].binding.local_variables
leaky lambda keeps rows alive: yes
fixed lambda keeps rows alive: no
[100000, 100000]
[:rows, :count]

The lambda created inside counter_for keeps the binding of that call, including rows (100,000 elements) that it never reads. Create long-lived lambdas (callbacks, define_method bodies, values stored in a hash) in a small method that receives only what they need.

Symbols

Symbols created dynamically with to_sym or :"#{...}" are garbage collected since Ruby 2.2, so turning user input into symbols no longer leaks memory. Symbols that appear literally in source code (:name) and those used as method names stay forever, but your program contains a fixed number of them.

Allocating less

Every object you allocate must be freed later. Reducing allocations in a hot loop often speeds it up more than any other change, because it also cuts GC time. Using the allocations helper from above:

words = Array.new(1_000) { |i| "w#{i}" }

puts "+=          #{allocations { s = +""; words.each { |w| s += w } }}"
puts "<<          #{allocations { s = +""; words.each { |w| s << w } }}"
puts "join        #{allocations { words.join }}"
puts "map.select  #{allocations { words.map(&:upcase).select { |w| w.end_with?("7") } }}"
puts "filter_map  #{allocations { words.filter_map { |w| w.upcase if w.end_with?("7") } }}"
puts "map+sum     #{allocations { words.map(&:size).sum }}"
puts "sum block   #{allocations { words.sum(&:size) }}"
+=          1003
<<          2
join        2
map.select  2003
filter_map  1104
map+sum     3
sum block   1
# chilled.rb
s = "abc"
s << "d"
p s
chilled.rb:3: warning: literal string will be frozen in the future (run with --debug-frozen-string-literal for more information)
"abcd"

Don't apply these everywhere. Measure first (see Profiling), then optimize the few loops that matter.

Looking at the heap with ObjectSpace

The objspace extension adds methods for inspecting live objects:

require "objspace"

Point = Struct.new(:x, :y)
points = Array.new(5_000) { |i| Point.new(i, i) }

GC.start
counts = ObjectSpace.count_objects
puts "T_STRING: #{counts[:T_STRING]}, T_STRUCT: #{counts[:T_STRUCT]}, FREE: #{counts[:FREE]}"
puts "Point instances: #{ObjectSpace.each_object(Point).count}"

top = ObjectSpace.count_objects_size.reject { |k, _| k == :TOTAL }.max_by(3) { |_, v| v }
top.each { |type, bytes| puts "#{type}: #{bytes / 1024} KB" }

puts "short string: #{ObjectSpace.memsize_of("hello")} bytes"
puts "long string:  #{ObjectSpace.memsize_of("x" * 1_000)} bytes"
puts "empty Hash:   #{ObjectSpace.memsize_of({})} bytes"
puts "Hash of 100:  #{ObjectSpace.memsize_of((1..100).to_h { [it, it] })} bytes"
T_STRING: 8739, T_STRUCT: 5010, FREE: 6897
Point instances: 5000
T_IMEMO: 1558 KB
T_DATA: 530 KB
T_STRING: 528 KB
short string: 40 bytes
long string:  1041 bytes
empty Hash:   160 bytes
Hash of 100:  3488 bytes

To find which line allocated an object, and to dump the whole heap to a file for leak hunting, see the ObjectSpace section in Profiling.

Process memory and why it doesn't shrink

GC.stat counts objects, but the operating system sees the process's resident set size (RSS). On Linux you can read it from /proc:

def rss_mb
  kb = File.read("/proc/self/status")[/^VmRSS:\s+(\d+)/, 1].to_i
  kb / 1024.0
end

def report(label)
  s = GC.stat
  puts format("%-15s RSS %5.1f MB  live %7d  pages used %4d of %4d",
              label, rss_mb, s[:heap_live_slots], s[:heap_eden_pages], s[:heap_allocated_pages])
end

report("start")
data = Array.new(1_000_000) { |i| "row #{i} " * 4 }
report("after allocate")
data = nil
GC.start
report("after GC")
start           RSS  14.6 MB  live   20937  pages used   35 of   35
after allocate  RSS 117.8 MB  live 1121841  pages used 1311 of 1459
after GC        RSS  95.8 MB  live   18742  pages used   36 of 1230

After the GC almost all objects are gone and only 36 pages are in use, but most of the empty pages are still allocated and RSS barely dropped. Ruby keeps empty pages around to reuse them for the next burst of allocations, and releases them to the OS slowly. malloc behaves similarly with the buffers of big strings and arrays.

The practical consequence: a Ruby process's memory use is set by its peak, not its average. One request that loads 500 MB of records leaves the process at 500 MB. Process data in batches (find_each in Active Record, each_slice, streaming parsers) to keep the peak low.

On Linux, glibc malloc can fragment badly in multi-threaded programs such as Puma or Sidekiq. Two common remedies:

Both often reduce memory use of a threaded server by 20-40%. Measure with your own workload.

Compaction

Freed slots leave holes in heap pages. A page can be released only when it's completely empty, so a few survivors can pin many pages. GC.compact moves live objects together and fixes all references to them:

data = Array.new(200_000) { |i| "item #{i}" }
data.select!.with_index { |_, i| i % 10 == 0 }   # free 90%, leaving holes
GC.start

pages = GC.stat(:heap_eden_pages)
GC.compact
puts "pages: #{pages} -> #{GC.stat(:heap_eden_pages)}"
puts "moved objects: #{GC.stat(:total_moved_objects)}"
pages: 156 -> 38
moved objects: 20233

Compaction is most useful in pre-forking servers (Puma in cluster mode, Unicorn): compact once in the parent after loading the application and right before forking. The workers then share more memory pages with the parent through copy-on-write. A common way is to call GC.compact in the server's before_fork hook.

GC.auto_compact = true makes every major GC also compact. It adds overhead to each major GC and is off by default.

Tuning with environment variables

The GC reads its starting parameters from environment variables. The defaults suit small scripts, so a large application allocates many objects during boot and runs many GCs while the heap grows. Giving it a bigger initial heap avoids that:

# boot.rb
t = Process.clock_gettime(Process::CLOCK_MONOTONIC)
objects = Array.new(2_000_000) { Object.new }
ms = (Process.clock_gettime(Process::CLOCK_MONOTONIC) - t) * 1000
puts "GC runs: #{GC.count}, GC time: #{GC.stat(:time)} ms, total: #{ms.round} ms"
$ ruby boot.rb
GC runs: 17, GC time: 93 ms, total: 286 ms
$ RUBY_GC_HEAP_0_INIT_SLOTS=2100000 ruby boot.rb
GC runs: 1, GC time: 0 ms, total: 205 ms

Object.new with no instance variables uses the 40 byte heap 0. There are variables for each heap (RUBY_GC_HEAP_0_INIT_SLOTS to RUBY_GC_HEAP_4_INIT_SLOTS). Check GC.stat_heap after your app has booted to see how many slots each heap actually needs.

Variable Effect
RUBY_GC_HEAP_n_INIT_SLOTS initial number of slots in heap n
RUBY_GC_HEAP_GROWTH_FACTOR how fast the heap grows (default 1.8)
RUBY_GC_HEAP_GROWTH_MAX_SLOTS cap on slots added in one growth step
RUBY_GC_HEAP_FREE_SLOTS_MIN_RATIO grow the heap if fewer slots than this are free after GC
RUBY_GC_MALLOC_LIMIT, RUBY_GC_MALLOC_LIMIT_MAX malloc bytes that trigger a minor GC
RUBY_GC_OLDMALLOC_LIMIT, RUBY_GC_OLDMALLOC_LIMIT_MAX malloc bytes by old objects that trigger a major GC

At run time, GC.config reads and changes some settings. For example GC.config(rgengc_allow_full_mark: false) stops the GC from starting major collections on its own. A latency-sensitive server can then run GC.start at a convenient moment, such as between requests. Ruby 3.4 also added a modular GC: a Ruby built with --with-modular-gc can load an alternative collector selected with RUBY_GC_LIBRARY.

Tune only with measurements from production-like load. Wrong settings make memory use or pause times worse.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents