Skip to content

Gemini API Errors: Diagnose 429, 400, 403, 404, and 5xx Failures

A 429 does not always mean “retry soon,” and a working API key does not prove your project can generate content. Use the error details to choose a fix, then configure retries that stop.

•••10 min read•Troubleshooting
Overview of Gemini API errors and troubleshooting paths

Start with the HTTP status, the error message, and the operation that failed. For a malformed request or denied project access, change the request or configuration before trying again. For a short-lived capacity failure, a small retry budget may help. For an exhausted daily quota, repeated requests just consume time until the quota resets or your approved limit changes.

This guide covers the Gemini Developer API used through Google AI Studio credentials, including generateContent. Gemini's consumer app, CLI, and Enterprise APIs have their own access and quota rules. Keep their troubleshooting instructions separate from the API request you are investigating.

Choose the next action from the error details

Diagram of diagnostic paths for Gemini API errors

The status code narrows the investigation; it does not establish the root cause. In particular, a 403 is not necessarily a bad key, and a 429 is not always a momentary traffic spike.

HTTP statusWhat to inspect firstWhat to do next
400The rejected field, model, API version, or unmet prerequisiteRepair the payload or stated prerequisite; do not resubmit it unchanged
401The authentication method and credential supplied to this endpointCorrect authentication before another request
402The message about Prepay credit availabilityResolve the billing state rather than retrying
403Key restrictions, project access, billing suspension, or resource permissionsIdentify which access check failed and correct that specific condition
404Exact model ID, API version, and resource nameConfirm that the resource exists and is available to this project
429The named limit and its time windowPace traffic for a short window; stop until reset or an approved increase for exhausted quota
500 or 503Whether the failure is intermittent or reproducibleTry bounded backoff; preserve a minimal reproduction if it persists
504The service deadline, client timeout, and request complexitySeparate a server error from a local timeout, then reduce work or adjust the appropriate timeout
501The unsupported operation or featureChange the operation; do not classify every 5xx as transient

The official API error reference documents endpoint-specific details. Its Interactions API examples use string identifiers such as rate_limit_exceeded and quota_exceeded; a generateContent SDK exception can expose an integer code and an uppercase status such as RESOURCE_EXHAUSTED. Do not make your parser depend on one JSON shape for every endpoint.

Before changing anything, keep a sanitized record of the failure: timestamp with timezone, endpoint and API version, model ID, SDK version, HTTP status, error identifier, and message. Keep any request ID or retry hint returned by the service. Remove credentials, authorization headers, private prompts, and access-bearing URLs before sharing the record.

429: identify the window before retrying

Open the active rate limits for the same project and model in Google AI Studio. Check the metric named by the error rather than relying on an overall usage chart. RPM, input TPM, and RPD measure different things; passing one limit does not mean the request passes all of them. Quotas apply to the project, so a second key in the same project adds no capacity. Google's rate-limit documentation explains these scopes.

Use the limiting metric to choose a practical change:

  • Requests per minute: place a queue ahead of the API calls and pace all workers sharing the project. A delay in one worker will not control traffic from the others.
  • Input tokens per minute: reduce repeated context or admit fewer large requests at once. Sending the same large prompt less often can be more useful than shaving a few milliseconds off each call.
  • Requests per day: stop the short retry loop. RPD resets at midnight Pacific time; use America/Los_Angeles when calculating the reset in another timezone so daylight saving is handled correctly.
  • Spend-based rate limit: where applicable, inspect the rolling 10-minute spend window. A low request count can still accompany expensive requests. This is distinct from a daily request allowance or an available credit balance.

The last two windows and the account-dependent spend rule are documented in rate limits. Use your active limits instead of copying a fixed free-tier table into application code.

Why a nearly empty dashboard can still accompany a 429

A low chart value is evidence about that chart, not proof of a quota bug. Check that the project, model, metric, and time window match the failed call. Include traffic from other workers and applications that share the project. Then inspect project availability and the active limit itself: low consumption cannot help when the project has no usable allowance for that operation.

If those checks do not explain the error, retain the response and report the mismatch. There is no verified universal “wait 15–30 minutes” fix. A useful report says which limit was named, what the corresponding dashboard showed, and when both observations were made.

When paying for more capacity helps

Consider an upgrade when an eligible project's measured workload consistently exceeds its active limits. Compare the requested capacity with your actual request and token patterns first. Billing will not repair an invalid payload, an unsupported model, or a suspended project. Published limits are not a capacity guarantee, and Google does not guarantee approval of a limit-increase request. See the official upgrade and increase guidance.

400 and 404: reduce the request to a supported operation

For a 400, start with the field named in the message. Check its type and allowed value against the documentation for the exact model and API version. For a 404, check the complete resource name and model ID before changing any generation settings.

A useful diagnostic sequence is to remove optional generation settings and tools, send a short text prompt to a model available to your project, then add the required features back one at a time. A successful minimal call tells you that the basic operation works; the first reintroduced feature that fails narrows the investigation. This is a separate API operation and can incur usage charges—listing models alone is not an equivalent test.

Do not treat temperature: 1.0 as a universal 400 repair. Parameter behavior varies by model generation. Google's model-parameter guidance currently says newer models may ignore sampling controls and warn, with rejection planned later; earlier Gemini 3 models should retain defaults. Removing an unnecessary setting is safer than copying a tuning recipe from another model.

For a model that used to work, consult both the current model catalog and deprecation guidance. An old example's default model is not a guaranteed migration destination. Confirm the replacement's supported operation and project access before adapting the request.

For uploaded-file requests, also inspect the referenced file. The Files API deletes uploaded files after 48 hours; use files.get to inspect the stored resource and upload it again when necessary. Keep the new URI with the corresponding job. Do not silently remove a required document just to make the request succeed. Files API documentation

403: check the project as well as the key

Check the key type and restrictions if an older integration stopped working. Google now rejects unrestricted standard keys, while restricted standard keys continue to work. Keep the appropriate Gemini API restriction instead of removing security restrictions as a generic fix. Current API key guidance

Read the specific denial message before rotating credentials. A leaked or blocked key needs a credential fix. A project denied access needs a project-level fix. Creating a fresh key in the same restricted project does not change that project's eligibility.

Check the project's status in AI Studio and follow the relevant recovery path for free-tier unavailability, payment needed, or suspension. A restricted free-tier project may require an active paid billing account; paid usage is billed and does not unlock a free-tier allowance. Google distinguishes these cases in its project access troubleshooting.

A successful models.list call is not proof that generation is authorized. Google explicitly notes that listing models does not check the project's billing or eligibility state. If listing succeeds but generation fails, retain the generation error and investigate that operation's access requirements. Project and billing suspension guidance

For a regional or prerequisite message, check the actual execution location against the available regions. Enabling billing is not a general workaround for an unsupported location. The language of your application or account does not establish where its requests execute.

500, 503, and 504: retry briefly, then narrow the failure

For an intermittent 500 or 503, a bounded retry with backoff gives a temporary failure a chance to clear. Check the Gemini status page for a matching incident, but do not assume that an empty incident list explains or disproves your individual failure.

When the same request repeatedly fails, compare it with a smaller request to the same model and endpoint. If only the larger request fails, reduce its context, attachments, or optional features in controlled steps. That result identifies a request-dependent trigger; it does not by itself prove that you crossed a documented context limit.

Distinguish an HTTP 504 returned by the service from an exception raised because your client stopped waiting. Increasing a client timeout can help when the client deadline is too short; it cannot extend every server-side deadline. Give long-running work a suitable application deadline and cancellation path. A client timeout also does not prove that the server did no work, so retrying may repeat generation.

Bounded retries with the current Python and Node.js SDKs

Illustration of retries spaced apart with increasing delays

Use google-genai for Python or @google/genai for JavaScript. The legacy libraries used in many older examples are no longer actively maintained; see Google's SDK migration guidance.

The examples below use the SDK's retry policy, without an additional retry loop. They allow three total attempts for HTTP 500, 503, and 504. A 429 deliberately stops for diagnosis because a status-only policy cannot tell a brief rate limit from exhausted daily quota. After your application classifies a 429 as temporary, you can handle that case in the queue with its own bounded policy.

A 30-second timeout and the delay values below are example settings, not a service guarantee or an end-to-end deadline. The SDK options use milliseconds for timeout and seconds for delay fields. attempts includes the original request. See the Python SDK reference and JavaScript retry options.

Python

Install google-genai, then set GEMINI_API_KEY and GEMINI_MODEL in your server environment. Both examples pass the key explicitly. If you instead rely on automatic SDK environment detection, GOOGLE_API_KEY takes precedence when both key variables are set, so confirm which project the SDK is actually using. Environment variable guidance Choose a model available to your project. Save this as diagnose.py and run python diagnose.py.

python
import os
from google import genai
from google.genai import errors, types

client = genai.Client(
    api_key=os.environ["GEMINI_API_KEY"],
    http_options=types.HttpOptions(
        timeout=30_000,
        retry_options=types.HttpRetryOptions(
            attempts=3,
            initial_delay=1.0,
            max_delay=8.0,
            exp_base=2.0,
            jitter=1.0,
            http_status_codes=[500, 503, 504],
        ),
    ),
)

try:
    response = client.models.generate_content(
        model=os.environ["GEMINI_MODEL"],
        contents="Reply with the word OK.",
    )
    if not response.text:
        raise RuntimeError("No text returned; inspect response metadata.")
    print(response.text)
except errors.APIError as exc:
    # Inspect the full error privately; do not publish raw request data.
    print(f"Gemini request failed: HTTP {exc.code}")
    raise SystemExit(1)
finally:
    client.close()

Node.js

Install @google/genai with npm and set the same two environment variables. Save this as diagnose.mjs and run node diagnose.mjs in the package directory.

javascript
import { GoogleGenAI } from "@google/genai";

if (!process.env.GEMINI_API_KEY || !process.env.GEMINI_MODEL) {
  throw new Error("Set GEMINI_API_KEY and GEMINI_MODEL first.");
}

const ai = new GoogleGenAI({
  apiKey: process.env.GEMINI_API_KEY,
  httpOptions: {
    timeout: 30_000,
    retryOptions: {
      attempts: 3,
      initialDelay: 1.0,
      maxDelay: 8.0,
      expBase: 2.0,
      jitter: 1.0,
      httpStatusCodes: [500, 503, 504],
    },
  },
});

try {
  const response = await ai.models.generateContent({
    model: process.env.GEMINI_MODEL,
    contents: "Reply with the word OK.",
  });
  if (!response.text) {
    throw new Error("No text returned; inspect response metadata.");
  }
  console.log(response.text);
} catch (error) {
  console.error("Gemini request failed:", error.status ?? error.name);
  process.exitCode = 1;
}

Both examples were checked locally with google-genai 2.33.0 and @google/genai 2.31.0 using fake credentials and intercepted HTTP responses. The checks covered successful text extraction, a transient failure followed by success, stopping after three failed attempts, and no automatic retry for 400, 403, 404, or 429. They did not call Google's API or verify live access, quota, or recovery times.

If a job runner also retries failed jobs, count those retries in the total budget. Three SDK attempts inside three job attempts can send nine requests. Stop or defer the job when the application deadline or quota condition requires it rather than letting independent retry layers multiply traffic.

What to collect when the error persists

Stop repeating an unchanged failing request once its retry budget is exhausted. Keep one minimal reproduction and a short comparison showing what succeeds and what fails. Include the SDK version, operation, model, timestamp, sanitized error, attempt count, and the relevant active quota or project status.

For application monitoring, record failures by status, model, and operation alongside latency and request volume. A spike confined to one deployment suggests a different investigation from failures across unchanged clients. Track retries separately so an apparent increase in traffic is not mistaken for increased user demand. Share the reproduction through the Google AI developer community or the support channel available to your account.

Common follow-up questions

Will a new API key fix a 429?

Not when the same project's quota is exhausted. Limits are project-scoped, not key-scoped. Change traffic or resolve the applicable quota condition; rotate a key when the key itself is compromised or blocked. Rate-limit scope

Are failed requests billed?

Google's billing FAQ says failed requests with a 400 or 500 response are not charged for tokens but still count toward quota. Do not extend that statement to every error, timeout, or repeated generation. A timeout is not evidence of a refund or of zero server-side work. Billing FAQ

Does an HTTP 200 mean the application received a usable answer?

No. Check the response content and relevant completion or blocking metadata before treating the task as complete. The examples reject an empty text result; an application using tools, images, or structured output should validate the corresponding expected output instead. The API error reference also covers generation and content-related failures.

Found an error, or hit a problem this article does not cover? Send the article URL and what you saw to hi@laozhang.ai. We check it and update the article.