Erlang / Erlang Advanced Interview questions
What is tail call optimization in Erlang and why does it matter for long-running loops?
A function call is a tail call when it's the very last operation in a clause — nothing happens with its result except returning it directly. Erlang recognizes this pattern and reuses the current stack frame instead of pushing a new one, so a tail-recursive function can loop indefinitely without growing the call stack.
%% tail-recursive: the recursive call is the last thing evaluated loop(State) -> receive Msg -> loop(handle(Msg, State)) %% tail call end. %% NOT tail-recursive: work happens AFTER the recursive call returns sum([]) -> 0; sum([H|T]) -> H + sum(T). %% addition happens after the call
This matters directly for OTP: every gen_server, supervisor, and hand-rolled process loop relies on tail
call optimization to run forever inside a receive loop without ever running out of stack space.
Without it, a long-lived Erlang process would eventually overflow its stack simply by staying alive and
handling messages.
More Related questions...