<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Rohan's Engineering Notes]]></title><description><![CDATA[Practical insights into AI engineering, LLM infrastructure, software development, and developer tools. I share hands-on experiments, technical deep dives, open-]]></description><link>https://rohandev.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Wed, 25 Nov 2026 11:10:57 GMT</lastBuildDate><atom:link href="https://rohandev.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Why AI Apps Crash Under Real Traffic (And How to Fix It in 2 Lines)]]></title><description><![CDATA[Stop 12x LLM retry storms, dead billing-key waits, and duplicate AI streams. Handle 429 rate limits safely in TypeScript with @rohan9024/retrykit.]]></description><link>https://rohandev.hashnode.dev/fix-ai-429-rate-limits-retry-storms</link><guid isPermaLink="true">https://rohandev.hashnode.dev/fix-ai-429-rate-limits-retry-storms</guid><category><![CDATA[AI]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[llm]]></category><category><![CDATA[openai]]></category><dc:creator><![CDATA[Rohan Wandre]]></dc:creator><pubDate>Sat, 21 Nov 2026 17:38:04 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/65086411cd9977037e9d43ac/41ea36c1-c797-40b4-8a5f-1a3a96b7eb7d.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p><strong>TL;DR:</strong> Generic retry wrappers like <code>p-retry</code> or <code>while</code> loops weren't built for LLM APIs. They multiply SDK retries into <strong>9x–12x traffic storms</strong>, sleep on hard billing errors (<code>insufficient_quota</code>), corrupt streamed UI text on mid-stream disconnects, and break tool-call message histories. <a href="https://github.com/rohan9024/retrykit"><code>@rohan9024/retrykit</code></a> (<code>v2.0.0</code>) is a <strong>zero-dependency TypeScript reliability engine</strong> for AI apps that solves rate limits, multi-key rotation, circuit breaking, stream recovery, and atomic context compaction in one package.</p>
</blockquote>
<hr />
<p>If you have ever shipped an AI feature with OpenAI, Anthropic, or Gemini, you have probably seen this story play out in production:</p>
<ol>
<li>Users send a burst of requests.</li>
<li>Your provider returns <code>429 Too Many Requests</code> (or Anthropic returns <code>529 Overloaded</code>).</li>
<li>Your retry loop waits a second and retries every single request at the exact same time.</li>
<li>Worse: the OpenAI or Anthropic SDK <em>already</em> has built-in retries (<code>maxRetries: 2</code> by default). Wrapping your own 3-retry loop around it means <strong>one failed call can turn into 12 requests (</strong><code>3 × 4</code><strong>)</strong>.</li>
<li>Everything slows to a crawl, users see duplicated streamed text, and your bill spikes.</li>
</ol>
<p>This guide explains <strong>why standard HTTP retry logic fails on LLM APIs</strong> and how to fix it cleanly in under a minute using <strong>RetryKit (</strong><code>@rohan9024/retrykit</code><strong>)</strong>.</p>
<hr />
<h2>5 Ways Generic Retries Break AI Applications</h2>
<p>Before writing code, it helps to understand what actually goes wrong when you use a generic retry helper for LLMs:</p>
<h3>1. The Hidden Double-Retry Storm (<code>maxRetries</code> Multiplication)</h3>
<p>Most official AI SDKs already retry failed requests twice internally. When developers add a custom <code>retry()</code> wrapper or queue around the SDK without setting <code>maxRetries: 0</code>, retries multiply instead of adding up—flooding your own API quota during an outage.</p>
<h3>2. Sleeping on Hard Billing Errors (<code>insufficient_quota</code>)</h3>
<p>Not every <code>429</code> error means <em>"slow down and try again."</em> OpenAI returns <code>429</code> for <code>insufficient_quota</code> or spend limits, and Anthropic returns <code>enforced_spend_limit_reached</code>. Waiting 1s → 2s → 4s → 8s on a dead key just freezes your user's request for 15+ seconds for no reason. You should <strong>quarantine that key immediately and rotate to a backup key</strong> with zero sleep.</p>
<h3>3. Ignoring Provider-Specific Reset Headers</h3>
<p>Providers return rate-limit resets in wildly different formats:</p>
<ul>
<li><code>retry-after-ms</code> (milliseconds)</li>
<li><code>retry-after</code> (seconds or HTTP date strings)</li>
<li>OpenAI Go-style durations (<code>"464ms"</code>, <code>"1m30s"</code>)</li>
<li>Anthropic RFC 3339 timestamps (<code>anthropic-ratelimit-requests-reset</code>)</li>
</ul>
<p>Generic backoff ignores these headers—retrying either too early (hitting another 429) or much too late.</p>
<h3>4. Replaying Streams Duplicates Text in the UI</h3>
<p>Suppose your LLM streams 40 tokens to the user's chat screen and then stalls on token 41. If a naive wrapper restarts the HTTP call from scratch and yields tokens from the beginning, <strong>your user sees the first paragraph pasted twice</strong>.</p>
<p>Safe streaming recovery must treat <strong>pre-first-token failures</strong> differently from <strong>mid-stream failures</strong> (where resuming requires an explicit checkpoint mechanism like <code>getCheckpoint</code>).</p>
<h3>5. Naive Context Truncation Crashes Tool Calling</h3>
<p>When an agent hits a context limit and you trim older chat messages blindly, you can accidentally delete an <code>assistant</code> message containing <code>tool_calls</code> while leaving its <code>tool</code> response behind (or vice versa). Both OpenAI and Anthropic reject orphaned tool pairs with a hard <code>400 Bad Request</code>.</p>
<hr />
<h2>The Fix: <code>@rohan9024/retrykit</code> (Zero Dependencies, AI-Native)</h2>
<p><a href="https://www.npmjs.com/package/@rohan9024/retrykit"><code>@rohan9024/retrykit</code></a> is a lightweight, zero-dependency TypeScript reliability library built specifically for AI apps, Node.js backends, and Edge runtimes (<code>Node &gt;= 20</code>, Bun, Deno, Cloudflare Workers).</p>
<p>Install it with your package manager:</p>
<pre><code class="language-bash">npm install @rohan9024/retrykit
</code></pre>
<p><em>(Also works with</em> <code>pnpm add @rohan9024/retrykit</code><em>,</em> <code>yarn add @rohan9024/retrykit</code><em>, or</em> <code>bun add @rohan9024/retrykit</code><em>.)</em></p>
<hr />
<h2>Quick Start: Wrap OpenAI / Anthropic in 2 Lines</h2>
<p>The fastest way to protect an existing codebase is <code>@rohan9024/retrykit/auto</code>:</p>
<pre><code class="language-typescript">import OpenAI from "openai";
import { wrapAI } from "@rohan9024/retrykit/auto";

const openai = wrapAI(
  new OpenAI({ apiKey: process.env.OPENAI_API_KEY }),
  { provider: "openai" }
);

// Use the SDK exactly as before:
const response = await openai.chat.completions.create({
  model: "gpt-4o",
  messages: [{ role: "user", content: "Explain circuit breakers simply." }],
});
</code></pre>
<h3>What <code>wrapAI()</code> handles automatically under the hood:</h3>
<ul>
<li><strong>Stops retry storms:</strong> Automatically normalizes request-level <code>maxRetries: 0</code> so the SDK and RetryKit never stack retries.</li>
<li><strong>Auto-discovers backup API keys:</strong> Reads <code>OPENAI_API_KEYS</code> (comma-separated) or <code>OPENAI_API_KEY_1</code>, <code>OPENAI_API_KEY_2</code>, etc. (plus <code>ANTHROPIC_API_KEYS</code> and <code>GEMINI_API_KEYS</code>).</li>
<li><strong>Concurrency-safe per-request key injection:</strong> Injects rotated keys cleanly via per-request headers (<code>Authorization</code>, <code>x-api-key</code>, <code>x-goog-api-key</code>) instead of mutating shared global client state.</li>
<li><strong>Fast-fails hard billing errors:</strong> Detects <code>insufficient_quota</code>, <code>credit_balance_exhausted</code>, <code>organization_spend_limit_exceeded</code>, <code>project_spend_limit_exceeded</code>, and <code>enforced_spend_limit_reached</code> and rotates immediately instead of wasting sleep time.</li>
<li><strong>True timeout &amp; cancellation:</strong> Propagates linked <code>AbortController</code> signals (<code>attemptTimeoutMs</code>, <code>totalDeadlineMs</code>) so timed-out network calls actually abort instead of leaking sockets.</li>
</ul>
<hr />
<h2>Audit Your Existing Codebase in 5 Seconds</h2>
<p>Already have a big TypeScript project? Run the built-in static doctor CLI to find unguarded AI clients and hidden double-retry loops:</p>
<pre><code class="language-bash">npx @rohan9024/retrykit doctor
</code></pre>
<p>It scans your source files and points to the exact file and line where:</p>
<ul>
<li><code>new OpenAI(...)</code> or <code>new Anthropic(...)</code> is called without protection</li>
<li><code>maxRetries &gt; 0</code> could trigger double-retry amplification</li>
</ul>
<p>You can also scaffold a project starter config safely with:</p>
<pre><code class="language-bash">npx @rohan9024/retrykit init --dry-run
</code></pre>
<hr />
<h2>Modular Subpaths (Import Only What You Need)</h2>
<p>RetryKit v2.0.0 ships clean ESM + CommonJS + TypeScript declarations across focused subpaths with <code>"sideEffects": false</code>:</p>
<table>
<thead>
<tr>
<th align="left">Import Path</th>
<th align="left">What It Solves</th>
</tr>
</thead>
<tbody><tr>
<td align="left"><code>@rohan9024/retrykit/auto</code></td>
<td align="left">Drop-in <code>wrapAI()</code> proxy, multi-key discovery (<code>discoverApiKeys</code>), SDK retry neutralization</td>
</tr>
<tr>
<td align="left"><code>@rohan9024/retrykit/core</code></td>
<td align="left">Core <code>retry()</code>, <code>CircuitBreaker</code>, <code>KeyPool</code>, backoff + jitter, linked timeouts</td>
</tr>
<tr>
<td align="left"><code>@rohan9024/retrykit/fetch</code></td>
<td align="left">Composable <code>createRetryFetch()</code> with safe body cloning &amp; idempotency checks</td>
</tr>
<tr>
<td align="left"><code>@rohan9024/retrykit/stream</code></td>
<td align="left">Streaming watchdog &amp; explicit <code>getCheckpoint</code>-based safe recovery</td>
</tr>
<tr>
<td align="left"><code>@rohan9024/retrykit/compaction</code></td>
<td align="left">Tool-call-safe atomic context compaction (never orphans <code>tool_calls</code> / <code>tool</code> results)</td>
</tr>
<tr>
<td align="left"><code>@rohan9024/retrykit/budget</code></td>
<td align="left"><code>RetryBudget</code> and <code>TokenBucketRetryBudget</code> to cap retry amplification</td>
</tr>
<tr>
<td align="left"><code>@rohan9024/retrykit/ai-sdk</code></td>
<td align="left">Zero-dependency structural middleware (<code>transformParams</code>, <code>wrapGenerate</code>, <code>wrapStream</code>) for Vercel AI SDK</td>
</tr>
<tr>
<td align="left"><code>@rohan9024/retrykit/mcp</code></td>
<td align="left">Safe Model Context Protocol (<code>MCP</code>) retry wrapper (read-only allowlists; never retries unsafe <code>tools/call</code> by default)</td>
</tr>
<tr>
<td align="left"><code>@rohan9024/retrykit/validate</code></td>
<td align="left">Retry-on-validation-failure utilities</td>
</tr>
</tbody></table>
<hr />
<h2>How RetryKit Compares to Alternatives</h2>
<table>
<thead>
<tr>
<th align="left">Capability</th>
<th align="center"><code>@rohan9024/retrykit</code> v2.0</th>
<th align="center"><code>p-retry</code> / <code>async-retry</code></th>
<th align="center"><code>cockatiel</code></th>
<th align="center">Raw OpenAI / Anthropic SDK</th>
</tr>
</thead>
<tbody><tr>
<td align="left"><strong>Zero runtime dependencies</strong></td>
<td align="center">Yes (<code>0</code>)</td>
<td align="center">No</td>
<td align="center">Yes</td>
<td align="center">Full SDK</td>
</tr>
<tr>
<td align="left"><strong>OpenAI / Anthropic reset header parsing</strong></td>
<td align="center">Yes (<code>464ms</code>, <code>1m30s</code>, RFC 3339, <code>529</code>)</td>
<td align="center">No</td>
<td align="center">No</td>
<td align="center">Basic</td>
</tr>
<tr>
<td align="left"><strong>Hard billing error fast-rotation</strong></td>
<td align="center">Yes</td>
<td align="center">No (sleeps &amp; fails)</td>
<td align="center">No</td>
<td align="center">No</td>
</tr>
<tr>
<td align="left"><strong>Per-request multi-key rotation</strong></td>
<td align="center">Yes</td>
<td align="center">No</td>
<td align="center">No</td>
<td align="center">No</td>
</tr>
<tr>
<td align="left"><strong>Circuit breakers + token-bucket retry budgets</strong></td>
<td align="center">Yes</td>
<td align="center">No</td>
<td align="center">Partial</td>
<td align="center">No</td>
</tr>
<tr>
<td align="left"><strong>Checkpoint-safe stream handling</strong></td>
<td align="center">Yes (<code>getCheckpoint</code>)</td>
<td align="center">No</td>
<td align="center">No</td>
<td align="center">No</td>
</tr>
<tr>
<td align="left"><strong>Atomic tool-call context compaction</strong></td>
<td align="center">Yes</td>
<td align="center">No</td>
<td align="center">No</td>
<td align="center">No</td>
</tr>
<tr>
<td align="left"><strong>Vercel AI SDK &amp; MCP adapters included</strong></td>
<td align="center">Yes</td>
<td align="center">No</td>
<td align="center">No</td>
<td align="center">No</td>
</tr>
<tr>
<td align="left"><strong>AI Coding Agent Skill + CLI</strong> <code>doctor</code></td>
<td align="center">Yes</td>
<td align="center">No</td>
<td align="center">No</td>
<td align="center">No</td>
</tr>
</tbody></table>
<hr />
<h2>Using RetryKit with AI Coding Agents (Cursor, Claude Code, Codex, Copilot)</h2>
<p>Building with an AI coding assistant? RetryKit includes an official <strong>Agent Skill</strong> (<code>skills/retrykit/SKILL.md</code> following the <code>agentskills.io</code> standard), <code>llms.txt</code>, <code>llms-full.txt</code>, <code>AGENTS.md</code>, and <code>context7.json</code>.</p>
<h3>Option 1: Install the Reusable Agent Skill</h3>
<pre><code class="language-bash">npx skills add rohan9024/retrykit --skill retrykit
</code></pre>
<h3>Option 2: Paste This Prompt Into Cursor / Claude Code / Copilot</h3>
<blockquote>
<p><em>"Inspect my project for AI SDK calls (</em><code>openai</code><em>,</em> <code>@anthropic-ai/sdk</code><em>, Vercel AI SDK, or</em> <code>fetch</code> <em>LLM requests). Run</em> <code>npx @rohan9024/retrykit doctor</code><em>, install</em> <code>@rohan9024/retrykit</code> <em>with my project's package manager, wrap the clients using</em> <code>@rohan9024/retrykit/auto</code><em>, ensure</em> <code>maxRetries: 0</code> <em>is set to prevent double-retry storms, and verify with tests."</em></p>
</blockquote>
<p>You can also run RetryKit's built-in stdio MCP diagnostic server in any MCP-compatible editor:</p>
<pre><code class="language-bash">npx @rohan9024/retrykit mcp
</code></pre>
<hr />
<h2>Frequently Asked Questions (FAQ)</h2>
<h3>How do I handle OpenAI 429 rate limits in TypeScript without causing a retry storm?</h3>
<p>Use <code>@rohan9024/retrykit/auto</code> (<code>wrapAI</code>) or <code>@rohan9024/retrykit/core</code> (<code>retry</code> + <code>TokenBucketRetryBudget</code>). RetryKit automatically sets request-level <code>maxRetries: 0</code> on wrapped OpenAI/Anthropic SDK calls so SDK retries and custom retries never multiply, while honoring <code>retry-after-ms</code>, <code>x-ratelimit-reset-*</code>, and jittered backoff.</p>
<h3>Should I retry <code>429 insufficient_quota</code> errors?</h3>
<p>No. Sleeping and retrying an exhausted key wastes latency. RetryKit detects <code>insufficient_quota</code>, <code>credit_balance_exhausted</code>, <code>organization_spend_limit_exceeded</code>, <code>project_spend_limit_exceeded</code>, and <code>enforced_spend_limit_reached</code>, failing fast on that key so a backup key can take over immediately.</p>
<h3>How does RetryKit prevent duplicate output when an LLM stream disconnects?</h3>
<p>If a stream fails mid-way after chunks have already been emitted, silently replaying from the beginning would duplicate text. RetryKit refuses silent replay after output begins unless you supply an explicit <code>getCheckpoint</code> recovery mechanism.</p>
<h3>Does <code>@rohan9024/retrykit</code> add bloat or third-party supply-chain dependencies?</h3>
<p>No. <code>@rohan9024/retrykit</code> has <code>"dependencies": {}</code> (zero runtime dependencies) and exposes tree-shakeable ESM/CJS subpath exports with <code>"sideEffects": false</code>.</p>
<hr />
<h2>Get Started</h2>
<ul>
<li><strong>GitHub:</strong> <a href="https://github.com/rohan9024/retrykit">https://github.com/rohan9024/retrykit</a></li>
<li><strong>npm:</strong> <a href="https://www.npmjs.com/package/@rohan9024/retrykit">https://www.npmjs.com/package/@rohan9024/retrykit</a></li>
</ul>
<pre><code class="language-bash">npm install @rohan9024/retrykit
</code></pre>
<p>If RetryKit saves you from a production <code>429</code> incident, leave a star on GitHub or open an issue telling us which AI SDK or framework adapter you want next!</p>
]]></content:encoded></item></channel></rss>