401 or 429 error when calling an OpenAI-compatible API: what does it mean and how do I fix it?

A 401 means the API rejected your authentication (key or base URL); a 429 means too many requests or no balance left. Here's how to tell them apart and fix each one step by step.

In an OpenAI API 401 or 429 error, the 401 means your authentication was rejected: wrong, badly copied or revoked key, or the wrong base URL. The 429 means too many requests or no balance or quota left. With Dongee AI Router, an OpenAI-compatible gateway to several models, check base URL, key, model limits and prepaid balance first.

In most cases the problem is in your configuration, not in the service. If you work through the checks in order, it takes a few minutes to fix.

Updated November 26, 2026 · Dongee Team

What does a 401 error mean in an OpenAI-compatible API?

The 401 (Unauthorized) code is a standard HTTP status: the server received the request but could not verify who sent it. You can read the full definition in the MDN reference for the 401 status. When you use the OpenAI SDK with a different base URL, these are the most common causes:

  • Badly copied key: leading or trailing spaces, line breaks or quotes got into the .env file.
  • The environment variable is not loaded: the process starts without reading the .env file or, on the server, the variable was never defined.
  • The key and the base URL don't match: you are using one provider's key against another provider's base URL. This happens a lot when you forget to set baseURL and the SDK points to its default URL.
  • Malformed header: if you call the API without an SDK, the header must be Authorization: Bearer YOUR_KEY, with the word Bearer followed by a space.
  • Revoked or deleted key: someone deleted or rotated it and your app is still using the old one.

What does a 429 error mean?

A 429 (Too Many Requests) covers two different situations. Tell them apart, because each one needs a different fix:

  • Rate limit: you sent too many requests or too many tokens in a short time. It is temporary, and waiting and retrying solves it.
  • Quota or balance exhausted: the account has no credit left. However many times you retry, it will keep failing until you top up.

To tell which one you have, read the error body, not just the code. If the message talks about rate limit or requests per minute, it's speed. If it mentions quota, balance or credit, it's money. The OpenAI error codes guide describes these messages for its own API, and most compatible APIs use a similar format.

How do I fix it step by step?

  1. Check that the key is loaded. Print only the last 4 characters, never the full key: console.log(process.env.AI_API_KEY?.slice(-4)) in Node.js or print(os.environ.get("AI_API_KEY", "")[-4:]) in Python. If you get an empty value or undefined, the problem is the variable, not the API.
  2. Check the base URL. It must be exactly the one your provider gives you, with no extra slashes and without repeating /v1. In n8n, check the node's credential and the base URL field.
  3. Make a minimal call outside your app. If this test works, the problem is in your code or your environment:
curl YOUR_BASE_URL/v1/chat/completions \
  -H "Authorization: Bearer YOUR_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "YOUR_MODEL", "messages": [{"role": "user", "content": "Hello"}]}'

If your base URL already ends in /v1, don't repeat it.

  1. Check the model you are requesting. If the key is limited to certain models, a request to a model outside that list can be rejected. Also check that the model name is spelled correctly.
  2. Check your balance and the request log. In Dongee AI Router, the request log shows the result of each call, so you can find the one that failed and see which key and model it used.
  3. Add retries with exponential backoff, only for rate-limit 429s and 5xx errors. If the response includes a Retry-After header, wait that long.

What does each error code mean?

CodeWhat it meansTypical causeHow to fix it
401Invalid authenticationKey badly copied, missing or revoked; wrong base URLCheck the environment variable, the header and the base URL
403Authenticated, but not allowedThe key has no access to that resource or modelCheck the key's permissions or restrictions
404Resource not foundBadly built path (duplicated /v1) or a model that doesn't existFix the base URL and the model name
429 (rate limit)Too many requestsBursts, loops or parallel processesRetry with exponential backoff and reduce concurrency
429 (quota)No balance or quotaCredit exhaustedTop up your balance; retrying won't help
500 / 503Server error or overloadTemporary failure of the service or the modelRetry with backoff; if it persists, try another model

What does a retry with exponential backoff look like in Node.js?

The official SDK already retries some errors on its own through the maxRetries option. If you want to control the logic yourself (and not retry when the balance is empty), you can use your own loop:

import OpenAI from "openai";

const client = new OpenAI({
  baseURL: process.env.AI_BASE_URL,
  apiKey: process.env.AI_API_KEY,
  maxRetries: 0
});

const esperar = (ms) => new Promise((r) => setTimeout(r, ms));

export async function preguntar(messages, intentos = 4) {
  for (let i = 0; i <= intentos; i++) {
    try {
      return await client.chat.completions.create({
        model: process.env.AI_MODEL,
        messages
      });
    } catch (err) {
      const s = err?.status;
      const sinSaldo = /quota|balance|credit|saldo/i.test(err?.message ?? "");
      const reintentable = (s === 429 && !sinSaldo) || s >= 500;
      if (!reintentable || i === intentos) throw err;
      const ra = Number(err.headers?.get?.("retry-after") ?? err.headers?.["retry-after"]);
      const base = ra > 0 ? ra * 1000 : 2 ** i * 1000;
      await esperar(base + Math.random() * 500);
    }
  }
}

If you haven't set up the client yet, this guide explains how to use the OpenAI SDK in Node.js with a compatible API.

How do I keep it from happening again with Dongee AI Router?

Dongee AI Router gives you one base URL and one key to use several models with the same SDK. It also includes tools that reduce these errors:

  • One key per app or per environment. You can create as many keys as you need. If you rotate the testing key, production keeps working, and if a 401 shows up you know which app to check.
  • Each key limited to its models. That way a bug in your code doesn't end up calling an expensive model. Here's how to limit an API key to certain AI models.
  • Usage in plain sight. The dashboard shows usage by model, by key and by request, so you can spot a loop before it drains your balance. More details in how to see token usage by key and model.
  • Prepaid balance from 3 USD, no monthly fee. If the balance runs out, requests stop and no debt is created. Read what happens when your AI API balance runs out to be prepared.
  • Streaming available, so your app can show the response as it arrives.

You program the routing: if you want to switch to another model when one fails, build that into your code. If you have questions, 24/7 human support in your language (the platform translates on the fly) can help you review it by chat or WhatsApp.

Frequently asked questions

Does a 429 mean I was blocked?

No. A 429 is almost always temporary: either you went over a rate limit and just need to wait, or your balance or quota ran out and you just need to top up. It is not a permanent block on your account.

Why do I get a 401 if the key works locally?

Most likely the environment variable isn't reaching the server. Your local .env file usually isn't uploaded with the deployment, so you need to define the key in the environment variables of your hosting or platform.

Does retrying a 401 help?

No. A 401 will keep repeating until you fix the key or the base URL. Only retry rate-limit 429s and 5xx errors.

How many retries should I set?

The usual practice is 3 to 5 retries with exponential backoff and a bit of randomness (jitter). More retries only make the user wait longer and add load.

Where can I see why a request failed in Dongee AI Router?

In the request log. Each call appears with its date, model, tokens, cost, duration and result, so you can find the request that failed and check its result.

In short: a 401 is almost always a key or base URL problem, and a 429 is about speed or balance. Check in that order, read the full error message and add retries only where they make sense.

Comenta lo que quieras

Unete a la charla
Solo ingresa tu email