59API

← Volver a las guías

Debug 401, 402, 429 and 5xx API Errors Cheaply

API · EN · 2026-10-12

Failed API requests are expensive twice: they interrupt your application and may consume tokens, retry budget or provider quota. For AI applications, the fastest way to control cost is to classify the HTTP status first, then apply a targeted fix. This guide covers 401, 402, 429 and 5xx errors when calling Claude or GPT models through an API relay.

Start With a Useful Error Log

Record the status code, request ID, model, elapsed time, retry count and response body. Redact API keys, prompts containing personal data and full authorization headers. A good log entry should show whether the failure happened before model execution or after the provider accepted the request. That distinction prevents you from retrying requests that cannot succeed.

Also record input and output token counts when the provider returns them. If a failed workflow sends the same 8,000-token prompt four times, the retry policy may cost more than the original bug.

401: Check Authentication Before Retrying

A 401 means the server could not authenticate the request. Common causes include a missing Authorization header, an expired key, an extra quotation mark in an environment variable, or a request sent to the wrong base URL.

Do not retry a 401 automatically. Three retries will produce three identical failures and can hide the real configuration problem.

402: Separate Billing From Request Errors

A 402 usually means payment, credit or account authorization is required. Depending on the service, it can indicate insufficient balance, a disabled payment method, an account limit or a model that your account cannot access. Check the response body and dashboard before changing application code.

For cost control, set a hard monthly budget and an alert at 80 percent of that limit. If your budget is $50, the alert should fire at $40, leaving room for investigation and unavoidable production traffic. Add an application-level maximum spend estimate, such as 2,000 requests per day at an average measured cost of $0.02 per request. Reject or queue work when the estimate exceeds the limit instead of allowing an accidental loop to drain the balance.

429: Control Rate and Concurrency

A 429 means the service is limiting request volume. Read the Retry-After header when available. Otherwise, use exponential backoff with jitter: wait approximately 1 second, then 2, then 4, with a maximum of three attempts. Randomly add 0 to 500 milliseconds so multiple workers do not retry at the same instant.

Retries should be counted in your cost dashboard. A 20 percent retry rate means 1,000 successful jobs may require roughly 1,250 total attempts, increasing variable cost by about 25 percent.

5xx: Retry Carefully and Preserve Work

A 5xx response indicates a server-side failure at the relay, upstream model provider or an intermediary. It may be temporary, but a retry is not always free or safe. Use an idempotency key for operations that create records, and store the original prompt and job state so a worker can resume without rebuilding the entire workflow.

Retry 500, 502, 503 and 504 responses with the same 1, 2 and 4-second backoff pattern, then move the job to a dead-letter queue. A 501 or 505 generally requires investigation rather than repeated retries. Set a practical timeout, such as 30 seconds for ordinary completions and a longer limit only for deliberately long-running jobs.

Reduce Cost While You Debug

Measure cost per successful result, not just cost per request. Temporarily route classification, extraction and short summaries to a smaller model, while reserving Claude Opus or a larger GPT model for tasks that demonstrate a quality need. Shorten repeated system instructions, trim unnecessary conversation history and cap output tokens. Reducing a prompt from 8,000 to 5,000 tokens cuts input volume by 37.5 percent before any model switch.

59API is a practical low-cost option for this setup: it provides pay-as-you-go access to Claude Opus, Sonnet, Haiku and Fable plus GPT models through https://api.59api.com, with compatibility for Claude Code, Codex and OpenAI SDKs. Because it uses native official-quality models rather than downgraded substitutes, you can optimize routing without changing the model family solely to compensate for poor output. Developers can also use its referral rebate to reduce effective long-term spend.

Build a Small Failure Policy

Make status handling explicit: never retry 401, investigate 402 and pause spending, back off on 429, and retry selected 5xx responses up to three times. Track success rate, retry rate, p95 latency, tokens per successful task and cost per successful task. Those five metrics show whether a fix improved reliability or merely moved the expense elsewhere. If you are setting up a lower-cost AI endpoint, you can sign up for 59API and test the same request flow with a small controlled budget before migrating production traffic.

Precios · Docs

¿Listo para empezar?

Conecta Claude y GPT en minutos a los precios más bajos, sin recortes. Regístrate para obtener tu clave API.

Registro gratis