All posts

Fix Infinite Loop in Ruby

Identify and resolve infinite loops in Ruby programs, including common issues with each, while loops, and ActiveRecord callbacks.

Tracking Down Infinite Loops in Ruby

Ruby's dynamic nature makes infinite loops particularly tricky. They often surface as processes that consume 100% CPU or gradually eat all available memory until the OOM killer strikes.

Classic While Loop Bug

Forgetting to increment a counter is the simplest case:

# Oops — i never changes
i = 0
while i < 10
  puts "Processing item #{i}"
  # Missing: i += 1
end

The fix is obvious, but in real codebases the loop variable might be buried in conditional branches.

ActiveRecord Callback Loops

In Rails, after_save callbacks that modify and save the record create silent infinite loops:

class Order < ApplicationRecord
  after_save :update_total

  def update_total
    # This triggers after_save again!
    update(total: line_items.sum(:price))
  end
end

Fix it by using update_column which skips callbacks:

def update_total
  update_column(:total, line_items.sum(:price))
end

Recursive Method Without Base Case

def flatten_tree(node)
  # Bug: doesn't check for leaf nodes
  node.children.flat_map { |child| flatten_tree(child) }
end

# Fixed
def flatten_tree(node)
  return [node] if node.children.empty?
  node.children.flat_map { |child| flatten_tree(child) }
end

Catching It Early

Bugsly can alert you to SystemStackError exceptions and abnormal process durations. Set up an alert rule for processes exceeding your expected timeout, and you'll catch these loops before they cascade into downtime.

Try Bugsly Free

AI-powered error tracking that explains your bugs. Set up in 2 minutes, free forever for small projects.

Get Started Free