SystemStackError
RubyFATALCommonSystem
Stack overflow from infinite recursion
Quick Answer
Add a base case to recursive methods; convert deep recursion to iteration or use tail-call optimisation.
What this means
Raised when the call stack grows beyond its limit, almost always due to infinite or runaway recursion. It is a subclass of Exception. The default Ruby stack depth is typically around 10,000–15,000 frames.
Why it happens
- 1Recursive method with a missing or unreachable base case
- 2Circular method_missing delegation
- 3Accidental infinite loop that calls a method each iteration
Fix
Add an explicit base case
Add an explicit base case
def factorial(n) return 1 if n <= 1 # base case prevents infinite recursion n * factorial(n - 1) end
Why this works
The base case terminates recursion when n reaches 1, unwinding the stack cleanly.
Code examples
Infinite recursionruby
def boom boom end boom # SystemStackError: stack level too deep
Iterative alternativeruby
def sum_to(n) (1..n).reduce(0, :+) # no recursion, no stack risk end
Rescue (emergency only)ruby
begin
deeply_nested_operation
rescue SystemStackError => e
puts "Stack overflow: #{e.message}"
endSame error in other languages
Sources
Official documentation ↗
Ruby Core Documentation
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev