惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
小众软件
小众软件
博客园_首页
博客园 - 聂微东
V
V2EX
WordPress大学
WordPress大学
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
罗磊的独立博客
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - 司徒正美
博客园 - 三生石上(FineUI控件)
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
S
SegmentFault 最新的问题
J
Java Code Geeks
Last Week in AI
Last Week in AI
The Cloudflare Blog
月光博客
月光博客
雷峰网
雷峰网
宝玉的分享
宝玉的分享
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Hugging Face - Blog
Hugging Face - Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
有赞技术团队
有赞技术团队
人人都是产品经理
人人都是产品经理
博客园 - Franky
腾讯CDC
Jina AI
Jina AI
博客园 - 叶小钗
大猫的无限游戏
大猫的无限游戏
阮一峰的网络日志
阮一峰的网络日志
量子位
爱范儿
爱范儿
美团技术团队
T
Tailwind CSS Blog
博客园 - 【当耐特】
D
Docker
IT之家
IT之家
V
Visual Studio Blog
P
Proofpoint News Feed
L
LangChain Blog
Engineering at Meta
Engineering at Meta
C
Check Point Blog
G
Google Developers Blog
Google DeepMind News
Google DeepMind News
云风的 BLOG
云风的 BLOG
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Microsoft Azure Blog
Microsoft Azure Blog
B
Blog RSS Feed
Recorded Future
Recorded Future

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Your Recursion Is Lying to You
Gabor Koos · 2026-05-10 · via DEV Community

Recursion is one of those ideas developers learn early and trust for years. If the recursive step is simple and the base case is correct, the code feels clean and safe.

It is elegant for a reason: many problems are naturally recursive, and the code often mirrors how we explain the logic out loud. For tree walks, nested structures, and divide-and-conquer patterns, recursion can be easier to read than explicit loops.

The catch is physical limits. Even with a correct base case and sound logic, each recursive call still consumes stack space. At some depth, you crash with stack overflow.

If you read Your Debounce Is Lying to You and Your Throttling Is Lying to You, this is the recursion version of the same pattern: elegant abstraction, hidden operational edge.

Problem Setup: Recursion Hits The Wall

You can run everything below directly in a browser console. Let's start simple: a recursive sum of all integers from 1 to n.

function sum(n) {
  if (n === 0) return 0;
  return n + sum(n - 1);
}

sum(10); // 55

Enter fullscreen mode Exit fullscreen mode

Now push a big input:

sum(100000); // RangeError or InternalError: too much recursion in most JS runtimes

Enter fullscreen mode Exit fullscreen mode

What just happened? The function is logically correct, but each call to sum stays on the stack until the one below it returns. At depth 100,000 the runtime runs out of stack space and throws. It has nothing to do with the result being wrong, it is purely a physical limit on how many nested frames the runtime can hold at once.

The Tail Recursion Rescue Story

The usual next step is tail call optimization. The idea is simple: make the recursive call the last thing the function does, so the runtime can reuse the same frame instead of pushing a new one.

Note that sum is not tail-recursive, even though the recursive call appears on the last line. After sum(n - 1) returns, there is still pending work: the result must be added to n. A call is only in tail position when its return value is forwarded immediately, with no pending computation afterward.

The tail-recursive version moves that pending state into an accumulator:

function sumTR(n, acc = 0) {
  if (n === 0) return acc;
  return sumTR(n - 1, acc + n);
}

sumTR(10); // 55

Enter fullscreen mode Exit fullscreen mode

Here sumTR(...) is the very last thing that happens — no pending +, no pending anything. The running total lives in acc, not in waiting stack frames. In theory, a runtime that implements TCO can execute this in constant stack space regardless of depth.

Now repeat the same stress input:

sumTR(100000); // may still throw RangeError!

Enter fullscreen mode Exit fullscreen mode

Even with correct tail-recursive structure, many JavaScript runtimes still allocate a new stack frame per call and throw at large depth. This surprises developers who expect TCO to be a universal guarantee. ECMAScript 2015 formally specified proper tail calls in strict mode, but most engines never adopted the feature consistently. Some shipped it and then walked it back due to performance regressions. Others never implemented it at all. The result is that you cannot assume tail recursion is stack-safe in production JavaScript, even if the code is correctly structured for TCO.

A Note on Fibonacci

Fibonacci is the go-to recursion textbook example and it does run into stack limits too, but it carries a second problem that makes it even worse: exponential time complexity.

function fib(n) {
  if (n <= 1) return n;
  return fib(n - 1) + fib(n - 2);
}

Enter fullscreen mode Exit fullscreen mode

Each call branches into two more calls, so the total number of calls grows as O(2ⁿ). fib(30) already makes over a million calls; fib(50) is in the tens of billions. In a browser this freezes the tab long before any stack limit is reached, which makes the failure mode look identical to a stack overflow but have a completely different root cause.

The tail-recursive version of Fibonacci:

function fibTR(n, a = 0, b = 1) {
  if (n === 0) return a;
  if (n === 1) return b;
  return fibTR(n - 1, b, a + b);
}

Enter fullscreen mode Exit fullscreen mode

This version runs in linear time, but it still risks stack overflow at large n due to the same TCO uncertainty. The exponential version is a red herring for this discussion because it fails for a completely different reason: stack overflow and exponential blowup are two separate problems. They look the same from the outside (the page hangs or crashes) but require completely different fixes.

Runtime Reality (At The Time Of Writing)

At the time of writing (May 2026), proper tail-call optimization support is not something you can count on across JavaScript runtimes.

Runtime Engine Proper Tail Calls You Can Rely On? Practical Take
Chrome V8 No Do not expect stack-safe tail recursion.
Node.js V8 No Tail-recursive code can still overflow.
Deno V8 No Same operational expectation as Node/Chrome.
Firefox SpiderMonkey No Do not treat tail recursion as a safety guarantee.
Safari JavaScriptCore Inconsistent — JSC has shipped and walked back TCO across versions Do not rely on it; behavior has varied enough across releases that it is not a stable guarantee.
Bun JavaScriptCore-based Engine-dependent, not a cross-runtime guarantee Verify on exact version; do not assume universal behavior.

The key point is portability. Tail recursion is a property of function structure, while stack reuse is a property of runtime implementation. Even if one engine behaves better in one version, production JavaScript usually spans multiple targets, and correctness should not depend on optimizer-specific behavior. A function can be perfectly tail-recursive in shape and still consume stack per call in the environments your users actually run.

Better Patterns for Production Code

Every recursive function can be rewritten iteratively, and that is usually the safest choice in production when input depth can grow. Iteration does not rely on runtime optimizations for stack safety, because it does not consume stack frames per step. This does not mean giving up the recursive mental model. You can still write code that is conceptually recursive but uses an explicit stack or a trampoline to manage control flow without hitting physical limits.

function sumIter(n) {
  let acc = 0;
  for (let i = n; i > 0; i--) acc += i;
  return acc;
}

sumIter(1000000); // no recursive stack growth

Enter fullscreen mode Exit fullscreen mode

The Trampoline Pattern

If you want to keep the recursive structure for readability but need to avoid stack growth, you can use a trampoline: a loop that repeatedly calls a function that returns either a final result or another function to call.

function trampoline(fn) {
  let result = fn;
  while (typeof result === 'function') {
    result = result();
  }
  return result;
}

function sumTrampoline(n, acc = 0) {
  if (n === 0) return acc;
  return () => sumTrampoline(n - 1, acc + n);
}

trampoline(() => sumTrampoline(100000)); // no stack overflow, still tail-recursive in spirit

Enter fullscreen mode Exit fullscreen mode

Trampolines trade stack safety for additional function allocations and dispatch overhead, so they are most useful when preserving recursive structure matters more than raw performance.

This approach scales in a way that does not depend on runtime tail-call behavior, which is exactly what you want when input depth can grow. If recursive structure improves readability for a particular problem, these techniques let you keep that mental model with explicit tradeoffs instead of implicit runtime assumptions.

A useful rule of thumb is to keep recursion for small, bounded depths that you control, and switch to iterative control flow as soon as depth is user-driven, data-driven, or operationally uncertain. For hot paths, benchmark both styles, but do not base correctness on assumed TCO.

Practical Checklist

  • Never assume TCO in JavaScript for production-critical paths.
  • Test with realistic upper bounds, not toy input sizes.
  • Favor iterative implementations when depth can grow.
  • Treat recursion as a readability tool, not a stack-safety guarantee.

Conclusion

Recursion itself is not the enemy, unverified runtime assumptions are. Tail-recursive shape does not automatically make JavaScript stack-safe, and that gap is where many "works on my machine" surprises come from in production.

Use recursion where it improves clarity and depth is genuinely bounded. When depth can grow or input is outside your control, prefer iterative designs that make stack behavior explicit and portable.