Every production AI outage looks dramatic in a Slack incident channel, yet most of them start with something remarkably mundane. A background worker silently drops an environment variable during a rolling deploy and begins firing 401 authentication_error at twenty requests per second. A product engineer bumps max_tokens from 1,024 to 32,768 on a classification route without checking prepaid balance headroom and triggers 402 insufficient_quota mid-afternoon. Or a reverse proxy sits on its default 60-second read timeout and severs long claude-sonnet-5-5 Server-Sent Events (SSE) streams halfway through a legal summary, prompting a naive frontend retry loop that doubles load and confuses users.
This on-call runbook is your field manual for troubleshooting TOP AI API errors across every status code from 400 through 503, plus the messy middle ground of mid-stream SSE disconnects where HTTP already returned 200 OK. If you are still setting up credentials or wiring your first SDK, finish the TOP AI quickstart tutorial covering signup, API keys, and your first request and the TOP AI SDK integration tutorial for Python, Node.js, LangChain, and Vercel AI first. Here, we assume your code is already shipping traffic and you need deterministic failure classification, production-ready retry clients, and five-minute terminal isolation procedures.
First Rule of Gateway Reliability: Draw an unbreakable boundary in your client layer between deterministic
4xxerrors (400,401,402,403,404,413, and429 period_limit_exceeded) that must fail fast, and transient errors (429 rate_limit_exceeded,500,502,503) that recover viaRetry-After, capped exponential backoff, and 0–250 ms random jitter. Enforcing that single split prevents more cascading incidents than any fancy orchestration framework.
Every status code, header name, timeout boundary, and billing semantic in this runbook maps directly to live TOP AI gateway behavior documented in the official API reference at /en/docs and current token pricing at /en/pricing. We will dissect both OpenAI and Anthropic error envelopes, inspect a 10,000-error production root-cause breakdown, ship complete TypeScript and Python resilient clients with circuit breakers, build a 30-second SSE data-heartbeat watchdog backed by Idempotency-Key, and close with copy-paste curl triage commands.
Dual-Protocol Error Envelopes: OpenAI vs. Anthropic Shapes
Before a single retry policy or alert rule can work reliably, your HTTP layer has to parse failures cleanly across both protocol surfaces. TOP AI runs a native dual-protocol gateway—serving OpenAI-compatible traffic under https://topai.id/v1 and native Anthropic Messages traffic under https://topai.id, an architecture detailed in our 2026 unified AI gateway field guide. Because each surface respects its upstream wire contract verbatim, error bodies follow two distinct JSON shapes.
Teams routinely stumble here when one shared TypeScript or Python service calls gpt-6-1 or deepseek-v4-1-flash through the OpenAI endpoint while routing claude-sonnet-5-5 through /v1/messages for prompt caching. If your centralized logger assumes every error response has body.error.code and body.error.param, half of your Anthropic-path alerts arrive in Grafana or Sentry with blank error codes and broken routing rules.
Compare the exact JSON payloads returned by TOP AI across the two surfaces:
// OpenAI-compatible surface (/v1/chat/completions, /v1/models, /v1/images/generations)
{
"error": {
"message": "Model \"gpt-9\" tidak tersedia. Lihat GET /v1/models.",
"type": "not_found_error",
"code": "not_found_error",
"param": "model"
}
}// Anthropic-compatible surface (/v1/messages, /v1/messages/count_tokens)
{
"type": "error",
"error": {
"type": "not_found_error",
"message": "Model \"gpt-9\" tidak tersedia. Lihat GET /v1/models."
}
}Three structural differences matter immediately in production parsers. First, Anthropic-path errors wrap the payload with a top-level "type": "error" discriminator, whereas OpenAI-path errors begin directly with the "error" object. Second, the OpenAI envelope exposes dedicated "code" and "param" fields—critical for distinguishing rate_limit_exceeded from period_limit_exceeded, catching key_paused, or identifying which request field triggered a 400 or 404. On the Anthropic surface, standard errors carry "type" and "message" inside "error", so sub-code detection must inspect both error.type and the message or accompanying response headers. Third, whenever an intermediate proxy (Cloudflare, AWS ALB, corporate egress firewall, or nginx) aborts a request before TOP AI responds, the body is often plain text or HTML rather than JSON.

Never call await response.json() directly inside an error branch. If an intermediate proxy returns an HTML 502 Bad Gateway page, an unguarded .json() call throws a SyntaxError that hides the actual HTTP status code and breaks upstream retry triggers. Read raw text first, parse defensively, and normalize both surfaces into a single typed contract:
// language: TypeScript, file: topai-error-normalizer.ts, target: Node.js 20+ / Edge Runtime
export interface NormalizedGatewayError {
status: number;
surface: "openai" | "anthropic" | "raw_proxy";
type: string;
code: string;
param: string | null;
message: string;
retryAfterSec: number | null;
rateLimitLimit: number | null;
rateLimitRemaining: number | null;
rateLimitReset: string | null;
retryable: boolean;
rawSnippet: string;
}
export function normalizeTopAiError(res: Response, rawBody: string): NormalizedGatewayError {
const status = res.status;
const retryAfterRaw = res.headers.get("retry-after");
const retryAfterParsed = retryAfterRaw ? Number.parseFloat(retryAfterRaw) : NaN;
const retryAfterSec =
Number.isFinite(retryAfterParsed) && retryAfterParsed > 0 ? retryAfterParsed : null;
const parseIntHeader = (name: string): number | null => {
const val = res.headers.get(name);
if (val === null) return null;
const n = Number.parseInt(val, 10);
return Number.isNaN(n) ? null : n;
};
let surface: "openai" | "anthropic" | "raw_proxy" = "raw_proxy";
let type = "unknown_error";
let code = "unknown_error";
let param: string | null = null;
let message = rawBody.slice(0, 300) || `HTTP ${status} with empty body`;
try {
const parsed = JSON.parse(rawBody);
if (parsed && typeof parsed === "object" && parsed.error && typeof parsed.error === "object") {
surface = parsed.type === "error" ? "anthropic" : "openai";
type = String(parsed.error.type ?? "api_error");
code = String(parsed.error.code ?? parsed.error.type ?? "api_error");
param = typeof parsed.error.param === "string" ? parsed.error.param : null;
message = String(parsed.error.message ?? message);
}
} catch {
// Preserve raw_proxy classification so HTTP 502/503 status remains retryable
}
const isPeriodCap =
code === "period_limit_exceeded" || message.toLowerCase().includes("period_limit_exceeded");
const retryable =
(status === 429 && !isPeriodCap) ||
status === 500 ||
status === 502 ||
status === 503;
return {
status,
surface,
type,
code,
param,
message,
retryAfterSec,
rateLimitLimit: parseIntHeader("x-ratelimit-limit-requests"),
rateLimitRemaining: parseIntHeader("x-ratelimit-remaining-requests"),
rateLimitReset: res.headers.get("x-ratelimit-reset-requests"),
retryable,
rawSnippet: rawBody.slice(0, 240),
};
}Notice the deliberate isPeriodCap branch. A 429 with code: "period_limit_exceeded" is not a transient traffic burst; it means a customer API key has exhausted its daily or monthly spending allocation. Marking it retryable: false stops workers from hammering the gateway every few seconds and routes the alert straight to your quota operations channel.
Anatomy of 10,000 Production API Errors: Where Incidents Really Originate
Whenever an AI feature degrades, engineering Slack channels almost reflexively blame upstream model providers first. Hard telemetry tells a less flattering story. Across an aggregate sample of 10,000 production API errors logged from live multi-model workloads—customer support chatbots, structured JSON extractors, autonomous coding loops, and overnight batch pipelines—88% of failures originated from client payloads, credential governance, quota configuration, or unthrottled bursts, while only 12% stemmed from upstream 502/503 instability.

The table below pairs that 10,000-error distribution with the blast radius of blind retries and the observed Mean Time to Resolution (MTTR) shift once teams adopt structured classification:
| Error Cluster | Share of 10,000 Errors | Incident Count | Dominant Real-World Trigger | Blast Radius Under Blind Retries | Typical MTTR (Ad-Hoc vs. Runbook) | |
|---|---|---|---|---|---|---|
HTTP 400 (invalid_request_error) | 31% | 3,100 | Missing required max_tokens on /v1/messages, orphaned tool messages after naive history truncation, malformed JSON schema constraints | Exhausts worker threads and pollutes p95 latency dashboards with dead traffic | 38 min vs. 4 min | |
HTTP 429 (rate_limit_error) | 24%()HTTP 401 & 403 (authentication_error / permission_error) | 19% | 1,900 | Unset TOPAI_API_KEY after deploy, trailing \r\n from Windows .env, revoked key, key_paused, or unallowed model ID | Burns through shared RPM buckets across pods, taking down healthy routes on the same key | 44 min vs. 5 min |
HTTP 402 (insufficient_quota) | 14% | 1,400 | Prepaid TOP Points balance below worst-case preflight estimate, oversized max_tokens, or depleted customer-key total cap | Spams error logs as impatient users mash retry buttons in the UI | 25 min vs. 4 min | |
HTTP 502 & 503 (api_error / overloaded_error) | 12% | 1,200 | Upstream provider brownouts after automatic gateway failover, peak frontier-model congestion | The only non-429 cluster that genuinely benefits from capped exponential backoff + jitter | 17 min vs. 2 min (auto-healed) |
Seeing HTTP 400 at 31% surprises teams until they audit dynamic user inputs. Static unit tests pass because hand-crafted fixtures are clean. Production traffic brings copy-pasted PDFs with broken UTF-16 surrogates, multi-turn tool histories sliced right between an assistant tool_call and its matching tool output, or strict JSON extraction schemas missing additionalProperties: false.
Meanwhile, 19% in 401/403 and 14% in 402 prove that a third of all production LLM failures are operational governance problems rather than code bugs. Separating credentials per workload, enforcing explicit model allowlists, and setting proactive balance alerts—practices we unpack in enterprise AI API key governance with caps, allowlists, and audit logs and prepaid pay-as-you-go TOP Points vs. $200 monthly subscriptions—eliminates this entire band before customers notice anything.
Complete HTTP 400–503 Status Code & Retry Policy Reference
Every status code returned by TOP AI carries a deterministic meaning and a strict retry contract. Bookmark this matrix for on-call triage:
| HTTP Status | error.type | Key Sub-Code / Signal | Exact Gateway Cause on TOP AI | Safe to Retry? | Deterministic Remediation |
|---|---|---|---|---|---|
| 400 | invalid_request_error | param identifies offending field | Malformed JSON, missing required field (e.g., max_tokens on Anthropic), invalid parameter range or role sequence | No | Fix request serializer and validate payloads client-side before sending |
| 401 | authentication_error | Missing / invalid auth header | Absent Authorization: Bearer tp-... or x-api-key: tp-..., wrong secret, whitespace corruption, or revoked key | No (until key is fixed) | Inspect secret injection and tp- prefix; mint a replacement key if revoked |
| 402 | insufficient_quota | TP balance < estimate / cap hit | Prepaid TOP Points balance is lower than the estimated cost of the request, or customer key total quota is spent | No (until balance/cap changes) | Top up TOP Points, raise the customer key quota, or lower max_tokens |
| 403 | permission_error | key_paused or allowlist denial | Requested model is outside the API key's allowlist, key is paused (key_paused), or account is suspended | No (until permissions change) | Add model ID to the key allowlist, unpause key in dashboard, or contact admin |
| 404 | not_found_error | param: "model" or bad path | Model ID does not exist or is inactive, or Anthropic SDK duplicated /v1 into /v1/v1/messages | No (until model/path fixed) | Query GET /v1/models for active raw IDs; set Anthropic base URL to https://topai.id |
| 413 | invalid_request_error | Request body > 8 MB | Total HTTP body exceeds the hard 8 MB gateway ceiling (commonly inline base64 images or massive logs) | No (until body shrinks) | Compress images, pass media via URL instead of base64, and prune old turns |
| 429 | rate_limit_error | rate_limit_exceeded + Retry-After | Request velocity exceeds per-key RPM limit (default 60 RPM, configurable via RATE_LIMIT_RPM) | Yes (after Retry-After + jitter) | Sleep Retry-After * 1000 ms + 0–250 ms jitter; smooth bursts with a queue |
| 429 | rate_limit_error | period_limit_exceeded | Customer key reached its configured daily or monthly spend limit | No (until reset / cap raised) | Halt retries immediately; page tenant owner or raise the period limit |
| 500 | api_error | Internal gateway exception | Transient server-side fault inside the gateway layer | Yes (backoff + jitter) | Retry up to 3–4 times with the same Idempotency-Key; escalate with request id if persistent |
| 502 | api_error | Upstream provider failure | Upstream failed even after TOP AI executed automatic failover | Yes (backoff + jitter) | Retry with capped exponential backoff + jitter; consider model fallback after 3 misses |
| 503 | overloaded_error | Upstream capacity saturation | Target inference cluster is overloaded under peak demand | Yes (backoff + jitter) | Back off aggressively (up to 8 s + jitter) or shed non-critical load to deepseek-v4-1-flash |

Why Blind Retries on 4xx Amplify Minor Bugs into Full Outages
Default HTTP retry middleware often ships with a lazy rule: "on any non-2xx status, retry 3 times." On a single developer laptop that seems harmless. Inside a 12-pod Kubernetes deployment sharing a TOP AI API key, that rule acts as a self-inflicted denial-of-service amplifier.
Suppose one new microservice route deploys with a typo in its model name (404) or asks for a model excluded from the key's allowlist (403). Every incoming user request now multiplies into four consecutive gateway hits within a second. Those guaranteed-to-fail retries chew straight through the default 60 RPM budget (or whatever custom RATE_LIMIT_RPM you configured), starving completely healthy checkout or support routes sharing the same credential until they start returning 429. Worse, while pods sit blocked waiting on doomed retries, connection pools fill up, request queues back up, and downstream API timeouts ripple across unrelated services.
The fix is binary and non-negotiable: fail fast on 400, 401, 402, 403, 404, 413, and 429 period_limit_exceeded. Log one structured warning, emit one metric increment, and return a clean degraded state to the caller immediately.
Per-Code Triage Deep Dive: Subtle Traps Behind Each Status
1. HTTP 400 (invalid_request_error) and HTTP 413 (> 8 MB Payload Ceiling)
When 400 spikes in production, check four frequent culprits before touching SDK versions:
- Cross-protocol required fields:
/v1/messageson the Anthropic path strictly requires an explicit integermax_tokens. Teams porting payloads from/v1/chat/completionsroutinely omit it and trigger instant400responses. - Broken tool-call history windows: Rolling context trimmers that drop messages by array index often evict the
assistantturn containingtool_callswhile leaving the subsequenttoolresult message intact. Always prune tool call/result pairs atomically as a single unit. - Strict JSON schema violations: Nested schemas passed via
response_formatfrequently fail validation if objects omitadditionalProperties: falseor mismatch required property lists. Cross-check your schema structure against the battle-tested patterns in our DeepSeek V4.1 Flash latency and strict JSON extraction audit. - The 8 MB HTTP 413 wall: Text prompts rarely cross 8 MB on their own, yet multimodal requests hit
413 invalid_request_errorconstantly. Base64 encoding inflates binary size by 33%, so attaching two 3.2 MB screenshots inline pushes the JSON body straight over 8 MB. Resize and convert uploads to WebP/JPEG under 1 MB or pass signed URLs instead of inline data URIs, and guard oversized text contexts ahead of time with zero-cost [preflight token counting using/v1/messages/count_tokens](/en/blog/preflight-token-counting-with-messages-count-tokens).
2. HTTP 401 (authentication_error) vs. HTTP 403 (permission_error)
Treat 401 and 403 as two totally different operational pages:
- 401 means "who are you?" Either no auth header reached TOP AI, the string interpolated literally as
Bearer undefined, a Windows CRLF\r\ncrept into a CI secret, the wrong header scheme was sent on a raw HTTP client, or thetp-key was revoked. - 403 means "we know your key, and policy says no." On TOP AI,
403 permission_errorspecifically fires when: (1) the requested model ID is outside the API key's configured model allowlist—common right after enabling a new model likegpt-6-1without updating the production key's allowlist; (2) the key has been paused (key_paused) by an operator or automated spend guard; or (3) the parent account is restricted.
3. HTTP 402 (insufficient_quota) — The max_tokens Preflight Trap
A recurring head-scratcher on prepaid gateways (1 TP = Rp 1): an account dashboard clearly shows remaining balance, yet requests to claude-sonnet-5-5 fail with 402 insufficient_quota.
Here is why: TOP AI checks whether your available balance covers the estimated worst-case cost of the incoming call before forwarding it upstream—factoring in input tokens plus your requested max_tokens ceiling. If a developer leaves max_tokens: 32768 as a lazy default on an endpoint that only ever returns 80 tokens of JSON, the gateway reserves headroom for 32,768 output tokens and rejects the call when remaining balance sits below that worst-case estimate. The second cause of 402 is a depleted customer-key total cap, even when the master wallet still holds millions of TP.
Live TOP AI API Pricing for Models Mentioned
Frequently Asked Questions
Why does blindly retrying HTTP 401, 402, or 403 errors turn a minor bug into a full outage?+
Status codes 400, 401, 402, 403, 404, and 413 are strictly deterministic: repeating the exact same payload will fail identically until the request body, tp- key, TOP Points balance, model allowlist, or payload size changes. Blindly retrying three to five times multiplies traffic across pods, drains the default 60 RPM rate-limit bucket for healthy endpoints sharing the same key, and saturates worker queues.
What is the operational difference between 429 rate_limit_exceeded and 429 period_limit_exceeded on TOP AI?+
rate_limit_exceeded occurs when request velocity crosses the per-minute ceiling (60 RPM per API key by default, configurable via RATE_LIMIT_RPM) and recovers cleanly after honoring the Retry-After header plus random jitter. period_limit_exceeded means a customer key has hit its daily or monthly spending cap, so short-term retries will keep failing until the period rolls over or an operator increases the cap.
Why did TOP AI return HTTP 200 OK with [MODE SIMULASI] at the start of the text?+
When topai.upstream reports simulasi and the reply starts with [MODE SIMULASI], it is not a gateway error or SDK malfunction. It signals that upstream provider credentials are not configured on that server instance while real token accounting and balance deductions remain active so billing flows can be tested end to end.






