TL;DR: Generic retry wrappers like p-retry or while loops weren't built for LLM APIs. They multiply SDK retries into 9x–12x traffic storms, sleep on hard billing errors (insufficient_quota), corrupt streamed UI text on mid-stream disconnects, and break tool-call message histories. @rohan9024/retrykit ( v2.0.0) is a zero-dependency TypeScript reliability engine for AI apps that solves rate limits, multi-key rotation, circuit breaking, stream recovery, and atomic context compaction in one package.
If you have ever shipped an AI feature with OpenAI, Anthropic, or Gemini, you have probably seen this story play out in production:
429 Too Many Requests (or Anthropic returns 529 Overloaded). maxRetries: 2 by default). Wrapping your own 3-retry loop around it means 3 × 4
This guide explains why standard HTTP retry logic fails on LLM APIs and how to fix it cleanly in under a minute using RetryKit (@rohan9024/retrykit).
Before writing code, it helps to understand what actually goes wrong when you use a generic retry helper for LLMs:
maxRetries Multiplication)
Most official AI SDKs already retry failed requests twice internally. When developers add a custom retry() wrapper or queue around the SDK without setting maxRetries: 0, retries multiply instead of adding up—flooding your own API quota during an outage.
insufficient_quota)
Not every 429 error means "slow down and try again." OpenAI returns 429 for insufficient_quota or spend limits, and Anthropic returns enforced_spend_limit_reached. Waiting 1s → 2s → 4s → 8s on a dead key just freezes your user's request for 15+ seconds for no reason. You should quarantine that key immediately and rotate to a backup key with zero sleep.
Providers return rate-limit resets in wildly different formats:
retry-after-ms (milliseconds)retry-after (seconds or HTTP date strings)"464ms", "1m30s") anthropic-ratelimit-requests-reset)
Generic backoff ignores these headers—retrying either too early (hitting another 429) or much too late.
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, your user sees the first paragraph pasted twice.
Safe streaming recovery must treat pre-first-token failures differently from mid-stream failures (where resuming requires an explicit checkpoint mechanism like getCheckpoint).
When an agent hits a context limit and you trim older chat messages blindly, you can accidentally delete an assistant message containing tool_calls while leaving its tool response behind (or vice versa). Both OpenAI and Anthropic reject orphaned tool pairs with a hard 400 Bad Request.
@rohan9024/retrykit (Zero Dependencies, AI-Native)
@rohan9024/retrykit is a lightweight, zero-dependency TypeScript reliability library built specifically for AI apps, Node.js backends, and Edge runtimes (Node >= 20, Bun, Deno, Cloudflare Workers).
Install it with your package manager:
npm install @rohan9024/retrykit
(Also works with pnpm add @rohan9024/retrykit, yarn add @rohan9024/retrykit, or bun add @rohan9024/retrykit.)
The fastest way to protect an existing codebase is @rohan9024/retrykit/auto:
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." }],
});
wrapAI() handles automatically under the hood:
maxRetries: 0 so the SDK and RetryKit never stack retries.OPENAI_API_KEYS (comma-separated) or OPENAI_API_KEY_1, OPENAI_API_KEY_2, etc. (plus ANTHROPIC_API_KEYS and GEMINI_API_KEYS). Authorization, x-api-key, x-goog-api-key) instead of mutating shared global client state. credit_balance_exhausted, organization_spend_limit_exceeded, project_spend_limit_exceeded, and enforced_spend_limit_reached and rotates immediately instead of wasting sleep time.AbortController signals (attemptTimeoutMs, totalDeadlineMs) so timed-out network calls actually abort instead of leaking sockets.
Already have a big TypeScript project? Run the built-in static doctor CLI to find unguarded AI clients and hidden double-retry loops:
npx @rohan9024/retrykit doctor
It scans your source files and points to the exact file and line where:
new OpenAI(...) or new Anthropic(...) is called without protectionmaxRetries > 0 could trigger double-retry amplification
You can also scaffold a project starter config safely with:
npx @rohan9024/retrykit init --dry-run
RetryKit v2.0.0 ships clean ESM + CommonJS + TypeScript declarations across focused subpaths with "sideEffects": false:
| Import Path | What It Solves |
|---|---|
@rohan9024/retrykit/auto |
Drop-in wrapAI() proxy, multi-key discovery (discoverApiKeys ), SDK retry neutralization |
@rohan9024/retrykit/core |
Core retry() ,CircuitBreaker ,KeyPool , backoff + jitter, linked timeouts |
@rohan9024/retrykit/fetch |
Composable createRetryFetch() with safe body cloning & idempotency checks |
@rohan9024/retrykit/stream |
Streaming watchdog & explicit getCheckpoint -based safe recovery |
@rohan9024/retrykit/compaction |
Tool-call-safe atomic context compaction (never orphans tool_calls /tool results) |
@rohan9024/retrykit/budget |
RetryBudget andTokenBucketRetryBudget to cap retry amplification |
@rohan9024/retrykit/ai-sdk |
Zero-dependency structural middleware ( transformParams ,wrapGenerate ,wrapStream ) for Vercel AI SDK |
@rohan9024/retrykit/mcp |
Safe Model Context Protocol ( MCP ) retry wrapper (read-only allowlists; never retries unsafetools/call by default) |
@rohan9024/retrykit/validate |
Retry-on-validation-failure utilities |
| Capability | @rohan9024/retrykit v2.0 |
p-retry /async-retry |
cockatiel |
Raw OpenAI / Anthropic SDK |
|---|---|---|---|---|
| Zero runtime dependencies | Yes ( 0 ) |
No | Yes | Full SDK |
| OpenAI / Anthropic reset header parsing | Yes ( 464ms ,1m30s , RFC 3339,529 ) |
No | No | Basic |
| Hard billing error fast-rotation | Yes | No (sleeps & fails) | No | No |
| Per-request multi-key rotation | Yes | No | No | No |
| Circuit breakers + token-bucket retry budgets | Yes | No | Partial | No |
| Checkpoint-safe stream handling | Yes ( getCheckpoint ) |
No | No | No |
| Atomic tool-call context compaction | Yes | No | No | No |
| Vercel AI SDK & MCP adapters included | Yes | No | No | No |
AI Coding Agent Skill + CLIdoctor |
Yes | No | No | No |
Building with an AI coding assistant? RetryKit includes an official Agent Skill (skills/retrykit/SKILL.md following the agentskills.io standard), llms.txt, llms-full.txt, AGENTS.md, and context7.json.
npx skills add rohan9024/retrykit --skill retrykit
"Inspect my project for AI SDK calls (openai, @anthropic-ai/sdk, Vercel AI SDK, or fetch LLM requests). Run npx @rohan9024/retrykit doctor, install @rohan9024/retrykit with my project's package manager, wrap the clients using @rohan9024/retrykit/auto, ensure maxRetries: 0 is set to prevent double-retry storms, and verify with tests."
You can also run RetryKit's built-in stdio MCP diagnostic server in any MCP-compatible editor:
npx @rohan9024/retrykit mcp
Use @rohan9024/retrykit/auto (wrapAI) or @rohan9024/retrykit/core (retry + TokenBucketRetryBudget). RetryKit automatically sets request-level maxRetries: 0 on wrapped OpenAI/Anthropic SDK calls so SDK retries and custom retries never multiply, while honoring retry-after-ms, x-ratelimit-reset-*, and jittered backoff.
429 insufficient_quota errors?
No. Sleeping and retrying an exhausted key wastes latency. RetryKit detects insufficient_quota, credit_balance_exhausted, organization_spend_limit_exceeded, project_spend_limit_exceeded, and enforced_spend_limit_reached, failing fast on that key so a backup key can take over immediately.
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 getCheckpoint recovery mechanism.
No. @rohan9024/retrykit has "dependencies": {} (zero runtime dependencies) and exposes tree-shakeable ESM/CJS subpath exports with "sideEffects": false.
npm install @rohan9024/retrykit
If RetryKit saves you from a production 429 incident, leave a star on GitHub or open an issue telling us which AI SDK or framework adapter you want next!