Skip to main content
BuildOfficialCertifiedReviewed Nov 27, 2026

Api Gateway Backend Security and Rate Limiting

v1.0.2New

Install this skill

No account required. Pick your tool, then copy.

Run in your terminal. It detects your AI tool.

npx @skills-hub-ai/cli install google-cloud-skills-api-gateway-backend-security-and-rate-limiting

What this does: Secures and rate limits backend services behind Google Cloud API Gateway across OpenAPI 2.0 and OpenAPI 3.x API configurations, including MCP-enabled gateways. Use when configuring API key or JWT authentication, locking down Cloud Run or Cloud Run functions backends with a gateway service account, reading authenticated claims from X-Apigateway-Api-Userinfo, setting per-project request quotas, or changing quota metrics without the HTTP 500 "Failed to call Service Control Quota" error on older gateways. Do not use for finding the cause of failing requests from gateway logs, such as an unexplained HTTP 429 or 5xx (use api-gateway-troubleshooting), writing or migrating a whole spec (use api-gateway-openapi-spec-authoring), MCP tool setup (use api-gateway-mcp-server), Apigee, GKE Gateway API, Cloud Load Balancing custom domain setup, or LLM model routing.

Or get the file:
Browse all CLI commands →
Manual setup by platform

Claude Code

~/.claude/skills/google-cloud-skills-api-gateway-backend-security-and-rate-limiting/SKILL.md

Setup guide →

Signing

SignedSLSA L2
Signed by
skills-hub.ai distributor
Method
Distributor-signed by skills-hub.aiSigned with the skills-hub.ai Ed25519 distributor key over this exact slug, version and content. Check it with `npx @skills-hub-ai/cli verify`.
Key
skills-hub-ed25519-2026-11
Signed
0Save

Instructions

API Gateway Backend Security and Rate Limiting

This skill configures client authentication, gateway-to-backend authentication, and per-project rate limits (quotas) for Google Cloud API Gateway across OpenAPI 2.0 (swagger: "2.0") and OpenAPI 3.x (3.0.x and 3.1.x, such as openapi: 3.0.4), including gateways with Model Context Protocol (MCP) enabled (Public Preview).

Usage Attribution

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

Prerequisites

  1. Install the Google Cloud CLI and Python 3.10+ YAML parser:
    • If gcloud is not installed, give the user the Google Cloud CLI install guide. Do not install it yourself. Until it is installed, give the user the commands to run, and continue from the output that they paste.
    • If the gcloud CLI is old, ask the user before you run gcloud components update. An old gcloud CLI can fail when it uploads an OpenAPI 3.x spec.
    • Install PyYAML for the quota metric validation script. Ask the user before you install it:
      pip install "PyYAML>=6.0,<7.0"
      
  2. Authenticate your environment:
    • Local CLI session: gcloud auth login
    • Application Default Credentials (SDKs): gcloud auth application-default login
    • Service account key file (if required by CI): set GOOGLE_APPLICATION_CREDENTIALS={key_file_path}
  3. Select or create a project, verify billing, and pick a supported gateway location:
    • Ask the user which project to use, and use that ID as {project_id}. Pass --project={project_id} on every command. Do not run gcloud config set project, because it changes the default project for all other work of the user. If no project exists, create one with gcloud projects create {project_id} as an escape hatch.
    • Verify that an active billing account is linked to {project_id} (required even when staying within the API Gateway pricing free tier).
    • Use us-central1 as the default --location for API Gateway commands. For the other supported regions, see API Gateway deployment model.
  4. Enable required Google Cloud APIs:
    gcloud services enable \
      apigateway.googleapis.com \
      servicemanagement.googleapis.com \
      servicecontrol.googleapis.com \
      iam.googleapis.com \
      apikeys.googleapis.com \
      --project={project_id}
    
    API Gateway does not need the Cloud Run API. If the backend runs on Cloud Run, that API is already enabled in the backend's project.
  5. Verify required IAM roles:
    • To manage API Gateway resources and enable services: roles/apigateway.admin and roles/serviceusage.serviceUsageAdmin
    • To create the gateway service account and attach it to an API config: roles/iam.serviceAccountAdmin and roles/iam.serviceAccountUser
    • To manage API keys in consumer projects: roles/serviceusage.apiKeysAdmin
    • To change the IAM policy of the Cloud Run backend (grant the invoker role, remove allUsers, and turn on the invoker IAM check): roles/run.admin, or another role with run.services.get, run.services.getIamPolicy, run.services.setIamPolicy, and run.services.update. For a 1st gen function backend: roles/cloudfunctions.admin
    • For the gateway service account to invoke the backend: roles/run.invoker (Cloud Run or 2nd gen functions) or roles/cloudfunctions.invoker (1st gen functions)

Decision Matrix: Client Authentication, Backend Security, and Quotas

Select the layer that matches the security requirement:

GoalMechanism to ConfigureKey ConstraintDetailed Reference
Identify the calling consumer project for quotas and billingAPI key in the x-api-key header (use the key or api_key query parameter only as an escape hatch)NEVER rely on an API key alone to authenticate end-user identity. Rationale: API keys identify a Google Cloud project rather than a user, and clients can extract them. API Gateway ignores an API key scheme with any other name or location, with no error, and the operation then accepts calls with no key.Client Authentication
Authenticate end users or calling servicesJWT (oauth2 scheme with x-google-issuer / x-google-jwks_uri in OAS 2.0, or x-google-auth in OAS 3.x)Operation-level security overrides root security. Include api_key: [] and the JWT scheme in the same security requirement object when an endpoint needs both user identity and quotas.Client Authentication
Block direct calls to the backend serviceDedicated gateway service account (--backend-auth-service-account) + roles/run.invoker + remove public invoker bindings from the backend and turn on its invoker IAM checkEvery gateway of the API MUST serve a config with --backend-auth-service-account BEFORE you remove allUsers from a live backend. Otherwise those gateways get 403 errors.Backend Security
Rate limit requests per consumer project (1/min/{project})x-google-management (OAS 2.0) or x-google-api-management (OAS 3.x) + x-google-quotaRequire the API key in every security alternative of a quota operation. NEVER rename or remove a quota metric when creating a new API config while any gateway of the API runs an older config referencing that metric. Rationale: Creating the config immediately overwrites API-wide quotas and causes HTTP 500 Failed to call Service Control Quota on older gateways.Quotas and Rate Limiting
Secure MCP tools/list and tools/call on /mcp (Public Preview)x-google-api-management.mcp.tools-list.security (exactly one JWT or API key scheme) + operation security and x-google-mcp-tool: falsex-google-mcp-tool: false hides an operation from MCP only; the underlying REST route remains live unless secured or removed. An empty tools-list.security map leaves tools/list open.MCP Traffic Security

Execution Workflow and Validation Loop

Follow this zero-downtime sequence when authoring or updating an API Gateway security or quota configuration:

  1. Create the gateway service account and grant backend invoker permissions:
    • Follow Steps 1–3 of Backend Security to create {gateway_sa_name} and request human approval before granting roles/run.invoker on {backend_service}.
    • If operations authenticate a JWT, update backend handler code to decode verified user claims from X-Apigateway-Api-Userinfo (base64url-encoded JSON) instead of Authorization. API Gateway sends this header only for operations with JWT auth.
  2. Author the OpenAPI authentication and quota definitions:
    • To write a whole spec, or to migrate a spec from OpenAPI 2.0 to 3.x, use the api-gateway-openapi-spec-authoring skill. If it is not installed, continue with this skill.
    • Use the OpenAPI 2.0 or OpenAPI 3.x templates and provider tables in Client Authentication and Quotas and Rate Limiting.
    • If the specification enables MCP (x-google-api-management.mcp), configure exactly one JWT or API key scheme on tools-list (also list a JWT scheme in the root security list), and review operation opt-outs using MCP Traffic Security. To set up or name MCP tools, use the api-gateway-mcp-server skill. If it is not installed, see Configure Model Context Protocol.
  3. Run the quota metric validation loop BEFORE running api-configs create:
    • If neither the active specs nor {candidate_openapi_spec} define quota metrics (x-google-management.metrics or x-google-api-management.metrics), skip this step.
    • Request human approval before creating an API config that defines or modifies quotas, because api-configs create immediately replaces quota definitions across all gateways of the API.
    • By default, run scripts/check_quota_metrics.py against all active gateways deployed for {api_id} in {project_id}:
      python3 scripts/check_quota_metrics.py \
        --spec={candidate_openapi_spec} \
        --project={project_id} \
        --api={api_id}
      
    • Escape hatch for offline environments without gcloud access (pass --baseline-spec for every config currently served by a gateway of the API):
      python3 scripts/check_quota_metrics.py \
        --spec={candidate_openapi_spec} \
        --baseline-spec={previous_openapi_spec} \
        --dry-run
      
    • If scripts/check_quota_metrics.py exits with code 1 (status: "FAIL"), add the missing metrics and limits back to {candidate_openapi_spec}, move each x-google-quota listed in ignored_quota_extensions into the operations it applies to, and re-run the script until it exits with code 0 (status: "PASS"). If the user wants to remove a limit on purpose, confirm the removal with the user, because it removes that limit from every gateway of the API. If skipped_configs is not empty, tell the user that the script did not inspect those API configs (for example, gRPC configs), and check their quota metrics and limits manually. If it exits with code 2, fix the problem printed to stderr: the CLI arguments, gcloud authentication, or an API config that the script cannot inspect.
  4. Create the API config, update the gateway, enable the managed service, and lock down the backend:
    • Follow Steps 4–5 of Backend Security to run gcloud api-gateway api-configs create and gcloud api-gateway gateways update (request human approval before updating a production gateway), enable the API's managedService in consumer projects (Client Authentication), and then lock down {backend_service} (remove public invoker bindings and turn on the invoker IAM check).
    • If api-configs create fails with an OpenAPI error, use the api-gateway-openapi-spec-authoring skill. If it fails with another error, such as an IAM or service account error, use the api-gateway-troubleshooting skill. If the skill is not installed, read the error text, and compare the spec with the templates in the references or the IAM roles in Prerequisites.
    • Verify that direct calls to the backend URL (*.run.app, or *.cloudfunctions.net for a 1st gen function) return 403, unauthenticated calls to the gateway defaultHostname return 401, and authenticated calls return 200.
    • If you get another result, use the api-gateway-troubleshooting skill. If it is not installed, check which API config each gateway serves, and check the roles/run.invoker (or roles/cloudfunctions.invoker) binding of {gateway_sa_name} on {backend_service}.

Pre-Deployment Checklist

  • Dedicated {gateway_sa_name} is granted roles/run.invoker (or roles/cloudfunctions.invoker). Only after every gateway of the API serves a config with --backend-auth-service-account, public invoker bindings (allUsers, allAuthenticatedUsers) are removed and the invoker IAM check is on.
  • If operations authenticate a JWT, backend code decodes X-Apigateway-Api-Userinfo for user claims.
  • Security enforcement does not depend solely on a load balancer or Google Cloud Armor in front of the gateway, because the gateway's defaultHostname (*.gateway.dev) cannot be disabled.
  • Every quota-enforced operation requires an API key (api_key: []) in every security alternative, and the API's managedService is enabled and allowed on the API key in each consumer project.
  • python3 scripts/check_quota_metrics.py returns status: "PASS" (exit code 0) against active gateway configs or all baseline specs before api-configs create.
  • If MCP is enabled, x-google-api-management.mcp.tools-list.security names exactly one JWT or API key scheme (a JWT scheme is also in the root security list), and administrative endpoints are secured on REST in addition to x-google-mcp-tool: false.

Resource Cleanup

To avoid ongoing charges when tearing down a test or staging environment, request human approval and delete the gateway, all API configs, and the API in dependency order:

gcloud api-gateway gateways delete {gateway_id} --location={region} --project={project_id}
gcloud api-gateway api-configs delete {config_id} --api={api_id} --project={project_id}
gcloud api-gateway apis delete {api_id} --project={project_id}

Delete the service account only if no other API config or gateway uses it. List the service account of every remaining API config in the project, and ask the user if other workloads use the account:

gcloud api-gateway api-configs list --project={project_id} --format="value(name,gatewayServiceAccount)"

If no remaining API config uses the account and the user confirms that no other workload uses it, delete it:

gcloud iam service-accounts delete {gateway_sa_name}@{project_id}.iam.gserviceaccount.com --project={project_id}

Related skills

NeedSkill
Write or migrate an OpenAPI spec, or fix an OpenAPI error from api-configs createapi-gateway-openapi-spec-authoring
Expose operations as MCP tools, or fix /mcp errorsapi-gateway-mcp-server
Find why requests fail, including HTTP 401, 403, 429, and quota HTTP 500 errorsapi-gateway-troubleshooting
Deploy or change the Cloud Run backendcloud-run-basics
Put a load balancer, Cloud Armor, or a custom domain in front of the gatewaygoogle-cloud-global-frontend-configuration

If an API Gateway skill in this table is not installed, give the user this command to install the four API Gateway skills. Until it is installed, use the fallback in this skill.

npx skills add google/skills --skill api-gateway-mcp-server --skill api-gateway-backend-security-and-rate-limiting --skill api-gateway-openapi-spec-authoring --skill api-gateway-troubleshooting

For another skill in this table, give the user the same command with --skill {skill_name}.

This skill doesn’t include stateful context yet, instructions only. Learn about stateful skills.

Security

Loading security scan...

Reviews (0)

Browse all →
gke-manifest-generationGenerates and updates secure, production-ready Kubernetes YAML manifests optimized for GKE Autopilot and GKE Standard clusters. Use when creating or modifying GKE deployment manifests, configuring container security contexts, setting CPU/memory resource limits, defining readiness/liveness/startup probes, mounting secrets and volumes, configuring GKE Gateway API routes, targeting Spot VMs, or deploying AI model inference workloads (vLLM, TGI, Gemma). Don't use for live cluster operations, pod troubleshooting (use gke-workload-troubleshooting), or cluster infrastructure provisioning (use gke-cluster-creation).2 installsfirebase-basicsProvides foundational Firebase CLI setup, CLI installation, version checks (`firebase-tools@latest --version`), CLI login (including --no-localhost), project creation, project selection (`firebase use`), and app config file downloads (`google-services.json`, `GoogleService-Info.plist`). Use ONLY for CLI login, project creation/switching, or downloading app config files. Don't use for Firebase Hosting deploy, Firestore, Auth, App Hosting, Data Connect, Crashlytics, or Remote Config.1 installsgoogle-cloud-waf-cost-optimizationEvaluates Google Cloud workloads for cost efficiency and FinOps alignment using the Google Cloud Well-Architected Framework Cost Optimization pillar. Use when the user asks to analyze Google Cloud spend, reduce cloud bills, rightsize resources (for example, Compute, GKE, Storage, Databases), evaluate discount options (for example, CUDs, SUDs, Spot VMs), or eliminate idle capacity. Do not use for standalone product pricing lookups or non-cost architecture design.1 installsgke-cost-analysisAnswer natural language questions and perform analysis on GKE cluster and workload costs using BigQuery billing exports, cost allocation data, and live cluster monitoring metrics. Use when querying GKE costs across projects, namespaces, or workloads, analyzing billing reports in BigQuery (`bq`), checking cluster cost budgets (`gcloud billing`), or diagnosing cost drivers like pod requests vs. actual utilization (`kubectl top`). Don't use for applying cost optimization changes, creating rightsizing manifests (VPA/MPA), or selecting ComputeClasses (use gke-cost-optimization instead).1 installsgoogle-cloud-solution-rag-enterprise-search-gke-sqldbDiscovers requirements, and generates architectural, design, and deployment guidance for a retrieval-augmented generation (RAG)-capable enterprise search system in Google Cloud. Use when users need a vector-enabled SQL database as the store and index for the embedding vectors, an open model and open-source inferencing framework, and Kubernetes containers to host all the application components. DON'T use this skill for fully-managed RAG, or SaaS search services, or when a non-SQL vector database is required.1 installsgoogle-analytics-admin-api-basicsManages Google Analytics account and property settings, enables the Analytics Admin API via the Cloud CLI, lists accounts and properties, and manages data streams, custom dimensions, conversion events, and integrations. Use when you need to programmatically configure Google Analytics accounts, provision properties, manage data retention, configure Measurement Protocol secrets, or manage Firebase and Google Ads links.1 installs

More from Google Cloud Skills

View source →
google-ads-api-mcp-setupGuides developers through downloading, configuring, and installing the official open-source Google Ads MCP Server. Use this skill when a user wants to connect their AI assistant (such as Gemini, Claude Code, or Cursor) to their Google Ads account to query campaigns or retrieve reporting metrics using natural language.4 installsspanner-basicsAssists in provisioning instances and databases, designing performant schemas, and querying data in Cloud Spanner on Google Cloud. Use when designing primary keys, writing SQL queries or client library code, or diagnosing performance issues.4 installsgke-workload-securityAudits, configures, and hardens workload-level security controls for Google Kubernetes Engine (GKE) applications and namespaces. Covers running security audits (`audit_cluster.sh`), enforcing Network Policies (default-deny and Dataplane V2 logging), isolating high-risk pods inside GKE Sandbox (`gVisor`), enforcing Pod Security Standards (`restricted` labeling) and pod securityContext, and mounting Secret Manager secrets via CSI (`SecretProviderClass`). Use when auditing workload security posture, isolating namespaces, applying pod security standards, or configuring network policies and secret volume mounts. Don't use for Workload Identity (use gke-workload-identity), cluster-wide control plane security, RBAC hardening, Binary Authorization, Shielded Nodes, or enabling platform-level GKE add-ons (use gke-platform-security instead).3 installsgke-upgradesPlans, executes, and validates Google Kubernetes Engine (GKE) cluster upgrades and maintenance operations for both Standard and Autopilot clusters. Produces upgrade plans, pre/post-upgrade checklists, maintenance runbooks with gcloud commands, release channel strategy, and troubleshooting guides. Handles node pool upgrade strategies (surge, blue-green), version compatibility, PDB management, and workload-specific concerns (stateful, GPU, operators). Use this skill whenever the user mentions GKE upgrades, Kubernetes version bumps, node pool maintenance, GKE patching, cluster version management, release channel selection, maintenance windows, surge upgrades, stuck upgrades, or any GKE lifecycle management task — even casual mentions like "we need to upgrade our clusters" or "plan our next GKE maintenance" or "our upgrade is stuck." Don't use for GKE cluster creation, application onboarding, general networking/routing setup, or security policy configurations (use gke-basics or relevant GK2 installsgoogle-cloud-recipe-networking-observabilityInvestigates Google Cloud networking issues by analyzing logs, metrics, and diagnostics. Use when investigating VPC Flow Logs, NAT, firewall, or threat logs, querying latency and throughput metrics, or running Connectivity Tests for path diagnostics.2 installsmigrate-to-rustClones, analyzes, plans, and migrates legacy codebases (C++, Fortran, Java, Python, C, Shell) from a GitHub URL or local directory to a modern, high-performance, deterministic, 100% Safe Rust architecture, tracking live telemetry across every task bucket, test failure/fix cycle, and Profile-Guided Optimization (PGO) stage, and producing a first-person AI storytelling report and interactive HTML infographic. Use when migrating a GitHub repository or local codebase to Rust, porting legacy C++, Fortran, Python, or Java workloads to memory-safe Rust, designing Struct-of-Arrays (SoA) or SIMD Rust architectures, or optimizing Rust ports with LLVM PGO. Don't use for unrelated non-Rust refactoring or single-line syntax questions.2 installs

More Build skills

Browse category →
senior-frontendBuild and review React, Next.js, TypeScript or Tailwind frontends: components, scaffolding, performance and bundle size. Use whenever the user wants a new component or app, a page feels slow, the bundle is too big, or asks for a frontend code review.652 installsui-design-systemUse when building a design system: tokens, component docs, responsive scales or developer handoff. Generates tokens with design_token_generator.py.553 installsfrontend-designGuidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults.364 installssenior-backendBuild and fix backend services: REST or GraphQL APIs, auth, microservices, PostgreSQL queries, migrations and load tests. Use whenever the user's API is slow or broken, needs login or auth added, a schema change, or a new endpoint or service scaffolded.265 installsself-improving-agentCurate what the agent has learned into durable project knowledge. Reviews Claude Code auto-memory (MEMORY.md and its topic files) for learnings worth keeping, promotes proven ones into CLAUDE.md or .claude/rules/, records a correction as a lesson that persists across sessions, prunes stale or duplicate entries, and turns a recurring fix into a reusable skill. Use whenever the user asks what you have learned or saved about the project, which memories should become permanent rules, to remember a lesson or stop repeating a mistake, or to clean up, audit or check memory health.185 installsusing-superpowersUse when starting any conversation - establishes how to find and use skills, requiring skill invocation before ANY response including clarifying questions149 installs

Frequently asked questions about api-gateway-backend-security-and-rate-limiting

What does the api-gateway-backend-security-and-rate-limiting skill do?

Secures and rate limits backend services behind Google Cloud API Gateway across OpenAPI 2.0 and OpenAPI 3.x API configurations, including MCP-enabled gateways. Use when configuring API key or JWT authentication, locking down Cloud Run or Cloud Run functions backends with a gateway service account, reading authenticated claims from X-Apigateway-Api-Userinfo, setting per-project request quotas, or changing quota metrics without the HTTP 500 "Failed to call Service Control Quota" error on older gateways. Do not use for finding the cause of failing requests from gateway logs, such as an unexplained HTTP 429 or 5xx (use api-gateway-troubleshooting), writing or migrating a whole spec (use api-gateway-openapi-spec-authoring), MCP tool setup (use api-gateway-mcp-server), Apigee, GKE Gateway API, Cloud Load Balancing custom domain setup, or LLM model routing. It's a reusable SKILL.md instruction set that loads into your AI coding assistant on demand, no prompt engineering, no copy-pasting every session.

How do I install the api-gateway-backend-security-and-rate-limiting skill?

Run `npx @skills-hub-ai/cli install google-cloud-skills-api-gateway-backend-security-and-rate-limiting` from your terminal. The CLI writes the SKILL.md to the correct location for your AI tool (e.g. ~/.claude/skills/google-cloud-skills-api-gateway-backend-security-and-rate-limiting/ for Claude Code or ~/.cursor/skills/ for Cursor with --target cursor) and adds it to your project's .skills.json lockfile.

Which AI tools does api-gateway-backend-security-and-rate-limiting work with?

api-gateway-backend-security-and-rate-limiting runs in Claude Code. It follows the open Agent Skills standard (SKILL.md), so the same skill works in every supported tool without modification.

Is the api-gateway-backend-security-and-rate-limiting skill free?

Yes. Every skill on skills-hub.ai is free and open-source. There are no premium tiers, paywalls, or usage limits. You only pay for whatever AI assistant you're already using.

How do I use api-gateway-backend-security-and-rate-limiting after installing it?

In Claude Code, type `/google-cloud-skills-api-gateway-backend-security-and-rate-limiting` (or whatever slash command the skill registers) and the AI follows the skill's instructions immediately. You can also reference it by name in natural language, your AI loads the skill into context when relevant.

Can I share the api-gateway-backend-security-and-rate-limiting skill with my team?

Yes. Commit your project's .skills.json lockfile and teammates run `npx @skills-hub-ai/cli install` (no args) to install every skill at the exact version you pinned. Organization-scoped installs work via skills-hub.ai organizations.