# Claude Code Errors: 401, 402, 429, 529, "prompt is too long"

> **Short answer (verified 2026-11-20)**: These messages mean different things: `401` is an authentication failure, `402` means the quota is used up or the balance is insufficient, `429` means a rate or concurrency limit was hit, `529` means the API is overloaded for everyone, and `Credit balance is too low` means the account has run out of prepaid credits. Use the table below to find the meaning and first step for each exact message, then jump to the matching section for the full fix.

| Error text | Meaning | First step |
|---|---|---|
| `Credit balance is too low` | The Console organization is out of prepaid credits, or a subscription user is sending requests with an API key | Run `/status` to see the active credential; unset `ANTHROPIC_API_KEY`, or add credits in the Console |
| `Invalid API key` | The key from the environment or `apiKeyHelper` was rejected by the API | Check for typos and revocation, inspect all `ANTHROPIC` variables with `env`, and run `/status` |
| `API Error: 401 Invalid authentication credentials` | The credential format was recognized, but the account or organization was rejected | Run `/status` to identify the credential source, then rotate the key or run `/login` again |
| `Request rejected (429)` | The rate limit for the API key, Bedrock project, or Google Cloud project was reached | Run `/status`, check the provider console limits, and reduce concurrency |
| `API Error: Repeated 529 Overloaded errors` | The API is temporarily at capacity for all users, not your usage limit | Check the service status page, retry in a few minutes, or switch models with `/model` |
| `Your account is on hold` | The Claude account behind the login has been suspended | Open the link in the message to view details or appeal, or use an unaffected account or key |

## Paste-the-message dictionary (checked 2026-11-29)

Find the exact text you saw. The same words can come from QCode or from Anthropic, so each row says which side it points to and gives the one check that settles it.

| Message you pasted | With a QCode key (`cr_`) | With an Anthropic subscription or Console key | One check |
|---|---|---|---|
| `Invalid API key` / HTTP 401 | The key is mistyped, disabled or expired (an expired key returns 401, not 402) | A stale `ANTHROPIC_API_KEY` or `apiKeyHelper` is being rejected, or the login expired | Run `/status`, then `echo $ANTHROPIC_AUTH_TOKEN` and confirm it starts with `cr_`; details in [401](/docs/reference/errors) below |
| HTTP 402 `insufficient_quota` (`daily_cost_limit_exceeded`, `total_cost_limit_exceeded`) | Your QCode quota is used up; it does not clear by resending | Not an Anthropic message | Read `error.code`; renew a [Pay-as-you-go Pack](/docs/reference/payg-packs) or buy a booster pack, see [payment methods](/docs/reference/payment-methods) and [Quota exhausted](/docs/reference/errors#402-quota-exhausted) |
| `Credit balance is too low` | Not QCode's quota message (QCode quota ends in a 402 above); seeing it means requests are reaching Anthropic, not QCode | The Console organization has no prepaid credits, or a subscription user is sending an API key | `/status` and `echo $ANTHROPIC_BASE_URL` (should be `https://api.qcode.cc/api`); see [Subscriptions vs API keys](/docs/reference/subscription-vs-api-key) |
| `Usage limit reached… your limit will reset on…` / `Claude usage limit reached` | Not a QCode message; QCode quota errors are the 402 above and the daily quota resets at 00:00 Beijing time | The 5-hour or weekly limit of the Claude subscription; the reset time tells which | `/status`: if it shows a subscription login, Claude Code is not using your QCode key |
| `Request rejected (429)` / HTTP 429 | A rate or concurrency limit was hit; a used-up quota is a 402, not a 429 | The rate limit of the API key or project | Cut concurrency, wait 30-60 s; limits per plan are in the [FAQ](/docs/reference/faq) |
| HTTP 413 `request_too_large` / `Request too large (max 32MB)` | The request body is too many bytes (large images, PDFs, long history); not a token or quota problem | Same | Remove oversized images / files and run `/compact`; images over 25 MB return `413 image_too_large`, see [Image 2](/docs/usage/image-2) |
| `prompt is too long` (HTTP 400) | The conversation no longer fits the model's context window; not billing | Same | `/compact` or `/clear`, see [Context management](/docs/usage/context-management) |
| HTTP 529 `Overloaded` | The model is at capacity for everyone, not your quota | Same | Wait a few minutes, switch with `/model`, or try another endpoint domain, see [529](/docs/reference/errors) below |
| `server is busy` / service busy | QCode does not use this exact text for key or quota problems; treat it as temporary overload (503 / 529) | Provider-side capacity | Retry with backoff, switch model; if it persists, contact support with the time and model id |
| `404` with `Invalid URL (POST /v1/v1/messages)` or `Route /api/messages not found` | The base URL has an extra `/v1`, a trailing slash, or a wrong path | Same | Set `ANTHROPIC_BASE_URL` to exactly `https://api.qcode.cc/api` (`https://asia.qcode.cc/api` in Mainland China); see [Endpoints](/docs/getting-started/endpoints-and-api-paths) |

This document provides detailed information about various error codes you may encounter while using Claude Code and their solutions.

## Error Code Quick Reference

| Code | Type | Description | Severity |
|------|------|-------------|----------|
| 400 | Client Error | Malformed request | Low |
| 401 | Auth Error | Invalid API Key | Medium |
| 402 | Quota / Service Error | Quota used up, or service temporarily refusing | Medium |
| 403 | Permission Error | Access denied | Medium |
| 429 | Rate Limit | Too many requests | Medium |
| 500 | Server Error | Internal error | High |
| 502 | Gateway Error | Backend unavailable | High |
| 503 | Service Unavailable | Temporarily overloaded | High |
| 529 | API Overloaded | Claude API overloaded | High |

---

## 429 - Too Many Requests

One of the most common errors, indicating too many requests in a short period.

### Error Message

```text
Error: 429 Too Many Requests
Rate limit exceeded. Please slow down your requests.
```

### Common Causes

1. **Too frequent requests**: Sending multiple requests in rapid succession

2. **Too many concurrent requests**: Running multiple Claude Code instances simultaneously

3. **Token limit reached**: Consuming too many tokens in a short time

> **Running out of quota is not a 429**: when the daily, total or weekly quota is used up, the response is **402** (`insufficient_quota`) — see [Quota exhausted](/docs/reference/errors) on this page.

### Solutions

**Immediate Actions**:
```bash
# Wait 30-60 seconds before retrying
sleep 60 && claude "your question"
```

**Long-term Solutions**:

1. Reduce request frequency, avoid rapid consecutive sends

2. Use `/compact` command to compress context

3. Split large tasks into smaller batches

> **QCode.cc Advantage**: Professional load balancing to distribute request pressure, effectively reducing 429 errors.

---

## 502 - Bad Gateway

Indicates the gateway or proxy server received an invalid response from the backend.

### Error Message

```text
Error: 502 Bad Gateway
The server received an invalid response from the upstream server.
```

### Common Causes

1. **Backend temporarily unavailable**: Anthropic API server issues

2. **Network connection interrupted**: Connection dropped during request

3. **Proxy server issues**: Intermediate node failure

4. **Request timeout**: Response time exceeded gateway limit

### Solutions

**Immediate Actions**:
```bash
# Check network connection
curl -s -o /dev/null -w '%{http_code}\n' \
  -H "Authorization: Bearer $ANTHROPIC_AUTH_TOKEN" https://api.qcode.cc/openai/v1/models

# Wait and retry
sleep 30 && claude "your question"
```

**Long-term Solutions**:

1. Check local network stability

2. Try switching network environments

3. Use VPN or more stable network

4. Contact support if persistent

> **QCode.cc Advantage**: Multi-region deployment, CDN acceleration, automatic failover.

---

## 401 - Unauthorized

Invalid API Key or missing valid authentication.

### Error Message

```text
Error: 401 Unauthorized
Invalid API key or authentication token.
```

### Common Causes

1. **Incorrect API Key**: Missing characters or extra spaces when copying

2. **Expired API Key**: Subscription has expired

3. **Disabled API Key**: Banned due to policy violation

4. **Environment variable not set**: `ANTHROPIC_AUTH_TOKEN` not configured

### Solutions

**Verify API Key**:
```bash
# Check environment variable
echo $ANTHROPIC_AUTH_TOKEN

# Confirm correct format (starts with cr_)
# Correct example: cr_xxxxxxxxxxxxxxxxxxxx
```

**Steps**:

1. Login to [QCode.cc Dashboard](https://qcode.cc/dashboard) to check API Key status

2. Confirm subscription is active

3. If banned, contact support

---

## 402 - Payment Required

A 402 can mean two different things; check the response body first. If `error.type` is `insufficient_quota`, your **quota has run out** (see [Quota exhausted](/docs/reference/errors)); otherwise the model service is temporarily refusing (see [Service temporarily refusing](/docs/reference/errors)).

<a id="402-quota-exhausted"></a>

### Quota exhausted (`insufficient_quota`)

The response is HTTP 402 with `error.type` = `insufficient_quota`; the `code` tells you which quota ran out:

| code | Meaning | How it recovers |
|------|---------|-----------------|
| `daily_cost_limit_exceeded` | The daily quota is used up | Resets automatically at **00:00 Beijing time**; if today is not enough, buy a booster pack in the [console](https://qcode.cc/dashboard) |
| `total_cost_limit_exceeded` | The total quota is used up; applies to keys billed against a total quota, for example the total quota of a Pay-as-you-go Pack or the monthly quota of the Ultimate plan | Recovers according to your plan's rules: for Pay-as-you-go Packs, buy any pack again to continue on the same key; the Ultimate monthly quota is topped up at each monthly reset; contact support if unsure |
| `weekly_opus_cost_limit_exceeded` | The weekly limit for Claude models is used up | Resets automatically every week; see the [Console Guide](/docs/reference/dashboard-guide) |

Example response body (total quota used up):

```json
{
  "error": {
    "type": "insufficient_quota",
    "message": "...",
    "code": "total_cost_limit_exceeded"
  },
  "currentCost": 100.42,
  "costLimit": 100
}
```

The `message` text is a short Chinese-language notice, so rely on `type` and `code`. The amount in its parentheses (for example `$100`) is the **limit** of that quota — for the total quota it is the **cumulative limit** — not what is left.

This kind of 402 does not go away by resending; do not write a retry loop, restore the quota as in the table instead.

An expired key returns **401**, not 402 (`{"error":"Invalid API key","message":"API key has expired"}`) — see the 401 section above.

---

<a id="402-service-refused"></a>

### Service temporarily refusing the request

When the body has no `insufficient_quota`, the model service chain refused this request. **This is usually not a problem with your key or your configuration** — requests from the same key to other models at the same time normally succeed.

#### What you see

```text
Error: 402 Payment Required
```

In Claude Code it usually looks like the request simply failing with no response content; from a script or SDK you get HTTP 402.

#### Common causes

1. **The model service is temporarily unavailable**: this kind of 402 comes from the service chain, and the QCode gateway relays the status as-is

2. **Concentrated on one model**: at any given moment one model may see a high 402 rate while the others are completely fine

3. **Depends on the endpoint domain**: different domains route through different service paths, and the chance of hitting a 402 can differ substantially

4. **Not related to your balance**: this kind of 402 is not caused by running out of balance or plan quota; a quota 402 carries `insufficient_quota`, see [Quota exhausted](/docs/reference/errors) above

#### What to do

**1. Switch model (most effective)**

```bash
# Switch inside a session
/model sonnet

# Or specify at launch
claude --model claude-sonnet-5-5
```

**2. Switch endpoint domain**

```bash
# Mainland China
export ANTHROPIC_BASE_URL=https://asia.qcode.cc/api

# Global (Route 53 picks the nearest node)
export ANTHROPIC_BASE_URL=https://api.qcode.cc/api
```

All three domains take the same key, so switching needs no other configuration change. See [Endpoints & API Formats](/docs/getting-started/endpoints-and-api-paths).

**3. Don't write a tight retry loop**

A 402 does not go away by resending immediately; hammering only makes it worse. Use exponential backoff, or just switch model — see "Error handling best practices" on this page.

**4. If it persists, contact support**

Include the time it happened, the model id and the endpoint domain, and reach us through [live chat](javascript:void(Tawk_API.toggle())) or [hi@qcode.cc](mailto:hi@qcode.cc).


#### `INSUFFICIENT_BALANCE` / `Insufficient account balance`

Some 402/403 responses carry JSON like `"code":"INSUFFICIENT_BALANCE", "message":"Insufficient account balance"`. **This does not mean your QCode balance ran out.** It is a temporary condition somewhere in the service chain, passed through verbatim — unrelated to your account. When your own quota is used up, the body carries `insufficient_quota` with a `*_cost_limit_exceeded` code (see [Quota exhausted](/docs/reference/errors) above).

What to do: wait and retry / switch model / switch access domain (steps ①–③ above all apply); if it persists, contact support with the request id. Full checklist: [troubleshooting guide](/docs/reference/troubleshooting).

---

## 403 - Forbidden

Request rejected by server, usually due to insufficient permissions.

### Error Message

```text
Error: 403 Forbidden
You don't have permission to access this resource.
```

### Common Causes

1. **Wrong API endpoint**: Using incorrect API address

2. **Insufficient permissions**: Current plan doesn't support this feature

3. **Regional restrictions**: Some features unavailable in certain regions

4. **Account status issues**: Account restricted

### Solutions

```bash
# Confirm API endpoint is correct
echo $ANTHROPIC_BASE_URL
# Should be: https://api.qcode.cc/api
```

1. Verify API endpoint configuration

2. Confirm plan includes required features

3. Contact support to verify permissions


### `INSUFFICIENT_BALANCE` (when it appears on a 403)

If a 403 Forbidden body contains `INSUFFICIENT_BALANCE` / `Insufficient account balance`, this is again usually a temporary backend condition relayed verbatim — **not your account being restricted**. Handle it as in the same-named subsection of the 402 section; see the [troubleshooting guide](/docs/reference/troubleshooting) for the full order.

---

## 400 - Bad Request

Incorrect request format or invalid parameters.

### Error Message

```text
Error: 400 Bad Request
The request was malformed or contained invalid parameters.
```

### Common Causes

1. **Malformed request**: Incorrect JSON format

2. **Missing parameters**: Required parameters not provided

3. **Invalid values**: Parameter values out of allowed range

4. **Encoding issues**: Special characters not properly encoded

### Solutions

```bash
# Check for special characters in input
# Ensure request content is properly formatted
claude -p "simple test"
```

1. Simplify input, exclude special characters

2. Ensure file paths use correct encoding

3. Check command parameter format

---

## 500 - Internal Server Error

Server encountered unexpected condition preventing request completion.

### Error Message

```text
Error: 500 Internal Server Error
An unexpected error occurred on the server.
```

### Common Causes

1. **Server-side bug**: API server code issue

2. **Resource exhaustion**: Server resources temporarily depleted

3. **Configuration error**: Server misconfiguration

### Solutions

```bash
# Wait and retry
sleep 60 && claude "your question"

# Use verbose mode for more info
claude --verbose
```

1. Wait a few minutes and retry

2. Check [QCode.cc](https://qcode.cc) service status

3. Contact support with error details if persistent

### E015 - Conversation Context Overflow

Triggered when the conversation context approaches the model's capacity limit (~95%). QCode.cc wraps this error as a 429 response to trigger a retry:

```text
429 {"error":{"code":"E015","message":"Internal server error"},"status":500}
```

**Solution**: See the "Long Session Overflow Prevention" section in [Context Management](/docs/usage/context-management).

---

## 503 - Service Unavailable

Server temporarily unable to handle requests, usually due to overload or maintenance.

### Error Message

```text
Error: 503 Service Unavailable
The service is temporarily unavailable. Please try again later.
```

### Common Causes

1. **Server overload**: Request volume exceeds capacity

2. **Scheduled maintenance**: Server under maintenance

3. **Resource exhaustion**: Server resources temporarily insufficient

### Solutions

```bash
# Use exponential backoff retry
for i in 1 2 4 8 16; do
  claude "your question" && break
  echo "Retrying, waiting ${i} seconds..."
  sleep $i
done
```

1. Wait a few minutes and retry

2. Use exponential backoff retry strategy

3. Check service status announcements

---

## 529 - Overloaded

Claude API-specific error code indicating API service overload.

### Error Message

```text
Error: 529 Overloaded
The API is temporarily overloaded. Please try again later.
```

### Common Causes

1. **Global usage surge**: Claude service global user spike

2. **Peak hours**: Concentrated requests during work hours

3. **Popular events**: Certain events causing usage surge

### Solutions

```bash
# Retry later
sleep 120 && claude "your question"
```

1. Wait 2-5 minutes and retry

2. Avoid peak hours (US business hours)

3. Use `/compact` to reduce token usage

> **QCode.cc Advantage**: Load-distribution mechanisms effectively spread overload pressure.

---

## Connection Timeout

Request failed to complete within the specified time.

### Error Message

```text
Error: Connection timed out
The request timed out while waiting for a response.
```

### Common Causes

1. **Unstable network**: Poor network connection quality

2. **Request too large**: Too many context tokens

3. **Task too complex**: AI processing time too long

4. **Slow server response**: High server load

### Solutions

```bash
# Test network connection
ping api.qcode.cc

# Use compact mode to reduce context
/compact
```

1. Check network connection stability

2. Use `/compact` to compress context

3. Split complex tasks into simpler ones

4. Try more stable network environment

### Long responses cut off after about 5 minutes (Claude Code on QCode or another custom base URL)

As of November 19, 2026: if Claude Code reaches QCode through `ANTHROPIC_BASE_URL` and a response that stays quiet for a long time (extended thinking, a large file being written) is cut off at about five minutes, check your Claude Code version first. The Claude Code 2.1.328 changelog (2026-11-19) says: "Fixed `CLAUDE_STREAM_IDLE_TIMEOUT_MS` not lengthening the 5-minute connection limit on gateways, custom base URLs and cloud providers". Before that release, the variable could not extend the 5-minute limit on gateways or custom base URLs.

1. Upgrade to 2.1.328 or later: run `claude update`, then confirm with `claude --version`

2. Then set the streaming idle timeout if you need it (milliseconds). Per the official docs, when you set it explicitly the minimum is `300000` (5 minutes) and lower values are silently clamped up; the byte-level watchdog caps it at 30 minutes

```bash
# Example: 15-minute streaming idle timeout
export CLAUDE_STREAM_IDLE_TIMEOUT_MS=900000
```

3. Don't confuse it with `API_TIMEOUT_MS`: per the official docs, that is the time each request attempt has to receive its response headers (default 600000, or 10 minutes); it doesn't limit how long a streaming response runs after that

Sources: Claude Code [CHANGELOG 2.1.328](https://github.com/anthropics/claude-code/blob/main/CHANGELOG.md) and the [environment variables reference](https://code.claude.com/docs/en/env-vars) (checked 2026-11-19).

---

## MCP Server Errors

Errors that can come from MCP server configuration or runtime.

### Symptoms

```text
MCP server "xxx" failed to start
MCP connection timed out
MCP tool execution failed
```

### Common Causes

1. **Wrong server command**: npx package name typo or not installed

2. **Missing environment variables**: the token the MCP server needs is not set

3. **Timeout**: server start-up or execution takes too long

4. **Insufficient permissions**: file system / database access denied

### Solutions

```bash
# Check server status with /mcp
/mcp

# Diagnose configuration issues with /doctor
/doctor

# Manually test whether the MCP server can start
npx -y @modelcontextprotocol/server-filesystem /tmp
```

1. Check connection status with `/mcp`

2. Run automatic diagnostics with `/doctor`

3. Verify the format of `~/.claude/settings.json` or `.mcp.json`

4. Make sure required environment variables are set (`$GITHUB_TOKEN` etc.)

5. Increase timeouts with the `MCP_TIMEOUT` and `MCP_TOOL_TIMEOUT` environment variables

---


## General Troubleshooting Steps

When encountering any error, follow these steps:

### 0. Run automatic diagnostics

```bash
# Claude Code's built-in diagnostic tool
/doctor
```

This automatically checks common configuration issues: environment variables, API connectivity, MCP server status and more.


### 1. Check Network Connection

```bash
# Test API endpoint connectivity
curl -s -o /dev/null -w '%{http_code}\n' \
  -H "Authorization: Bearer $ANTHROPIC_AUTH_TOKEN" https://api.qcode.cc/openai/v1/models

# Test DNS resolution
nslookup api.qcode.cc
```

### 2. Verify Environment Variables

```bash
# Check all relevant environment variables
echo "BASE_URL: $ANTHROPIC_BASE_URL"
echo "AUTH_TOKEN: ${ANTHROPIC_AUTH_TOKEN:0:10}..."
```

### 3. Enable Detailed Logging

```bash
# Use verbose mode for detailed info
claude --verbose

# Or set debug mode
DEBUG=true claude
```

### 4. Test Simple Request

```bash
# Send simple test request
claude -p "say hello"
```

### 5. Check Service Status

Visit [QCode.cc](https://qcode.cc) for service status announcements.

---

## Error Handling Best Practices

### Implement Retry Mechanism

```bash
# Simple retry script
retry_claude() {
  local max_attempts=3
  local attempt=1

  while [ $attempt -le $max_attempts ]; do
    claude "$@" && return 0
    echo "Attempt $attempt failed, retrying..."
    sleep $((attempt * 2))
    ((attempt++))
  done

  echo "All attempts failed"
  return 1
}
```

### Monitor Usage

Regularly check API usage to avoid exceeding quota:

1. Login to [QCode.cc Dashboard](https://qcode.cc/dashboard)

2. View usage statistics

3. Set usage alerts

### Optimize Requests

1. **Reduce context**: Regularly use `/compact` or `/clear`

2. **Batch processing**: Split large tasks into smaller ones

3. **Avoid duplication**: Cache common results

---

## Getting Help

If the above solutions don't resolve your issue, contact QCode.cc support:

- **Live Chat**: Bottom right corner of website

- **Response Time**: 1-2 hours during business hours

- **Support Hours**: 10:00–22:00 daily

When contacting support, please provide:

1. Complete error message

2. Command executed

3. Time of occurrence

4. API Key prefix (never share full key)