Gemini API Error Troubleshooting: 429 RESOURCE_EXHAUSTED, 400/500
A Gemini 429 RESOURCE_EXHAUSTED can be a per-minute limit, a daily quota, a spend cap or no quota for the model. The error body says whether to retry or stop.
On this page

A Gemini API 429 RESOURCE_EXHAUSTED means your project ran into one of several limits, and only some of them clear if you wait a few seconds. A per-minute request or token limit resets within a minute. A daily quota resets at midnight Pacific time. A monthly spending cap on your project or billing account stays until you raise it or until the 1st of the next month, and limit: 0 means the project has no quota for that model at all. Since September 19, 2026, an empty Prepay balance returns HTTP 402 instead, although the body still says RESOURCE_EXHAUSTED.
So log the full error body, not just the status code, and decide from what it says. Check the HTTP code first, because 402 means you need to add Prepay credits. Then read the message: "monthly spending cap" means raising the cap on the AI Studio Spend page or waiting for the 1st. Then look at the quotaId in the QuotaFailure details, retry only PerMinute violations after the delay in RetryInfo, and stop on PerDay or limit: 0. If the body only says "Resource has been exhausted (e.g. check quota)", open the AI Studio Rate Limit page for that project before you retry. Don't count on the SDK to handle any of this: in a local test on October 30, 2026, the default generate_content call in google-genai 2.34.0 and generateContent in @google/genai 2.32.0 each sent one request and gave up.
Two lookalikes are not API quota errors. Numbered errors such as 1185 or 1555 come from the Gemini app, not the API, and are covered in Gemini Something Went Wrong Error Codes 13, 1076, 1099: 4 Checks. The message "Invalid StreamExperience Request … Text part must not be empty" comes from Android Studio's built-in Gemini agent, and updating Android Studio fixes it, as described further down.
429 RESOURCE_EXHAUSTED: which Gemini limit you hit and when it clears
RESOURCE_EXHAUSTED is a status, not a cause. The Gemini Developer API applies limits per project, not per API key, across requests per minute (RPM), input tokens per minute (TPM) and requests per day (RPD), and going over any one of them returns a 429, according to the Gemini API rate limits page (updated October 28, 2026). Billing adds monthly spend caps and a rolling 10-minute spend limit on top. The response tells you which one you hit through its message and, when present, the QuotaFailure and RetryInfo entries in error.details.
| What the response shows | What you hit | When it clears | Retry? |
|---|---|---|---|
quotaId containing PerMinute, such as GenerateRequestsPerMinutePerProjectPerModel-FreeTier, and "Please retry in 3.9s" | RPM or input TPM for that model | Within a minute; RetryInfo.retryDelay gives the wait | Yes, after the delay |
quotaId containing PerDay | RPD for that model | Midnight Pacific time | No, not until the reset |
limit: 0 in the message | No quota for this model on this project | Not by waiting | No; change the model, billing or project |
| "Your project has exceeded its monthly spending cap" | The project spend cap set in AI Studio | When you raise the cap, or on the 1st | No |
| "Your billing account has exceeded its monthly spending cap" | The billing-account tier cap: $250 on Tier 1, $2,000 on Tier 2, $20,000–$100,000+ on Tier 3 | On the 1st, after a tier upgrade, or after an approved increase | No |
HTTP 402, "Your prepayment credits are depleted", status still RESOURCE_EXHAUSTED | Prepay balance at $0 | When you add credits | No |
| Only "Resource has been exhausted (e.g. check quota)." with no details | Not identified: a 10-minute spend limit, a Search or Maps grounding limit, a tier drop, or a limit only AI Studio shows | Depends on the cause | A few backoff retries at most, then check AI Studio |
The quota IDs above come from real error logs posted on the Google AI Developers Forum, not from a published Google list, so match on the PerMinute or PerDay part rather than the full name. The "Please retry in" hint is not a promise either: a paid project's March 2026 log in that forum showed limit: 0 together with "Please retry in 3.914220433s", and waiting four seconds changes nothing there. Creating another API key in the same project adds no quota, because the limits count per project.
Google doesn't publish a per-model free-tier table anymore; the live numbers are on the AI Studio Rate Limit page. As one example, a free-tier project's AI Studio page in October 2026 showed 5 RPM, 250K TPM and 20 RPD for gemini-3.8-flash, according to a developer's screenshot on the Google AI Developers Forum, and your project may show different values. With 20 requests a day, a scheduled job that makes its 21st call gets a 429 that won't clear until midnight Pacific. Vertex AI uses its own quota system, so this table applies to Gemini API keys from Google AI Studio.
Spend caps, 402 and limit: 0 — the 429s that waiting won't fix
These responses look like rate limits but need a change in billing, the project or the model, so retrying them only burns time and log space.
Since Google's announcement on the Google AI Developers Forum on September 19, 2026, depleted prepayment credits return 402 Payment Required with the message "Your prepayment credits are depleted", but the body's status field is still RESOURCE_EXHAUSTED. Code that branches only on that status treats an empty balance as a rate limit and keeps retrying, so check the HTTP code first. When the Prepay balance on a billing account hits $0, every API key in every linked project stops until you buy credits (minimum purchase $5) or turn on auto-reload, and billing data lags by about 10 minutes, per the Gemini API billing documentation. Prepay, Postpay and credit questions are covered in Gemini API Billing Tiers: Prepay vs Postpay and No Credits Fixes.
When the billing-account tier cap is reached, Google pauses service for all projects linked to that billing account until the 1st of the month. You can ask for a higher cap through Google's quota and billing cap increase request form, or qualify for the next tier: Tier 2 needs $100 paid plus 3 days from the first successful payment. A Google staff member explained on October 24, 2026 that free credits don't count toward tier upgrades. So a Prepay account moves up with a cash prepayment, while a Postpay account paying with credits has to request an increase, which Google handles manually and which may take a few days. The project cap is a different message and a setting you control: raise it under Spend > Monthly spend cap > Edit spend cap in AI Studio, which needs the project editor, owner or admin role.
limit: 0 means the project has no quota for that model, so the fix is never time. On a free-tier project, the model may not be offered for free; pick a model that shows a limit on your Rate Limit page or link billing. If a paid project still reports free_tier metrics with limit: 0, follow Gemini API Paid Tier Getting free_tier_requests Limit 0: What to Fix. A restricted or suspended project can also return a 429 with a quota limit value of 0, as a Gemini CLI user with a pending appeal reported on October 16, 2026, and in that case the AI Studio Projects page or an email from Google tells you why.
A daily quota clears at midnight Pacific time or when your project moves to a paid tier. To see your live limits by tier and request higher ones, use Gemini API Rate Limits 2026: Free vs Paid Tiers and How to Raise. Image models count images per minute as well; for those, see Gemini Image 429 Rate Limit: How Long It Lasts and How to Fix It, and if a batch of images stopped halfway, Nano Banana Pro RESOURCE_EXHAUSTED: Fix 429 and Resume Image Jobs.
Resource has been exhausted (e.g. check quota): finding the cause
A 429 that carries only that sentence, with no QuotaFailure or RetryInfo, needs to be traced in AI Studio. On October 23, 2026, a Google staff member wrote in a Google AI Developers Forum thread about 429 errors that backend updates now make "all 429 errors come with a description field which properly explains the cause", and asked developers to scan their logs for it. The thread doesn't show where that field sits in the JSON, and clients that keep only the exception message lose it, so work through these checks in order:
- Log the raw response body and the UTC time of the failure. In Python,
e.detailsholds the parsed body; in JavaScript,@google/genaiputs the JSON insidee.message, so parse it from there. - Open the AI Studio Rate Limit page with the right project and time range selected, and compare peak RPM, TPM and RPD with the displayed limits. Scroll down to the Search grounding and Maps grounding limits, which Google staff asked 429 reporters to check; Grounding with Google Search on Gemini 3 and newer models has a default of 1,500 requests per day per project. One developer found the charts displayed in UTC-8, so convert your log time before comparing.
- Check the AI Studio Projects and Billing pages for banners about a tier drop, a restricted project or a payment, and look for an email from Google with an appeal link. A tier drop comes from an automated flag that support can't remove, and it lowers both your rate limits and your spend caps.
- On the Spend page, compare this month's spend with your project cap and the billing-account tier cap, and on Prepay, check the balance. Paid projects can also hit the rolling 10-minute spend limit of $10 on Tier 1, $50 on Tier 2 or $200 on Tier 3. Google says this returns 429 RESOURCE_EXHAUSTED and clears if you wait, and whether it applies depends on your billing history and account standing.
- If usage is below every limit, post on the Google AI Developers Forum with the unredacted description text, the exact UTC timestamp and a Rate Limit page screenshot for that window. Google staff asked for exactly these on October 27, 2026, and for the project ID by direct message rather than in public.
What the Gemini SDKs do on 429 by default: tested October 30, 2026
Google's Gemini API troubleshooting guide says the Python SDK "automatically retries transient errors up to four times" by default. A test on October 30, 2026 found that this holds only for some calls. It ran on macOS with google-genai 2.34.0 (Python 3.12.1) and @google/genai 2.32.0 (Node 24.11.0), the latest releases that day, against a local mock server that returned Gemini-shaped 429 and 402 bodies modeled on real error logs. The mock isn't Google's server, so the results show what the client libraries do with those responses, not what Google sends. "Retry options on" below means HttpRetryOptions() in Python and retryOptions: {} in JavaScript, with default settings.
| Case | Python google-genai 2.34.0 | JavaScript @google/genai 2.32.0 |
|---|---|---|
Default client, generate_content / generateContent, any 429 or 402 | 1 request, no retry | 1 request, no retry |
Retry options on, per-minute 429 with a 7 s RetryInfo | 5 requests in 17.1 s; gaps of 1.5, 2.2, 4.8 and 8.5 s | 5 requests in 27.5 s; gaps of 1.4, 4.0, 7.4 and 14.7 s |
| Retry options on, monthly spending cap 429 | 5 requests in 17.6 s | Not run |
| Retry options on, 402 Prepay depleted | 1 request | 1 request |
Default client, interactions.create, 429 quota_exceeded | 4 requests in 3.1 s, then RateLimitError | Not run |
| Where the quota details are | e.code, e.status, e.details["error"]["details"] | e.status; details only inside the JSON string in e.message |
The plain generate_content call has no retry at all, so a per-minute 429 that would clear in seven seconds fails your request outright. Turning on the SDK's retry options fixes that but brings two problems. The SDK never reads RetryInfo, so its first two retries went out before the 7 seconds the server asked for. It also decides by HTTP code alone (the Python SDK's default retry codes are 408, 429, 500, 502, 503 and 504), so it retried a monthly-cap 429 four times even though that cap only clears on the 1st. A 402 isn't on that list, which is one more reason the September change from 429 to 402 matters.
The Interactions API reports errors with snake_case codes instead: rate_limit_exceeded for a per-minute or per-second limit and too_many_requests for bursts, both meant for backoff, and quota_exceeded for a daily quota, which means waiting for the reset; a 402 there is payment_required, according to the Gemini API errors page (updated October 23, 2026). In the Python test, client.interactions.create retried a daily quota_exceeded three times by default and then raised google.genai._gaos.lib.compat_errors.RateLimitError. That class is not a subclass of errors.APIError, so an except errors.APIError block doesn't catch it.
Retry-or-stop code for Gemini 429 in Python and JavaScript

This diagram is from an earlier version of this guide; the text and code on this page reflect the rules as of October 30, 2026.
The functions below turn the table above into code, and on October 30, 2026 they ran against the same local mock. They check in this order: HTTP 402, then any code other than 429, then the project-cap message, then any other "spending cap" message, then "prepayment credits", then limit: 0, then a PerDay quota ID, and only then a PerMinute quota ID, which waits for the longer of RetryInfo and an exponential backoff, plus up to a second of jitter. Anything left over gets a bounded backoff of at most four attempts. The order matters: the project-cap check has to run before the broader "spending cap" match, and a limit: 0 response can carry PerMinute quota IDs and a retry delay, so it has to be caught first.
import random
import re
import time
from google import genai
from google.genai import errors
def classify(e: errors.APIError) -> dict:
"""Return {'kind', 'wait', 'retry'} for a Gemini API error."""
if e.code == 402:
return {"kind": "prepay_depleted", "wait": None, "retry": False}
if e.code != 429:
return {"kind": f"http_{e.code}", "wait": None, "retry": False}
err = (e.details or {}).get("error", {}) if isinstance(e.details, dict) else {}
msg = (err.get("message") or e.message or "").lower()
quota_ids, wait = [], None
for d in err.get("details", []):
t = d.get("@type", "")
if t.endswith("QuotaFailure"):
quota_ids += [v.get("quotaId", "") for v in d.get("violations", [])]
elif t.endswith("RetryInfo"):
wait = float(d.get("retryDelay", "0s").rstrip("s") or 0)
if "project has exceeded its monthly spending cap" in msg:
return {"kind": "project_spend_cap", "wait": None, "retry": False}
if "spending cap" in msg:
return {"kind": "billing_account_spend_cap", "wait": None, "retry": False}
if "prepayment credits" in msg:
return {"kind": "prepay_depleted", "wait": None, "retry": False}
if re.search(r"limit: 0\b", msg):
return {"kind": "no_quota_for_model", "wait": None, "retry": False, "quota_ids": quota_ids}
if any("PerDay" in q for q in quota_ids):
return {"kind": "daily_quota", "wait": None, "retry": False, "quota_ids": quota_ids}
if any("PerMinute" in q for q in quota_ids):
return {"kind": "per_minute", "wait": wait or 60.0, "retry": True, "quota_ids": quota_ids}
# No quota details: rolling spend limit, capacity, or a cause only AI Studio shows.
return {"kind": "unspecified_429", "wait": wait, "retry": True}
def generate_with_quota_handling(client, model, contents, max_attempts=4):
for attempt in range(1, max_attempts + 1):
try:
return client.models.generate_content(model=model, contents=contents)
except errors.APIError as e:
info = classify(e)
if not info["retry"] or attempt == max_attempts:
raise RuntimeError(f"{info['kind']}: {e.message}") from e
backoff = min(60.0, 2 ** attempt)
delay = max(info["wait"] or 0, backoff) + random.uniform(0, 1)
print(f"attempt {attempt}: {info['kind']}, sleeping {delay:.1f}s")
time.sleep(delay)
client = genai.Client() # reads GEMINI_API_KEY from the environment
response = generate_with_quota_handling(client, "gemini-3.8-flash", "Summarize this ticket in one line.")
print(response.text)import { GoogleGenAI, ApiError } from "@google/genai";
function classify(e) {
if (!(e instanceof ApiError)) return { kind: "not_api_error", retry: false };
if (e.status === 402) return { kind: "prepay_depleted", retry: false };
if (e.status !== 429) return { kind: `http_${e.status}`, retry: false };
// @google/genai keeps the error JSON inside e.message.
let err = {};
try { err = JSON.parse(e.message.slice(e.message.indexOf("{"))).error ?? {}; } catch {}
const msg = (err.message ?? e.message).toLowerCase();
const quotaIds = [];
let wait = null;
for (const d of err.details ?? []) {
if (d["@type"]?.endsWith("QuotaFailure")) quotaIds.push(...d.violations.map((v) => v.quotaId));
if (d["@type"]?.endsWith("RetryInfo")) wait = parseFloat(d.retryDelay);
}
if (msg.includes("project has exceeded its monthly spending cap")) return { kind: "project_spend_cap", retry: false };
if (msg.includes("spending cap")) return { kind: "billing_account_spend_cap", retry: false };
if (msg.includes("prepayment credits")) return { kind: "prepay_depleted", retry: false };
if (/limit: 0\b/.test(msg)) return { kind: "no_quota_for_model", retry: false, quotaIds };
if (quotaIds.some((q) => q.includes("PerDay"))) return { kind: "daily_quota", retry: false, quotaIds };
if (quotaIds.some((q) => q.includes("PerMinute"))) return { kind: "per_minute", retry: true, wait: wait ?? 60, quotaIds };
return { kind: "unspecified_429", retry: true, wait };
}
async function generateWithQuotaHandling(ai, model, contents, maxAttempts = 4) {
for (let attempt = 1; ; attempt++) {
try {
return await ai.models.generateContent({ model, contents });
} catch (e) {
const info = classify(e);
if (!info.retry || attempt >= maxAttempts) throw new Error(`${info.kind}: ${String(e.message).slice(0, 80)}`);
const delay = Math.max(info.wait ?? 0, Math.min(60, 2 ** attempt)) + Math.random();
console.log(`attempt ${attempt}: ${info.kind}, sleeping ${delay.toFixed(1)}s`);
await new Promise((r) => setTimeout(r, delay * 1000));
}
}
}
const ai = new GoogleGenAI({}); // reads GEMINI_API_KEY from the environment
const response = await generateWithQuotaHandling(ai, "gemini-3.8-flash", "Summarize this ticket in one line.");
console.log(response.text);In the mock test, two per-minute 429s followed by a success recovered in 8.2 seconds in Python and 7.9 seconds in JavaScript, three requests each. A per-minute limit that never cleared made the Python wrapper sleep 7.7, 7.1 and 8.9 seconds and give up after four requests. limit: 0, both spending-cap messages and the 402 each stopped after one request, and the bare "Resource has been exhausted" case made four requests over 15.1 seconds before raising unspecified_429.
Three limits come with this code. It matches the English message text seen in 2026 error reports, so log the kind next to the raw body and look at any unspecified_429 you collect, because Google may reword messages or add fields. It re-raises every code other than 429, including 500, 503 and 504, so add the handling described in the 5xx section below. If you also turn on the SDK's retry options, the SDK retries 429s, caps included, before this code ever sees them, and in Python it won't catch the Interactions API's RateLimitError.
Other Gemini API error codes: retry 5xx, fix 400, 403 and 404

This flowchart is from an earlier version of this guide; where it differs from the text, the text reflects the rules as of October 30, 2026.
Outside 429, the HTTP code alone mostly tells you whether to retry. A 4xx code means the request, the key or the project needs changing, so an identical retry fails the same way, while 500, 503 and 504 come from Google's side or a time limit and are worth retrying with backoff. Google's troubleshooting guide lists 429, 408 and 5xx as retryable and says not to retry 400, 402 or 403.
A 403 PERMISSION_DENIED points at the key or the project: a key reported as leaked, a project restricted from the free tier, a past-due billing account or a policy suspension. Retrying won't change it; Gemini API Key Permission Denied: Fix 403 by Error Source (2026) walks through each source. A 404 such as "models/gemini-1.5-flash is not found for API version v1beta" means the model ID is no longer served. Switch to a current ID such as gemini-3.8-flash, gemini-3.6-flash or gemini-4-argon from the Gemini models page; Google's troubleshooting guide now calls the Gemini 2.5 models deprecated.
Gemini API 400 INVALID_ARGUMENT: common causes in 2026
A 400 means Google rejected the request as written, so the same request will fail again until you change it. The status field says INVALID_ARGUMENT for a bad request body or parameter, or FAILED_PRECONDITION when a prerequisite such as billing isn't met, and the message usually names the field. These are the causes that show up most with current models:
temperature,top_p,top_kandcandidateCount. Gemini 4 and Gemini 3.6 and newer ignore customtemperature,top_pandtop_k, return deprecation warning headers, and "will return 400 errors in a future release", according to Google's troubleshooting guide, so remove them now. On earlier Gemini 3 models, keep them at their defaults.candidateCountis unsupported on Gemini 3 and 4.- A beta feature on
/v1. Features in beta are only available on/v1beta, so the same request fails on/v1. - "Request contains an invalid argument." When the message names no field, send a minimal request with only the model and one text part, then add your fields back one at a time until the 400 returns.
- "Requests ending with a model turn are not supported." The last turn in
contentsbelongs to the model; the fix is in 'Gemini "Requests ending with a model turn are not supported" Fix'. - "API key not valid. Please pass a valid API key." The string that reached Google isn't a valid Gemini API key. Check which environment variable your process actually loaded, and create a new key in Google AI Studio if the old one was deleted.
- "User location is not supported for the API use." The request comes from a location where Google doesn't offer the API to your project; the regions section of Gemini API Free Tier 2026: Limits, Free Models, and Free API Keys links to the list.
Android Studio "Invalid StreamExperience Request": update the IDE
"Please try again later. Error: Status INVALID_ARGUMENT Invalid StreamExperience Request. Violations: contents[7].parts[0].text: Text part must not be empty." comes from the Gemini agent built into Android Studio, not from your own Gemini API code. Android Studio builds that request from the agent's chat history, so changing your API key or your app's code won't fix it. Google lists the error as fixed (Gemini issue #549864592) in Android Studio Rabbit 1 2026.2.1 Canary 3 on the Android Studio fixed bugs page, last updated October 1, 2026.
Developers in a Google AI Developers Forum thread on Gemini in Android Studio fixed it by updating, and one reported that 2026.1.3 Patch 1 made agent chat work again. Install the latest Android Studio patch for your channel. The same developer later saw "content message must contain at least one part" when asking the agent for query changes, which that thread left unresolved, so that message may still appear after the update.
Gemini API 500, 503 and 504: retry, wait or shorten the request
These three come from Google's side or from the request's time limit, so retry them with exponential backoff, add jitter and cap the number of attempts. When many requests fail at once, check the Google AI Studio status page before you change any code.
500 INTERNAL is an unexpected server error. Retry it, and if the same input keeps failing, contact support, as the Gemini API errors page recommends. 503 UNAVAILABLE means the service is temporarily overloaded or down. Messages such as "no capacity available for model gemini-3.5-flash-lite on the server", or Android Studio's "Model query failed: RESOURCE_EXHAUSTED: We are currently experiencing high demand and are temporarily at capacity", say plainly that the model is at capacity, and the Android Studio one adds that the agent is already retrying. Gemini High Demand Error: What It Means and What to Do First covers what to do while it lasts, and for image models, Fix Gemini 3 Pro Image 503 Errors: Model Overloaded and Deadline Expired.
504 DEADLINE_EXCEEDED means the request didn't finish within the deadline. Google's errors page recommends removing or increasing your client deadline setting so the server default applies. Gemini 3.x models think by default, which adds latency and tokens, so if speed matters more than depth, lower the thinking level as the Gemini API troubleshooting guide suggests.
Gemini API 429 and quota errors: other questions
What does "HTTP response at 400 or 500 level … 429" mean?
The full message, "HTTP response at 400 or 500 level, error: , HTTP status code: 429", comes from a tool or plugin that wraps the Gemini API and passes on the status code without the body. The 429 is one of the Gemini limits in the table near the top of this page, and only the body says which one. Find the raw response in the tool's execution log, or send one request with the same key and model from your own code or curl and log the whole response, then match its message and quotaId against the table.
Why did my Gemini API calls suddenly start returning 429 when nothing changed?
The limits can change under unchanged code. Google cut free-tier rate limits in December 2025, and the live values for each project are now only on the AI Studio Rate Limit page. As of October 2026, Google staff also name tier drops from an automated account flag, which lower both rate limits and spend caps, and a billing-account cap reached mid-month, which pauses every linked project until the 1st. The rate limits page also says that "specified rate limits are not guaranteed and actual capacity may vary".
Is a Vertex AI 429 RESOURCE_EXHAUSTED the same error?
The status name is the same, but Vertex AI on Google Cloud has its own quota system, separate from the Gemini Developer API tiers, AI Studio Rate Limit page and spend caps described here. If your requests go to a Vertex AI endpoint with Google Cloud credentials rather than an AI Studio API key, check the quota documentation for Vertex AI instead.
Sources12
External pages this guide links to, in the order they appear. Last updated Oct 30, 2026.
Sources12
External pages this guide links to, in the order they appear. Last updated Oct 30, 2026.
- 1.Gemini API rate limits pageai.google.dev/gemini-api/docs/rate-limits
- 2.AI Studio Rate Limit pageaistudio.google.com/rate-limit
- 3.announcement on the Google AI Developers Forumdiscuss.ai.google.dev/t/api-update-depleted-prepay-credits-now-return-http-402-instead-of-429/183654
- 4.Gemini API billing documentationai.google.dev/gemini-api/docs/billing
- 5.quota and billing cap increase request formforms.gle/ETzX94k8jf7iSotH9
- 6.Google AI Developers Forum thread about 429 errorsdiscuss.ai.google.dev/t/189883
- 7.Gemini API troubleshooting guideai.google.dev/gemini-api/docs/troubleshooting
- 8.Gemini API errors pageai.google.dev/gemini-api/docs/api-errors
- 9.Gemini models pageai.google.dev/gemini-api/docs/models
- 10.Android Studio fixed bugs pagedeveloper.android.com/studio/releases/fixed-bugs/studio/2026.2.1
- 11.Google AI Developers Forum thread on Gemini in Android Studiodiscuss.ai.google.dev/t/gemini-on-android-studio/179147
- 12.Google AI Studio status pageaistudio.google.com/status





