Generated banner for API Gateway Troubleshooting
Generated logo for API Gateway Troubleshooting

API Gateway Troubleshooting

GoogleOfficialPublished by Google

  • Skill
  • Tool integration
  • Cloud and DevOps
  • Apache-2.0
  • Low risk
  • Has scripts

From the author

Diagnoses failing requests and deployment errors on Google Cloud API Gateway. Use when calls through a gateway return 4xx or 5xx errors, including 429 and other quota errors, time out, or fail a CORS preflight; when `api-configs create` fails with a service account, concurrency, or limit error, or `gateways create` or `gateways update` fails; when a custom domain, load balancer, or TLS finding involves a gateway; or when the user asks if Google is at fault. Don't use for Apigee, Cloud Endpoints, or GKE Gateway API. For OpenAPI errors from `api-configs create`, use api-gateway-openapi-spec-authoring; for setting up or changing API keys, JWTs, or quotas, use api-gateway-backend-security-and-rate-limiting; for MCP `/mcp` errors, use api-gateway-mcp-server.
— the description by Google

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a structured, evidence-based workflow for troubleshooting Google Cloud API Gateway. It helps identify the root cause of 4xx and 5xx errors, deployment failures, and configuration issues by analyzing logs, checking project configurations, and validating OpenAPI specifications. The skill emphasizes safe, read-only diagnostic practices and requires explicit user approval before applying any changes to the infrastructure.

What it does

  • Identifies the specific hop (gateway or backend) where a request is failing.
  • Analyzes gateway logs to pinpoint authentication, quota, or routing errors.
  • Validates OpenAPI specifications using an offline linter to prevent deployment errors.
  • Provides step-by-step guidance for resolving IAM, service account, and configuration issues.
  • Offers a clear escalation path for issues originating within the Google Cloud platform.
  • Enforces safe operational habits by requiring approval for all configuration changes.

When to use it

  • When API Gateway returns 4xx or 5xx errors, including 429 quota errors or CORS failures.
  • When deployment commands like api-configs create or gateways update fail.
  • When investigating issues with custom domains, load balancers, or TLS configurations.
  • When you need to verify if a failure is caused by the gateway, the backend, or the caller's credentials.

Advantages

  • Reduces downtime by systematically isolating the source of API failures.
  • Prevents accidental configuration changes through a strict approval-based workflow.
  • Ensures security by mandating the redaction of sensitive credentials from logs and output.
  • Provides consistent, documented troubleshooting steps aligned with official Google Cloud practices.

Usage examples

“My API Gateway is returning 500 errors for all requests. Can you help?”
The agent will collect the project ID and gateway details, then use the provided log query to identify if the error is a gateway-side issue or a backend failure.
“I am getting a 403 error when calling my API through the gateway.”
The agent will determine if the 403 is coming from the gateway (auth/API key) or the backend (IAM/invoker role) and guide you through the appropriate fix.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/google/api-gateway-troubleshooting/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip api-gateway-troubleshooting.zip -d .agents/skills

Documentation by Google

API Gateway Troubleshooting

Use this skill to find out why requests to a deployed Google Cloud API Gateway fail and how to fix them. Work only from three sources of evidence:

  1. Public Google Cloud documentation, linked from this skill.

  2. The user's own project, read with the user's own credentials.

  3. Files and output that the user provides, such as an OpenAPI document, an error response, or a pasted log entry.

Scope

This skill covers only Google Cloud API Gateway. If the question is about Apigee, Cloud Endpoints, or GKE Gateway API, reply that this skill covers only Google Cloud API Gateway, and don't run its steps or commands.

Usage Attribution

MUST READ: Before executing any gcloud, REST API, or MCP command, you MUST read and follow the instructions in Usage Attribution.

Ground rules

RuleWhy
Stay read-only until the user approves a change. While you diagnose, run only list, describe, get-iam-policy, and logging read commands, plus nslookup and curl GET requests to a path that's safe to call.Gateways serve production traffic, and the quota metrics and limits of the most recently created API config apply to every gateway of the API.
Before any change, show the exact command, what it changes, and how to undo it, then wait for an explicit yes. Changes include IAM grants, api-configs create, gateways update, Cloud Run ingress changes, and gcloud services enable.The user owns the project and the change.
Never fix a 401 or 403 by making a backend public (--allow-unauthenticated, --no-invoker-iam-check, allUsers) or by granting a basic role such as Editor.Grant the gateway's service account the invoker role on the one backend instead, which keeps least privilege.
Keep every log read bounded: filter on the gateway, set --freshness or a timestamp window, and set --limit.Unbounded reads are slow and pull in caller data that the diagnosis doesn't need.
Redact API keys, bearer tokens, and JWTs before you show log entries, commands, or files.Request logs and pasted output can contain credentials.
Base every limit, default, and error meaning on a linked public doc or on output from the user's project. If neither explains the problem, say so and escalate.Guessing about undocumented behavior leads to wrong fixes.
Use the user's existing gcloud login. Never ask for passwords, API key values, or service account key files.Credentials don't belong in a chat transcript.
For Preview features (streaming, MCP, model routing), check the release notes before answering.Preview behavior changes between releases.

Prerequisites

  1. Google Cloud CLI. Use a recent gcloud (the commands here were checked with version 591.0.0); see Install the gcloud CLI. Don't install or update software without the user's approval. If gcloud isn't available or the user says not to run commands, work in evidence mode: give the user the read-only commands to run, and diagnose from the output, response bodies, and log entries they paste.

  2. Authentication. Use the user's existing gcloud auth login session; this skill doesn't need application-default credentials.

  3. Project. Ask which project hosts the gateway and pass --project={project_id} on every command. Don't run gcloud config set, because it changes the user's environment. This skill troubleshoots existing gateways and never creates projects.

  4. Billing. The project needs an active billing account even when usage stays in the free tier; see API Gateway pricing.

  5. APIs. API Gateway requires apigateway.googleapis.com, servicemanagement.googleapis.com, and servicecontrol.googleapis.com. A gateway can keep responding while one of them is missing, and its logs then stay empty, so check with gcloud services list --enabled --project={project_id}. Enabling a missing API is a change that needs approval.

  6. IAM roles for diagnosis (read-only): roles/apigateway.viewer, roles/logging.viewer, roles/serviceusage.serviceUsageViewer, and roles/iam.serviceAccountViewer (to check the gateway's service account). For Cloud Run backends, add roles/run.viewer; to trace a custom domain through its load balancer, add roles/compute.viewer; to check an API key's project, roles/serviceusage.serviceUsageViewer is also needed there.

  7. IAM roles for fixes (only after approval): roles/apigateway.admin; roles/iam.serviceAccountUser on the gateway's service account, because creating or updating an API config or a gateway requires iam.serviceAccounts.actAs; roles/run.admin to change a Cloud Run service's IAM policy or ingress; roles/serviceusage.serviceUsageAdmin to enable an API or a managed service, plus roles/servicemanagement.serviceConsumer on the API's managed service to enable it in another project; and roles/iam.serviceAccountAdmin to re-enable a disabled service account.

  8. Region. Gateways are regional. Use the region that gateways list reports. When a fix needs a new gateway, create it in the original gateway's region, or in us-central1 if the user has no preference; see API Gateway deployment model and Cloud locations.

Workflow

Copy this checklist into your notes and tick it off as you go:

- [ ] 1. Context collected
- [ ] 2. Gateway identified by defaultHostname
- [ ] 3. Expected or transient states ruled out
- [ ] 4. Gateway log entry read (bounded query)
- [ ] 5. One branch chosen from the classification table
- [ ] 6. Root cause stated with redacted evidence and a doc link
- [ ] 7. Fix proposed, approved, and applied (or handed to the user)
- [ ] 8. Fix verified
- [ ] 9. Escalated, if the evidence points to Google Cloud
1. Collect context

Extract these from the conversation first, and ask only for what's missing:

NeededWhy
{project_id} of the gatewayEvery command is scoped to it.
Failing URL (host and path) or {gateway_id} and {region}Identifies the gateway.
HTTP method, status code, and response bodySeparates gateway errors from backend errors.
Approximate time of the failure, in UTCBounds the log query.
What changed recently (new API config, IAM, backend deploy, DNS)Recent changes are the first place to look.
Authentication used by the caller (API key, JWT, none)Selects the auth branch.

If the project or the host is unknown, stop and ask before you run any gcloud command. Don't guess project IDs, and don't use the active gcloud project instead.

2. Identify the gateway

List the project's gateways:

gcloud api-gateway gateways list --project={project_id} \
  --format="table(name.basename():label=GATEWAY,name.segment(3):label=REGION,defaultHostname,state,apiConfig)"

Match the request host against defaultHostname. Don't decide from the URL suffix: a gateway's hostname can use either of two gateway.dev formats or, for older streaming and model-routing gateways, a run.app format. Don't guess the owning project from numbers in the hostname either; list the gateways in the project the user names. A custom domain points at a load balancer whose serverless NEG targets the gateway. See references/triage-and-logs.md for the hostname formats and how to trace a custom domain.

If no gateway in the project matches, confirm the product before going on (see Scope).

Then read the gateway's details, including its API config and streaming mode:

gcloud api-gateway gateways describe {gateway_id} \
  --location={region} --project={project_id}
3. Rule out expected and transient states
  • Gateway state isn't ACTIVE: CREATING or UPDATING means an operation is still running, so wait and check again. FAILED means creation failed; read the error of the failed operation. DELETING means the gateway is being removed.

  • API config just created: creating a complex API config can take up to ten minutes, and only one config can be created for an API at a time.

  • First requests after an idle period: API Gateway has cold-start latency.

  • Google Cloud incident: check the Service Health dashboard.

4. Read the gateway log entry

Use a bounded query that prints only the fields you need. Replace {status_code} with the status the caller saw:

gcloud logging read 'resource.type="apigateway.googleapis.com/Gateway" AND resource.labels.gateway_id="{gateway_id}" AND resource.labels.location="{region}" AND httpRequest.status={status_code}' \
  --project={project_id} --freshness=1h --limit=20 \
  --format="json(timestamp,httpRequest.status,httpRequest.latency,httpRequest.requestUrl,jsonPayload.responseDetails,jsonPayload.apiConfig,jsonPayload.apiMethod)"

If you know the failure time, replace --freshness with a timestamp>="{start_utc}" AND timestamp<="{end_utc}" filter that spans about 30 minutes around it. Read httpRequest.status, httpRequest.requestUrl, jsonPayload.responseDetails, jsonPayload.apiConfig, and jsonPayload.apiMethod. Keep the --format field list, because a full entry can contain the caller's credentials, and redact credentials before you quote any field, including a key query parameter in httpRequest.requestUrl.

To compare API configs, compare only the apis/{api_id}/configs/{config_id} part: the same config can appear as a full resource name (//apigateway.googleapis.com/projects/...) and with either the project number or the project ID.

jsonPayload.responseDetails decides the branch: via_upstream means the backend produced the response; any other value means the gateway produced it. The troubleshooting page explains via_upstream and service_control_quota_error, and the model routing page explains the model_router_* values that model-routing gateways log. Quote any other value as-is, and don't explain how the gateway works internally.

5. Classify and follow one branch

Pick the first row that matches, and load only the reference file it names.

What you seeLikely causeReference
401 or 403 with via_upstreamThe backend rejected the gateway: invoker role, audience, or deleted service accountauth-errors.md
A 4xx produced by the gateway whose body names a credential problem (for example UNAUTHENTICATED)The API key or JWT was rejected; quote the bodyauth-errors.md
500 with no gateway log entry, after log exclusions and a wrong scope are ruled outThe gateway's service account may be deleted or disabledauth-errors.md
500 with service_control_quota_errorQuota metric missing from the newest API configconfig-deployment-errors.md
429 with service_control_quota_errorThe caller exceeded the API's quotalimits-and-escalation.md
404, 502, 503, or 504, an oversized request, or a timeoutRouting, backend errors, size limits, or the deadline. The docs don't name the status codes for size or deadline failures, so confirm with responseDetails and the body.backend-routing-and-timeouts.md
CORS preflight fails or latency is highCORS pass-through or slow backendbackend-routing-and-timeouts.md
api-configs create fails with an error about the OpenAPI document, such as an unsupported extension or an invalid path, parameter, server, or security requirementA spec problemHand off to api-gateway-openapi-spec-authoring; if it isn't installed, see OpenAPI pre-flight check
api-configs create fails with a service account, concurrency, or limit error, or gateways create or gateways update failsService account, concurrent creates, limits, or the backend deadlineconfig-deployment-errors.md
400 "The request was malformed" from an old TLS client, TLS scan findings, custom domain, or no log entry at allTLS enforcement, DNS, load balancer, or wrong hostnetworking-domains-tls.md
Errors on several gateways, or on an unchanged config, with healthy backendsPossible Google Cloud issuelimits-and-escalation.md

If the request also needs log queries or backend inspection commands, use triage-and-logs.md.

6. State the root cause

Give the cause, the evidence (redacted, quoted verbatim from logs or command output), and the public doc section that explains it. If the evidence fits more than one cause, list at most three, say what would tell them apart, and collect that evidence before proposing a fix.

7. Propose the fix

Show the exact command, the resource it changes, its effect on live traffic, and how to undo it. Wait for approval, then run it, or hand it to the user if they prefer. Keep these rules in mind:

  • To change the OpenAPI document, create a new API config and deploy it with gcloud api-gateway gateways update. Before you create the config, check quota metrics with the api-gateway-backend-security-and-rate-limiting skill, because the newest API config's quota metrics apply to every gateway of the API.

  • Before you create a new API config, check the OpenAPI document with the linter (see OpenAPI pre-flight check).

8. Verify

Read the logs again for new entries after the change, or repeat the failing request. Repeat a request yourself only if it's safe to repeat, such as a GET; otherwise ask the user to repeat it, because a repeated POST can change data in their backend. After gateways update, wait until the gateway's state is ACTIVE before you test.

9. Escalate when the evidence points to Google Cloud

Escalate to Cloud Customer Care when the service account is active, the required APIs are enabled, and no log exclusion or wrong scope explains it, but requests get 500 errors with no gateway log entry; when several gateways fail at once without a config change; when errors are intermittent on an unchanged config while the backend logs stay clean; when control-plane operations keep failing with internal errors; or when Service Health reports an incident. Draft the case text with the evidence bundle in limits-and-escalation.md. The user files the case.

OpenAPI pre-flight check

Run the linter on every OpenAPI file before creating an API config. Run it; don't read its source. If you don't have the file, give the user the command to run:

python3 scripts/lint_openapi_for_gateway.py {spec_path} [{spec_path} ...]

It reads the files only, makes no network calls, and prints JSON findings that each link to the public doc for the limitation. Exit code 0 means no errors, 1 means at least one ERROR finding, and 2 means a usage, parse, or dependency error. The linter needs Python 3.8 or later. YAML input needs PyYAML; ask the user before you install it with pip install "PyYAML>=6.0,<7.0". JSON input doesn't. Fix the ERROR findings, and then create the API config. If api-configs create still fails on the OpenAPI document, hand off to api-gateway-openapi-spec-authoring, or use the error message if that skill isn't installed. Show WARNING findings to the user and explain them.

Output format

Report findings in this form:

**Problem:** <one sentence in the user's terms>
**Failed hop:** <gateway or backend, and the evidence for it>
**Evidence:** <redacted log fields or command output, verbatim>
**Root cause:** <one or two sentences> (<public doc link>)
**Fix:** <exact command or spec change; approval needed: yes/no>
**Verify:** <how to confirm the fix>
**Open questions:** <anything you couldn't confirm>
NeedSkill
Write or change API key, JWT, backend authentication, or quota configurationapi-gateway-backend-security-and-rate-limiting
Write, migrate, or fix an OpenAPI spec, including OpenAPI errors from api-configs createapi-gateway-openapi-spec-authoring
MCP /mcp JSON-RPC errors on an MCP-enabled gatewayapi-gateway-mcp-server
Deep IAM analysis, such as deny policies or role discoveryiam-helper-for-troubleshooting
Build a load balancer, Cloud Armor policy, or custom domain front endgoogle-cloud-global-frontend-configuration
Deploy or reconfigure a Cloud Run backendcloud-run-basics

Reference files

Files

references/backend-routing-and-timeouts.md

Routing, size limits, backend errors, timeouts, and CORS

  • 404 Not Found: Lines 10-47

  • Request and header size limits: Lines 49-59

  • 502 and 503: Lines 61-70

  • 504 and slow responses: Lines 72-105

  • CORS: Lines 107-119

  • Streaming and gRPC notes: Lines 121-129

404 Not Found

Read responseDetails first (see triage-and-logs.md).

via_upstream, and no matching entry in the Cloud Run request log. The Cloud Run service's ingress setting is probably blocking the gateway, or the service's default run.app URL is disabled while the gateway's address still uses it. With ingress set to Internal, only the sources listed on the ingress page can reach the service, and requests from other sources can't reach it at the run.app URL, a custom URL, or a custom domain (Cloud Run ingress). Cloud Run documents that requests blocked by these ingress settings, or sent to a disabled run.app URL, get 404 and don't appear in its request log (Cloud Run troubleshooting). Read the run.googleapis.com/ingress annotation to confirm. Fix, after approval: gcloud run services update {service} --ingress=all --region={backend_region} --project={backend_project}, and keep the service private through IAM: grant roles/run.invoker to the gateway's service account only (see auth-errors.md).

via_upstream, and the backend logged the 404. The backend received a path it doesn't serve. Check path translation in x-google-backend (OpenAPI 2.0 extensions):

Where x-google-backend is setDefault path_translationEffect
Top level of the specAPPEND_PATH_TO_ADDRESSThe request path is appended to address.
On an operationCONSTANT_ADDRESSThe request goes to address as-is, and path parameters are sent as query parameters.

Produced by the gateway. By default, API Gateway serves only the methods listed in the OpenAPI document (x-google-allow: configured in OpenAPI 2.0), so the request's path or method is probably missing from the API config that the gateway serves. Print the deployed OpenAPI document (see triage-and-logs.md) and compare its paths, methods, and base path with the request. Confirm the gateway serves the config you expect by comparing the config ID in jsonPayload.apiConfig with the gateway's apiConfig.

Request and header size limits

API Gateway allows requests up to 32 megabytes, responses up to 32 megabytes (streamed and chunked responses are exempt), and 60 kilobytes of request headers. gRPC transcoding requests and responses are limited to 1 megabyte each. The backend may have lower limits (Quotas and limits). The docs list these limits but not the status codes returned when a limit is exceeded, so confirm from the response body and responseDetails. Compare the request's body and header sizes with the limits, then suggest smaller payloads, fewer or smaller headers, or streaming for large responses.

502 and 503

  • via_upstream: the backend returned the error. Troubleshoot the backend directly, starting with its own request logs; this skill's scope ends once the backend is identified.

  • Produced by the gateway: the gateway, not the backend, generated the error. Check that address uses https for serverless backends, that the backend host resolves, and that the backend is healthy in its own logs and metrics. If all three hold and the errors continue, escalate (see limits-and-escalation.md).

504 and slow responses

  • Deadline. The default backend deadline is 15.0 seconds. It can be raised up to 3600 seconds, but a non-streaming gateway rejects values above 600 seconds when the gateway is created or updated, not when the API config is created (OpenAPI 2.0 extensions). Check effectiveStreamingMode before you propose a value above 600. The docs don't name the status code returned when the deadline expires, and a 504 with via_upstream can come from the backend's own request timeout instead.

  • Default fix. On a non-streaming gateway, set deadline to at most 600 seconds in a new API config and deploy it with gateways update. Requests that need longer require a new streaming-enabled gateway, which gets a new hostname that callers must switch to (see Streaming and gRPC notes). Give the commands for the existing gateway even when you also propose a new gateway.

  • Trade-off. The docs warn that long deadlines can overload the proxy with TCP connections when the backend is slow, and short deadlines can make expensive requests fail consistently. Propose the smallest deadline that covers the backend's normal response time.

  • Backend timeout. The backend's own request timeout also limits the response. For example, the streaming guide notes that a Cloud Run service deployed with --timeout 600 ends its streams after 10 minutes, so a 3,600-second deadline also needs --timeout 3600 on the service.

  • Streaming endpoints. On an SSE or chunked-transfer path, the deadline bounds the whole response, so a stream is cut when it elapses. On a gRPC or WebSocket endpoint, it bounds the gap between messages (OpenAPI 2.0 extensions, Configure streaming).

  • Cold starts. After 15 to 20 minutes without traffic, the first requests can see added latency. If latency persists after warm-up, check the backend's request logs (Troubleshooting overview).

CORS

To let the backend handle CORS, including OPTIONS preflight requests, turn on CORS pass-through, then make sure the backend answers preflight requests with the right Access-Control-* headers:

OpenAPI versionSetting
2.0Top-level x-google-endpoints with allowCors: True (extensions)
3.xallowCors: true in the x-google-endpoint extension on the server (extensions)

After the change, create a new API config and deploy it, then repeat the browser request and inspect the preflight response.

Streaming and gRPC notes

  • You can't update a gateway to change its streaming mode; create a new gateway, which gets a new hostname (Deploy an API to a gateway).

  • Gateways with streaming enabled can't sit behind a load balancer or serverless NEG, so they can't use custom domains during Public Preview (Configure streaming).

  • Terraform can't enable streaming yet.

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs an API key, Needs a command-line tool, Needs Python

Security

What our scanner noticed· Low risk

  • Instructions that use the network
  • Scripts that your agent may run

This skill includes scripts that your agent may run. Read them before you use it.

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Published by
Google
Publisher
Google (Official)
Source
google/skills · skills/cloud/api-gateway-troubleshooting · commit 2194d3b
Licence
Apache License 2.0 (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Google.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download api-gateway-troubleshooting.zip