SystemStackError: stack level too deep

Problem

You receive the error message SystemStackError: stack level too deep on the Error details page in your APM UI.

In addition, because of a bug in Ruby versions 2.1 and lower, you might receive only a one-line stack trace that points to the Ruby agent as the issue.

Solution

In most cases, the Ruby agent is not the underlying issue. The issue is that alias_method and Module#prepend work together only in particular situations and can cause non-terminating recursions when not used together properly.

  1. Upgrade to Ruby version 2.2 or higher to fix the one-line stack trace bug. Then, review the full stack trace to see if the Ruby agent is the issue.

    If you can't upgrade, refer to the URL included in the SystemStackError message to troubleshoot the issue or disable the Ruby agent to see if the problem disappears.

  2. If the Ruby agent is not the cause of the error, look for evidence of non-terminating recursions including the following:
    • You don't find new_relic near the top of the trace.
    • You see repeating patterns in the trace.
  3. If you see evidence of a recursion, make sure that alias_method and Module#prepend are compatible with each other when used on the same method.
    When used in ActiveRecord 5 code

    Upgrade to Ruby agent version 3.17.2 or higher.

    When used outside of ActiveRecord 5 code

    • Verify that your app always calls alias_method before Module#prepend when used on the same method.
    • Also, check to see if your app calls Module#prepend before the Ruby agent calls alias_method on the same method. If so, follow the recommendations in the New Relic blog post about resolving Module#prepend and alias_method conflicts.

Cause

When your app uses Module#prepend on a method that the Ruby agent later uses an alias_method on, it creates a non-terminating recursion and throws the SystemStackError: stack level too deep error.

If you upgraded to Rails 5, which deprecated alias_method_chain, you might have replaced alias_method with Module#prepend, and that could be the source of your issue.

For more help

Recommendations for learning more: