# Errors and rate limits

Both APIs return errors in a consistent JSON envelope:

```json
{
  "errors": {
    "detail": "Error message describing the issue"
  }
}
```

The HTTP status code tells you what went wrong. The `detail` string gives the specifics. Read both before deciding whether to retry.

## Status codes

| Status | Meaning                                    | What it means                                                                                                                                                                        | What to do                                                                                                                                                                                                                  |
| ------ | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `307`  | Temporary redirect                         | Your request is being routed to a supplier endpoint. The `Location` header points to the target.                                                                                     | Follow the redirect with the same method, body, and `Authorization` header. Most clients do this automatically. cURL needs `-L`. See [Request routing and redirects](/docs/api-reference/request-routing-and-redirects.md). |
| `400`  | Bad request                                | Malformed body or invalid parameter types.                                                                                                                                           | Fix the request. Check required fields and parameter types against the OpenAPI block on the relevant endpoint page. Don't retry as-is.                                                                                      |
| `401`  | Unauthorized                               | Missing or invalid API key. On the Trading API, also fires for invalid signatures or stale timestamps.                                                                               | Verify the key in the dashboard. Check that your auth header is `Authorization: Bearer ...` (Consumption) or that signature, timestamp, and fingerprint headers are correct (Trading). Don't retry without fixing.          |
| `402`  | Payment required                           | Insufficient USD balance, or no token capacity available for this instrument.                                                                                                        | Add credits, enable [auto-reload](broken://pages/pdlcsdUZJSSSfhsYQcIu), or wait for the system to top up automatically. **Retry** after a short delay; the next request usually goes through once balance replenishes.      |
| `404`  | Not found                                  | Most commonly: invalid instrument string in the `model` parameter. Also fires for unknown order IDs, market IDs, etc.                                                                | Check the value against the catalog at [Current instruments](/docs/instrument-specifications/current-instruments.md) or `https://thegrid.ai/instruments.json`. Don't retry.                                                 |
| `422`  | Validation error                           | Request is well-formed but a parameter value is out of range or structurally invalid. Common causes: `temperature` outside 0–2, malformed `tools` schema, invalid `response_format`. | Read the `detail`. Fix and resubmit. Don't retry as-is.                                                                                                                                                                     |
| `429`  | Rate limit exceeded                        | You hit the per-key request limit.                                                                                                                                                   | Back off and **retry**. Check the `Retry-After` header if present, otherwise use exponential backoff with jitter starting at 1 second.                                                                                      |
| `500`  | Internal server error                      | Server-side issue, often supplier transient errors surfaced through the API.                                                                                                         | **Retry** with exponential backoff. If persistent, contact <support@thegrid.ai>.                                                                                                                                            |
| `503`  | Service unavailable / balance replenishing | Temporary supplier unavailability, or the system is replenishing your balance.                                                                                                       | Wait 1 to 3 seconds and **retry**. The system handles supplier failover automatically; we don't bill your request if it doesn't complete.                                                                                   |

## Retry guidance

Always retry: `402`, `429`, `500`, `503`, and any other `5xx`. These are transient and a backoff loop fixes them. Don't retry `400`, `401`, `404`, or `422` without changing the request first; you get the same error.

A reasonable retry policy:

```python
import time, random

def call_with_retry(fn, max_attempts=5):
    for attempt in range(max_attempts):
        try:
            return fn()
        except RetryableError as e:
            if attempt == max_attempts - 1:
                raise
            delay = min(2 ** attempt + random.random(), 30)
            time.sleep(delay)
```

Cap the backoff somewhere sensible (e.g., 30 seconds) so you don't stall a worker indefinitely. Honor `Retry-After` when the server sends it.

### Backup routing transparency

We route around supplier failures automatically. If the primary supplier for an instrument is unavailable, we try the next one. Your client doesn't see which supplier served the request, and you don't need failover code in your application. If a request fails entirely or returns a response that doesn't meet the instrument's specification, we don't bill you for it.

This means you should treat `5xx` errors as transient by default. Most resolve on retry without any action on your end.

## Rate limits

Rate limits are enforced per API key, per endpoint group. They depend on your plan.

For current values, check the dashboard at [app.thegrid.ai/profile/api-keys](https://app.thegrid.ai/profile/api-keys); your plan's limits are listed there. Response headers (`Retry-After`, plus rate-limit headers when present) are documented in the OpenAPI blocks on each endpoint page.

When you hit a `429`:

1. Read `Retry-After` if present. It tells you exactly how long to wait.
2. If absent, use exponential backoff with jitter starting at 1 second.
3. Streaming and non-streaming requests count equally.
4. If your team consistently hits limits at the edge of your plan, talk to support. We raise limits on enterprise plans.

Rate limits behave the same in Auto Mode and Advanced Mode.

## Trading API specifics

The Trading API surfaces the same error shape, with a few extras:

* `401` from the Trading API is most often a signing error. Check timestamp drift first (your clock vs. server time), then the message format you signed (`<timestamp><METHOD><path><body>`), then the fingerprint header. See [Authentication](/docs/api-reference/authentication.md).
* `409` fires on order operations with state conflicts (e.g., cancelling an already-cancelled order). Don't retry; the state is final.
* `422` on order placement usually means a price or quantity violates instrument rules. The OpenAPI block on the [Trading API](/docs/api-reference/trading-api.md) page documents tick size and lot size constraints per endpoint.

The full Trading API error catalog is documented in the OpenAPI blocks on the [Trading API](/docs/api-reference/trading-api.md) page.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://thegrid.ai/docs/api-reference/errors-and-rate-limits.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
