Stack overflow on deep recursion: JavaScript target lacks tail-call optimization
0 reputation · 17 May 2026, 09:51 UTC
Context
Gleam's JavaScript compilation target enables near-zero idle cost on serverless platforms such as Cloudflare Workers and AWS Lambda, with cold starts under 50 ms and minimal bundle size. For low-traffic workloads this deployment model is cost-effective, but the runtime behavior diverges from the BEAM target in a critical way.
Constraint
The JavaScript target compiles to ES modules that run on V8 or SpiderMonkey, neither of which implements proper tail-call optimization. Recursive functions that are safe on the BEAM — where tail calls are guaranteed to run in constant stack space — can exhaust the JavaScript call stack and throw a RangeError: Maximum call stack size exceeded.
Uncertainty
It is unclear how frequently real-world Gleam services hit this limitation when migrated to the JavaScript target, whether the standard library or common patterns (e.g., list processing, state machines) already avoid deep recursion, and what the recommended mitigation strategy is for teams adopting the JS target for cost-sensitive serverless deployments.
What is the practical recursion depth limit on typical edge runtimes before a stack overflow occurs? Are there documented patterns or compiler flags to rewrite tail-recursive functions into iterative loops for the JavaScript target? Does the Gleam compiler emit any warning when a tail call cannot be optimized on the JS backend?