Finding the Cause of a Memory Leak in Ruby

Finding the cause of a memory leak in Ruby

It looks like you are entering The Lost World here. I don’t think the problem is with c-bindings in racc either.

Ruby memory management is both elegant and cumbersome. It stores objects (named RVALUEs) in so-called heaps of size of approx 16KB. On a low level, RVALUE is a c-struct, containing a union of different standard ruby object representations.

So, heaps store RVALUE objects, which size is not more than 40 bytes. For such objects as String, Array, Hash etc. this means that small objects can fit in the heap, but as soon as they reach a threshold, an extra memory outside of the Ruby heaps will be allocated.

This extra memory is flexible; is will be freed as soon as an object became GC’ed. That’s why your testcase with big_string shows the memory up-down behaviour:

def report
puts 'Memory ' + `ps ax -o pid,rss | grep -E "^[[:space:]]*#{$$}"`
.strip.split.map(&:to_i)[1].to_s + 'KB'
end
report
big_var = " " * 10000000
report
big_var = nil
report
ObjectSpace.garbage_collect
sleep 1
report
# ⇒ Memory 11788KB
# ⇒ Memory 65188KB
# ⇒ Memory 65188KB
# ⇒ Memory 11788KB

But the heaps (see GC[:heap_length]) themselves are not released back to OS, once acquired. Look, I’ll make a humdrum change to your testcase:

- big_var = " " * 10000000
+ big_var = 1_000_000.times.map(&:to_s)

And, voilá:

# ⇒ Memory 11788KB
# ⇒ Memory 65188KB
# ⇒ Memory 65188KB
# ⇒ Memory 57448KB

The memory is not released back to OS anymore, because each element of the array I introduced suits the RVALUE size and is stored in the ruby heap.

If you’ll examine the output of GC.stat after the GC was run, you’ll find that GC[:heap_used] value is decreased as expected. Ruby now has a lot of empty heaps, ready.

The summing up: I don’t think, the c code leaks. I think the problem is within base64 representation of huge image in your css. I have no clue, what’s happening inside parser, but it looks like the huge string forces the ruby heap count to increase.

Hope it helps.

Want to determine whether we have memory leak in ROR

Because of garbage collection, ruby will never have the kind of memory leak that occurs in C/C++ where the program was supposed to free the memory it no longer needs but did not.

What can happen is runaway memory because you are holding on to references which you don't need. Typically this happens when you keep things in class instance collections but don't cull the list as things are unneeded or old.

Another thing which can happen is an interaction between ruby memory management and the OS memory allocator. There is a very good article, What causes Ruby memory bloat by Hongli Lai on this. This might be something you can do very little about since it is not a memory "leak" in your code.

A feature was added in ruby 2.7 which addresses the issue in Hongli Lai's article. The method is GC.compact which is not called automatically but will defragment the ruby heap.

How do I track down a memory leak in my Ruby code?

I did not find ruby-prof very useful when it came to locating memory leaks, because you need a patched Ruby interpreter. Tracking object allocation has become easier in Ruby 2.1. Maybe it is the best choice to explore this yourself.

I recommend the blog post Ruby 2.1: objspace.so by tmml who is one of the Ruby core developers. Basically you can fetch a lot of information while debugging your application:

ObjectSpace.each_object{ |o| ... }
ObjectSpace.count_objects #=> {:TOTAL=>55298, :FREE=>10289, :T_OBJECT=>3371, ...}

require 'objspace'
ObjectSpace.memsize_of(o) #=> 0 /* additional bytes allocated by object */
ObjectSpace.count_tdata_objects #=> {Encoding=>100, Time=>87, RubyVM::Env=>17, ...}
ObjectSpace.count_nodes #=> {:NODE_SCOPE=>2, :NODE_BLOCK=>688, :NODE_IF=>9, ...}
ObjectSpace.reachable_objects_from(o) #=> [referenced, objects, ...]
ObjectSpace.reachable_objects_from_root #=> {"symbols"=>..., "global_tbl"=>...} /* in 2.1 */

With Ruby 2.1 you can even start to track allocation of new objects and gather metadata about every new object:

require 'objspace'
ObjectSpace.trace_object_allocations_start

class MyApp
def perform
"foobar"
end
end

o = MyApp.new.perform
ObjectSpace.allocation_sourcefile(o) #=> "example.rb"
ObjectSpace.allocation_sourceline(o) #=> 6
ObjectSpace.allocation_generation(o) #=> 1
ObjectSpace.allocation_class_path(o) #=> "MyApp"
ObjectSpace.allocation_method_id(o) #=> :perform

Use pry and pry-byebug and start exploring the memory heap where you think it will probably grow, respectively try different segments in your code. Before Ruby 2.1 I always relied on ObjectSpace.count_objects and calculated the result's difference, to see if one object type grows in particularly.

The garbage collection works properly when the number of objects growing are retested back to a much smaller amount during the iterations as opposed to keep growing. The garbage collector should run all the time anyway, you can reassure yourself by looking into the Garbage Collector statistics.

From my experience this is either String or Symbol (T_STRING). Symbols before ruby 2.2.0 were not garbage collected so make sure your CSV or parts of it is not converted into symbols on the way.

If you do not feel comfortable, try to run your code on the JVM with JRuby. At least the memory profiling is a lot better supported with tools like VisualVM.

How to deal with memory leak in Ruby/Rails

This isn't really a case of a memory leak. You're just indescrimely loading data off the table which will exhaust the available memory.

The solution is to load the data off the database in batches:

City.find_each do |city|
city.update(data: city.neighbourhoods.sum(&:data))
end

If neighbourhoods.data is a simple integer you don't need to fetch the records in the first place:

City.update_all(
'data = (SELECT SUM(neighbourhoods.data) FROM neighbourhoods WHERE neighbourhoods.city_id = cities.id)'
)

This will be an order of magnitude faster and have a trivial memory consumption as all the work is done in the database.

If you REALLY want to load a bunch of records into rails then make sure to select aggregates instead of instantiating all those nested records:

City.left_joins(:neighbourhoods)
.group(:id)
.select(:id, 'SUM(neighbourhoods.data) AS n_data')
.find_each { |c| city.update(data: n_data) }

Memory leak in ruby

Operating as Designed

It's a leak if and only if the memory isn't returned to the system after Ruby exits. Since that's not the behavior you're describing, it's fair to say that your interpreter appears to be operating as designed.

See below for a little more about how Ruby's garbage collection works at a high level, and why your array-building is so memory intensive.

No Memory is Leaking

This is not a leak; this is how Ruby garbage collection works! It's basically a mark-and-sweep garbage collector, with some new support for compaction. At a high level, Ruby allocates memory for objects still in scope, and generally won't release the allocation until all references go out of scope.

Ruby's garbage collection isn't well-documented outside of source code, and the implementation is a bit more complex than what I described above. Furthermore, the garbage collection implementation can vary from release to release, and between different interpreters (e.g. JRuby and MRI) too! Still, it's sufficient to understand what you're seeing.

Basically, 100000000000.times do a.push([1]) end will push an element onto Array a 100 million times. As long as a is in scope, the memory won't be garbage collected. Even if you manually start the garbage collector routines after a goes out of scope, Ruby may or may not free the memory if the system isn't under memory pressure.

I wouldn't worry about this unless you have very long-lived processes that need to keep millions of records in active memory. If you do, a purpose-built cache or database (e.g. memcached, Redis) might be more efficient.

ruby/ruby on rails memory leak detection

Some tips to find memory leaks in Rails:

  • use the Bleak House plugin
  • implement Scout monitoring specifically the memory usage profiler
  • try another simple memory usage logger

The first is a graphical exploration of memory usage by objects in the ObjectSpace.

The last two will help you identify specific usage patterns that are inflating memory usage, and you can work from there.

As for specific coding-patterns, from experience you have to watch anything that's dealing with file io, image processing, working with massive strings and the like.

I would check whether you are using the most appropriate XML library - ReXML is known to be slow and believed to be leaky (I have no proof of that!). Also check whether you can memoize expensive operations.

Ruby code memory leak in loop

Try removing the lines from the bottom up, and seeing if the memory leak persists. It's possible that the Memory leak is coming from the find method, or possibly the JSON.parse (extremely unlikely), or the custom Queue data structure. If the memory leak is still there after removing all of the lines, it is likely coming from the worker itself and/or the program running the workers.

q = Queue.new("test")
while true do
m = q.dequeue # Finally remove this and stub the while true with a sleep or something
body = JSON.parse(m.body) # Then remove these two lines
user_id = body["Records"][0]
user = V2::User.find(user_id) # Remove the bottom two lines first
post = V2::Post.find(post_id)
end


Related Topics



Leave a reply



Submit