Fix "RecursionError: maximum recursion depth exceeded", "Maximum call stack size exceeded" and StackOverflowError
Why recursion runs out of stack in Python, JavaScript and Java, the accidental-recursion bugs behind most of these errors (getters, toString, equals), and how to rewrite deep recursion as iteration.
By Software Side Hustles Editorial Team · Published · Updated · 5 min read
Quick answer: a function kept calling itself (directly or through other functions) until the call stack ran out. Usually the base case is missing, wrong or unreachable — or the recursion is accidental, such as a property getter or toString() that calls itself. Fix the termination condition first. If the recursion is correct but the input is genuinely deep, rewrite it with a loop and an explicit stack; raising the recursion limit is a last resort.
The error in each language
| Language | Error | Typical default depth |
|---|---|---|
| Python | RecursionError: maximum recursion depth exceeded | 1,000 frames (sys.getrecursionlimit()) |
| JavaScript | RangeError: Maximum call stack size exceeded | ~10,000 frames, varies by engine and frame size |
| Java | java.lang.StackOverflowError | depends on thread stack size (-Xss) |
| C# | process terminates: "Stack overflow" (cannot be caught) | 1 MB main-thread stack by default |
| Go | runtime: goroutine stack exceeds 1000000000-byte limit | stacks grow up to 1 GB on 64-bit |
The stack trace is often enormous and repetitive. Scroll to where the repeating pattern starts — that shows which function, or which cycle of functions, is recursing.
Cause 1: a missing or unreachable base case
def countdown(n): if n == 0: return countdown(n - 2)
countdown(5) # 5, 3, 1, -1, -3 ... never hits 0Base cases must cover every path to the bottom. n <= 0 instead of n == 0 fixes this one. Other versions of the same bug: forgetting to make the problem smaller (return f(n) instead of f(n - 1)), and negative or unexpected input that skips past the base case.
When reviewing a recursive function, ask three questions:
- What is the base case?
- Does every recursive call move strictly closer to it?
- What happens with empty, zero, negative and very large input?
Cause 2: accidental recursion
Many stack overflows come from code that was never meant to be recursive:
class User { set name(value) { this.name = value; // calls the setter again → Maximum call stack size exceeded }}Store the value in a different field (this._name or a private #name).
class Config: def __getattr__(self, key): return self.settings[key] # if 'settings' is missing, __getattr__('settings') recurses@Data // Lombok generates equals, hashCode and toStringclass Author { List<Book> books; }@Dataclass Book { Author author; } // toString: Author → Book → Author → ... StackOverflowErrorBidirectional relationships (common with JPA entities) make generated toString, equals and hashCode methods recurse forever. Exclude one side (@ToString.Exclude, @EqualsAndHashCode.Exclude) or write those methods by hand using IDs.
Other accidental cycles: two functions that call each other on the same input; a React component that renders itself; an event handler that triggers the event it handles; a JSON serialiser walking a circular object graph (although JSON.stringify reports that as TypeError: Converting circular structure to JSON).
Cause 3: correct recursion, input too deep
def depth(node): if node is None: return 0 return 1 + max(depth(c) for c in node.children)This is correct, but a tree (or linked list, or nested JSON) more than about 1,000 levels deep will exhaust Python's default limit. Real data can be that deep: long comment threads, file systems, generated ASTs, degenerate trees.
Rewrite recursion as iteration
Any recursion can be converted to a loop with an explicit stack (for depth-first order) or queue (for breadth-first):
from collections import deque
def depth(root): if root is None: return 0 best = 0 queue = deque([(root, 1)]) while queue: node, d = queue.popleft() best = max(best, d) for child in node.children: queue.append((child, d + 1)) return bestThe explicit queue lives on the heap, which is limited only by memory. Our free tree depth exercise compares exactly these two versions.
Memoise overlapping recursion
Sometimes the problem is not depth but repetition. Naive Fibonacci makes an exponential number of calls; caching results makes it linear:
from functools import cache
@cachedef fib(n): return n if n < 2 else fib(n - 1) + fib(n - 2)Note that fib(5000) still hits the depth limit even with caching, because the first call recurses 5,000 levels down. Build up from small values in a loop instead.
Should I increase the recursion limit?
import syssys.setrecursionlimit(10_000)This helps only when the recursion is correct and moderately deep. Each Python frame also uses C stack space, so setting the limit too high can crash the interpreter with a hard segmentation fault instead of a catchable RecursionError. In Java you can enlarge the stack (-Xss4m, or a dedicated Thread with a larger stack size), and in Node.js --stack-size, but these are workarounds. If input size is unbounded, iteration is the real fix.
Does tail-call optimisation help?
A tail call is a recursive call that is the very last action of a function (return f(n - 1, acc)). Some languages reuse the stack frame for tail calls — Scheme, Scala with @tailrec, Kotlin with tailrec. Python, Java, C# and most JavaScript engines do not guarantee this, so rewriting in tail-recursive form does not prevent stack overflows there. Convert to a loop instead; a tail-recursive function translates almost mechanically.
Frequently asked questions
What is the call stack?
A region of memory holding one frame per active function call: its arguments, local variables and where to return. Each nested call adds a frame; returning removes it. The stack has a fixed maximum size.
Can I catch a stack overflow?
In Python you can catch RecursionError, and in Java StackOverflowError, but the program may be in an inconsistent state. In C# it cannot be caught at all. Fix the cause rather than catching it.
Is recursion bad?
No. It is the clearest way to express many algorithms on trees and nested data. Just know the depth limits of your language and the maximum depth of your data.
Where this skill pays off
"Is this recursion safe for large inputs?" is one of the questions AI code evaluators answer when comparing solutions — the elegant recursive answer is not always the better one. Read what makes one coding solution better than another to see how that judgement is made in paid evaluation work.