Find Memory Leak in a Ruby on Rails Project

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 can I track down a memory leak in a rails app?

I managed to figure it out. I was instantiating runtime classes on each iteration which apparently do not get GC'd. Refactoring to not use Class.new fixed the problem.

So if anyone's googling this, Class.new creates memory leaks.

Find memory leaks in a Rails application

I'd try using passenger (which automatically restarts and manages rails instances that grow too large in memory - much easier than rebooting mongrels that have strayed off sane memory constraints). Also you might have luck with ruby enterprise edition fork of 1.8.7 which backports some memory management fixes from 1.9 (like allowing the VM to shrink when it's using less memory) - that change might have worked it's way back to normal 1.8.7 though, although I am not sure. The claim with REE is that you can reduce memory consumption with 33% for rails applications.

Ruby stuff generally tend to grow over time and need rebooting, with passenger it does that automatically for you. It's worked perfectly for me so I can really recommend it.

http://www.modrails.com/

It also has good memory analytic functions

http://www.modrails.com/documentation/Users%20guide%20Apache.html#_analysis_and_system_maintenance

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.

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) }

Tracing memory leak in Ruby on Rails 3 / Postgres / Apache Passenger application

Some good resources to help you track down the source of the leaks:

Newer:

Find memory leak in a Ruby on Rails project

Older:

ruby/ruby on rails memory leak detection

http://tomcopeland.blogs.com/juniordeveloper/2007/09/tracking-down-a.html

http://xdotcommer.wordpress.com/2009/03/03/tracking-down-a-memory-leak-performance-issues-in-rails/



Related Topics



Leave a reply



Submit