Debugging a Stuck or Slow Ruby Program
Last updated March 20, 2023
When a Ruby program doesn’t crash but hangs indefinitely or becomes very slow, it can be difficult to debug. Add a sampling profiler to see where the program hangs or slows down.
You can add a crude sampling profiler to any Ruby application. Spin up a thread in the background and report the backtrace of all executing threads. For example, if your application hangs during deployment, add this code to an initializer in config/initializers/sampling_profiler.rb
:
Thread.new do
loop do
sleep 10 # seconds
puts "=" * 80;
Thread.list.each.with_index { |t, i| puts "== Thread #{i}"; puts t.backtrace }
end
end
In this example, the location of all executing code prints out every 10 seconds. The location gives you a hint of where the program hangs or slows down.
After isolating that code, you can add additional debugging statements or attempt to remediate the problem directly.