Common Failure Patterns and Fixes

1. Context window overflow

The most expensive error. You build a massive prompt, send it, and get a 400 error because you exceeded the model's context window. The fix: always count tokens before sending.

// Before sending, validate token count
const maxTokens = {
  'gpt-4o': 128000, 'gpt-5': 272000, 'gpt-5.5': 1000000,
  'claude-sonnet-4.6': 1000000, 'claude-haiku-4.5': 200000,
  'gemini-2.0-flash': 1000000, 'deepseek-v4-pro': 1000000
};

const limit = maxTokens[model] || 128000;
if (estimatedTokens > limit * 0.9) {
  // Truncate or summarize before sending
  prompt = truncateToTokenLimit(prompt, limit * 0.85);
}

2. Streaming connection drops

Streaming responses (SSE) can disconnect mid-response, especially on long outputs. The result: you've consumed input tokens but get no complete output. Fix: implement streaming resume or fall back to non-streaming for critical requests.

// Streaming error handling
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 60000);

try {
  const stream = await fetch(url, {
    ...options,
    signal: controller.signal
  });

  let fullResponse = '';
  for await (const chunk of stream.body) {
    fullResponse += parseChunk(chunk);
    clearTimeout(timeout); // Reset timeout on each chunk
  }
} catch (error) {
  if (error.name === 'AbortError') {
    // Timeout โ€” retry with non-streaming
    return await callWithRetry(() => fetchNonStreaming(options));
  }
  throw error;
}

3. Concurrent request collisions

Sending many requests simultaneously often triggers rate limits. The fix: implement a request queue with concurrency limits.

class RequestQueue {
  constructor(concurrency = 5) {
    this.concurrency = concurrency;
    this.running = 0;
    this.queue = [];
  }

  async add(fn) {
    if (this.running >= this.concurrency) {
      await new Promise(resolve => this.queue.push(resolve));
    }
    this.running++;
    try {
      return await fn();
    } finally {
      this.running--;
      if (this.queue.length) this.queue.shift()();
    }
  }
}

Cost-Aware Error Handling

The biggest mistake: retrying expensive requests blindly. If you're retrying a request that costs $0.50 per attempt, three retries cost $1.50 for a single logical operation.

Cost-Aware Retry Rules

Model fallback chains

When your primary model fails, falling back to a cheaper model saves both time and money:

Recommended Fallback Chains
Premium chainGPT-5 โ†’ Claude Sonnet 4.6 โ†’ Gemini 2.5 Pro
Mid-tier chainGPT-5 mini โ†’ Claude Haiku 4.5 โ†’ Gemini 2.5 Flash-Lite
Budget chainDeepSeek V4 Pro โ†’ Gemini Flash Lite โ†’ GPT-4o mini
Free/cheap chainGemini Flash Lite โ†’ GPT-oss 20B โ†’ Llama 3.1 8B

Calculate the real cost of your error rate

If 10% of your requests fail and you retry them, you're paying double for that 10%. Use our calculator to see the impact.

Open Calculator โ†’

โ€” See if you're overpaying for AI APIs

๐ŸŽฏ API Cost Score

Rate your API setup โ€” get a letter grade in 30 seconds

Monitoring and Alerting

Handle errors in code, but monitor them in production. Set up alerts for:

Use our AI API cost monitoring guide to set up real-time tracking of error-related spend.

๐ŸŽฏ API Cost Score

Rate your API setup โ€” get a letter grade in 30 seconds

Provider-Specific SDK Retry Defaults

Most providers have built-in retry logic in their official SDKs. Here's what you get by default:

Provider SDK Retries Default Strategy Customizable
OpenAI 2 Exponential backoff Yes โ€” maxRetries param
Anthropic 2 Exponential backoff Yes โ€” maxRetries param
Google Gemini 0 (manual) N/A โ€” implement yourself N/A
DeepSeek 0 (manual) N/A โ€” implement yourself N/A
Mistral 0 (manual) N/A โ€” implement yourself N/A

Important: Don't rely solely on SDK defaults. OpenAI and Anthropic retry on 429 and 500 errors, but they won't implement cost-aware retry logic or model fallbacks. Build your own wrapper on top.

The Complete Error Handler

Here's a production-ready error handler that combines everything:

async function resilientLLMCall(options) {
  const { model, prompt, maxCost = 0.50 } = options;
  const costPerToken = getModelCost(model);
  let totalCost = 0;

  const fallbackChain = getFallbackChain(model);

  for (const currentModel of fallbackChain) {
    const cost = getModelCost(currentModel);
    if (totalCost + cost > maxCost) break;

    try {
      const result = await callWithRetry(
        () => callLLM(currentModel, prompt),
        currentModel.includes('gpt') || currentModel.includes('claude') ? 2 : 1
      );
      return { ...result, model: currentModel };
    } catch (error) {
      totalCost += cost;
      console.warn(`${currentModel} failed: ${error.message}. Falling back.`);
    }
  }

  throw new Error('All models in fallback chain failed');
}

Track your error costs in real time

See exactly how much failed requests are costing you across all providers.

View Pricing Trends โ†’

Quick Reference: Error Handling Checklist

Related Reading

๐ŸŽฏ Rate Your API Setup in 30 Seconds

Get an A+ to F grade on your AI API costs. See how you compare and find cheaper alternatives instantly.

Get Your Cost Score โ†’

๐Ÿ“Š Generate Your Personalized API Cost Report

Select your model, enter your monthly spend, and get a custom savings report with cheaper alternatives โ€” free, in 60 seconds.

Found this useful? Share it:

Save money: ๐Ÿ“Š Live API Pricing ยท Cost Optimizer โ€” find out how much you could save by switching models. Free tool.

Want to optimize your AI API costs?

APIpulse includes free cost comparisons, exports, and recommendations that can save you up to 40%.

Free Cost Audit โ†’
๐Ÿ’ธ Looking for DeepSeek V4 Flash Alternatives?
5 models ranked by cost โ€” some offer better quality at similar prices.
See 5 DeepSeek V4 Flash Alternatives โ†’
๐Ÿ’ธ Looking for Sonnet 4.6 Alternatives?
5 models ranked by cost โ€” some are 90% cheaper.
See 5 Sonnet 4.6 Alternatives โ†’
๐Ÿ”ง Free Embeddable Pricing Widget
Add live AI API pricing to your docs, blog, or README with one script tag. 87 models, auto-updating.
Get the Free Widget โ†’ Free MCP Server โ†’