Stack-Safe Recursion Without the TCO Fairy Tale
Photo: Tess Mattew, CC BY-SA 4.0, via Wikimedia Commons
There is a specific kind of bug report that only shows up in production: RangeError: Maximum call stack size exceeded, on a code path that passed every test because every test used twelve items instead of two hundred thousand.
Recursion is the natural way to express a great many things — tree walks, state machines, parsing, list processing. The trouble is that the elegance is paid for in stack frames, and most runtimes are not obligated to give them back. So if you want to ship the recursive formulation, you need a plan for the frames.
Three plans exist. They are not interchangeable.
Option 1: Trampolining
A trampoline turns recursion into a loop by having each step return the next step instead of calling it. The driver bounces on those thunks until it gets a value.
const trampoline = (fn) => (...args) => {
let result = fn(...args);
while (typeof result === 'function') result = result();
return result;
};
const sumList = trampoline(function step(node, acc) {
if (!node) return acc;
return () => step(node.next, acc + node.value);
});
It also rescues mutual recursion, which is where an iterative rewrite gets ugly fast:
const evenStep = trampoline(function even(n) {
return n === 0 ? true : () => oddStep(n - 1);
});
Cost: one allocation per iteration. In JavaScript that is a closure; in Python it is a lambda or a functools.partial. For a million-row walk, you are creating a million short-lived objects, and the garbage collector will notice.
Option 2: An explicit stack
If the recursion is genuinely a traversal — not just a loop in disguise — put the pending work in a heap-allocated list and drive it with a while.
def walk(node):
total = 0
stack = [node]
while stack:
current = stack.pop()
if current is None:
continue
total += current.value
stack.append(current.next)
return total
This is the right answer when the recursion is not tail-shaped: depth-first search, expression evaluation, anything where you need to come back to a node after finishing its children.
Cost: the traversal order is now something you manage by hand. Pre-order, post-order, and in-order each need a different push discipline, and getting it wrong produces results that are subtly mis-ordered rather than obviously broken — the worst failure mode there is.
Option 3: Rewrite as a loop
Most tail-recursive functions are loops wearing a costume. If all the state lives in the arguments, an accumulator plus a while does the same job with zero allocation and zero cleverness.
def sum_list(head):
total = 0
node = head
while node is not None:
total += node.value
node = node.next
return total
Cost: readability, sometimes. The recursive version usually states the problem; the loop states the mechanism. For a linked list nobody cares. For a three-state parser, the loop version can be genuinely harder to review.
Clojure gets to cheat, a little
Clojure has two mechanisms built in, and they mean different things. recur is a genuine tail-position jump — it does not grow the stack and it is not a function call:
(defn total [node]
(loop [n node acc 0]
(if (nil? n)
acc
(recur (:next n) (+ acc (:value n))))))
trampoline handles the mutual case by doing the thunk-bouncing for you:
(defn even-step [n] (if (zero? n) true #(odd-step (dec n))))
(defn odd-step [n] (if (zero? n) false #(even-step (dec n))))
(trampoline even-step 1000000)
The catch is that recur only works in tail position. Put it anywhere else and the compiler tells you politely, which is honestly better than the silence you get elsewhere.
So which one goes in the codebase
- Tail-shaped and simple? Rewrite it as a loop. No allocation, no cleverness, no explanation needed in review.
- Tail-shaped but mutual, or dispatched through several functions? Trampoline. It preserves the shape that made the logic readable.
- Genuinely tree-shaped? Explicit stack. Stop pretending the recursion was a loop.
- Clojure?
recurfirst,trampolinesecond, and treat plain deep recursion as a bug waiting for bigger input.
One rule that outranks all of this
Write the recursive version first, because it is usually the clearest statement of the algorithm. Then, before it merges, ask what the maximum depth is and whether anyone has actually bounded it. If the answer is a shrug, convert it — not because recursion is bad, but because an unbounded stack is a production incident with a nicer name.
The brand on this site is recursion, and I am not here to talk you out of it. I am here to make sure the thing you ship recurses in constant space.