A 402 payment required error llm api is an HTTP response status that signals the inference provider rejected the request because the calling account cannot cover the estimated token cost. It is a billing-level halt, not a rate limit or authentication failure. In practice, LLM gateways and model hosts repurpose the seldom-used HTTP 402 code to enforce prepaid balances and hard spend caps before generating any tokens.
What the 402 status code originally meant
The HTTP/1.1 spec reserved 402 (“Payment Required”) as a non-standard, experimental code for future use where a server might require payment for a resource. Almost no traditional web services adopted it; most billing flows moved to paywalls, 403s, or application-level error objects. LLM APIs brought it back because token generation has a directly metered, per-request marginal cost that can be computed before the work is done.
The semantics are simple: the server evaluated the request, determined it would incur cost, and concluded the client has no authorized way to pay. No tokens are produced. The connection is closed with a 4xx class status.
How LLM APIs use 402 differently from classic HTTP
Classic APIs treat 402 as undefined. LLM platforms assign it concrete meaning:
- The account has no usable prepaid credit.
- The attached payment method failed validation or was declined.
- A hard monthly or per-minute spend limit is already reached.
- The requested model is restricted in the caller’s region or plan tier.
This is distinct from a 401 (bad key), 403 (forbidden scope), or 429 (too many requests). A 402 payment required error llm api means the identity is known and authorized, but the money path is not.
Why the 402 payment required error llm api happens
Insufficient prepaid balance
Most inference gateways operate prepaid. You deposit credits; each request deducts based on prompt and completion token counts. If the estimated cost exceeds remaining balance, the gateway returns 402 before calling the upstream model. The estimate uses max_tokens and input length, so a large max_tokens on a near-empty account triggers it even if the actual completion would be short.
Missing or invalid payment method
Postpaid or hybrid plans require a card on file. If the card expires, fails 3-D Secure, or is blocked by the processor, the API shifts to a frozen state. New requests get 402 with a code like card_declined or no_payment_method.
Spend caps and hard limits
Account settings often define a hard cap separate from the balance. A team can have $500 in credit but a $50/day limit. At 12:01 AM UTC after a heavy day, the next request sees the cap reset, but if the cap is hit mid-day, 402 fires regardless of remaining wallet funds.
Currency and region restrictions
Some models are not billable in certain jurisdictions. The API may reject with 402 rather than 403 because the failure is fundamentally “cannot charge you for this.” This surfaces often with newer frontier models under export controls.
How a typical response looks
A minimal JSON body from an OpenAI-compatible endpoint:
{
"error": {
"message": "Insufficient balance to cover estimated token cost.",
"type": "invalid_request_error",
"code": "insufficient_balance",
"param": null
}
}
The HTTP status line is HTTP/1.1 402 Payment Required. Headers may include Retry-After only if the provider expects auto-resolution (rare), and X-Request-Id for support tracing.
Handling the error in code
Treat 402 as a terminal, human-intervention state for the current credentials. Do not retry with the same auth token blindly.
Python example
import requests
import os
def complete(prompt: str) -> dict:
resp = requests.post(
"https://api.example.com/v1/chat/completions",
headers={"Authorization": f"Bearer {os.environ['KEY']}"},
json={"model": "gpt-4o-mini", "messages": [{"role": "user", "content": prompt}]},
timeout=30,
)
if resp.status_code == 402:
# Surface to billing owner, do not loop
raise SystemExit(f"Billing halt: {resp.json()['error']['message']}")
resp.raise_for_status()
return resp.json()
TypeScript example
async function complete(prompt: string): Promise<unknown> {
const res = await fetch("https://api.example.com/v1/chat/completions", {
method: "POST",
headers: { Authorization: `Bearer ${process.env.KEY}` },
body: JSON.stringify({ model: "gpt-4o-mini", messages: [{ role: "user", content: prompt }] }),
});
if (res.status === 402) {
const body = await res.json();
console.error("Payment required:", body.error.code);
throw new Error("billing_required");
}
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}
In both cases, the caller should route the signal to a billing alert, not a retry queue.
Why it matters for production systems
A 402 payment required error llm api breaks silently if your code assumes any 4xx is a transient client bug. In a nightly batch job, a depleted balance means zero completions and a pile of dead letters. In a user-facing chat, it means a hard failure unless you catch and render “service temporarily unavailable” with a fallback path.
Multi-tenant systems need per-tenant balance tracking. If you proxy many sub-accounts through one gateway key, the gateway’s 402 reflects your aggregate balance, not the end user’s. You must map the error back to the correct internal ledger and possibly switch to a backup payment instrument or provider.
An inference gateway such as n4n.ai meters per-token usage and will return 402 when the account balance cannot cover the estimated cost before forwarding to upstream models; its automatic fallback only triggers on provider degradation, not on billing failure, so your code must still handle 402 explicitly.
Common misconceptions
“402 is just a rate limit”
No. A 429 carries Retry-After and clears when traffic drops. A 402 persists until a human adds funds or raises a cap. Treating them identically causes infinite retry storms that never succeed.
“402 means the model is down”
The model is healthy. Your wallet is not. Routing to a different region or model on the same broke account yields the same 402.
“Retrying will eventually succeed”
Only if a webhook or cron replenishes credit between attempts. Without that, a retry loop burns CPU and may trip abuse detection. Exponential backoff without a credit event is pointless.
“402 is standardized across all LLM APIs”
OpenAI, Anthropic, and open-router-style gateways use it for billing, but some smaller hosts return 400 with an error code, or 403. Never assume the numeric status alone; parse the error code field.
“It only happens at account creation”
Experienced teams hit it mid-flight when a large max_tokens request lands after a quiet period drained the wallet via background evals. It is a runtime condition, not onboarding friction.
Gateway behavior and routing directives
When you send X-Route: provider-a or similar headers, a gateway forwards your intent. If provider-a is degraded, the gateway may auto-fallback to provider-b. But if your account shows insufficient balance, the gateway short-circuits with 402 before any routing. Honoring client routing directives does not bypass billing. Likewise, provider cache-control hints (cache_control in the body) reduce cost but do not exempt you from the balance check.
Preventing unexpected 402s
- Set a webhook on balance thresholds. Most gateways emit
balance.lowevents at 20% and 5%. - Use conservative
max_tokens. Estimate withlen(prompt) / 4tokens and add headroom, not 4096 blind. - Run a pre-flight
GET /v1/account(if offered) in health checks to catch zero-balance before user requests. - Separate keys per environment. A staging key that hits 402 should not block production.
- For batch jobs, checkpoint progress so a mid-run 402 resumes after top-up instead of restarting.
The 402 payment required error llm api is a clear signal: stop, fund, reconfigure. Build your client to respect it, alert on it, and never confuse it with capacity or auth errors.