API Gateway in Google Cloud

API Gateway in Google Cloud

A complete, beginner-friendly guide to the front door of your applications: how API Gateway receives requests, checks who is calling, protects your backends, limits abuse, and gives you one clean, secure address for many serverless services.

Think about a big hotel. Guests do not walk straight into the kitchen to order food, into the laundry to drop off clothes, or into the manager’s office to ask about a late checkout. Instead, they go to one front desk. The receptionist checks their room key, understands what they need, sends the request to the right department, and sends the answer back. If someone is rude or tries to enter a staff-only area, the receptionist stops them. The departments behind the desk stay calm and focused on their real work.

Modern software works the same way. A company may have dozens of small programs, each doing one job: one handles orders, one handles payments, one handles user profiles. Mobile apps, websites, and partners need to talk to them, but you do not want to hand every outsider the direct address of every program. You want one front desk. In Google Cloud, one of the services that plays this role is called API Gateway.

This guide explains API Gateway from zero. You do not need to be an expert in networks or security. Every new word is explained the first time it appears, with a simple comparison from everyday life. By the end you will understand what an API is, why a gateway helps, how requests travel through it, how it checks identity and limits traffic, how to publish and update your APIs safely, how to compare it with related services, and how to avoid common mistakes.

1What Is API Gateway?

API Gateway is a managed Google Cloud service that sits in front of your backend services, gives them a single public address, and applies rules about who may call them and how often.

Let us start with the word API. It stands for Application Programming Interface. In simple terms, an API is a menu of requests that one program can make to another. A weather service might offer an API where you ask, “What is the temperature in Delhi?” and it answers with a number. Most web APIs use the same language as web pages, called HTTP, and often exchange information in a tidy text format called JSON. Each kind of request has an address, called an endpoint, such as “/orders” or “/users/42”.

A gateway is a doorway. An API gateway is a doorway that all API requests must pass through before reaching the programs behind it. Those programs are called the backends, which means the services that do the real work. Google Cloud API Gateway is designed to front backends that run on serverless Google Cloud services, such as Cloud Functions, Cloud Run, and App Engine. Serverless means you do not manage servers yourself. You provide code, and Google runs it and scales it for you.

You describe your API in a document written in a standard format called OpenAPI. You give that document to API Gateway, create a gateway, and the service gives you a public web address. Clients call that address. The gateway checks their identity, applies limits, forwards the call to the correct backend, and returns the reply.

Analogy

It is the hotel front desk described earlier. The guest (client) talks only to the receptionist (gateway). The receptionist checks the room key (authentication), knows which department handles which request (routing), refuses guests who ask too often (rate limits), and writes everything in a log book (monitoring). The kitchen, laundry, and office (backends) never face the street.

What it does for you

One address

Single entry point

Many backends appear behind one tidy web address, so clients never learn your internal layout.

Identity

Checks who is calling

Validates API keys and signed tokens before any request reaches your code.

Protection

Limits traffic

Applies quotas so a single customer or a bug cannot flood your backends.

Routing

Sends calls to the right place

Maps each path and method to the correct function or service.

Visibility

Logs and metrics

Records requests, errors, and delays so you can see what is happening.

Managed

No proxy servers to run

Google operates and scales the gateway, so there is nothing to patch or restart.

i
Tip

Google Cloud has several services that touch APIs, and their roles overlap. API Gateway is the lightweight, serverless-focused option. Larger organizations with complex needs often look at a fuller platform, and a later chapter compares them. Product names, features, and status change over time, so confirm current details in Google’s documentation before you commit to a design.

One door
Many backends behind a single public address
Checked
Keys and tokens verified before backends run
Managed
No gateway servers for you to operate

2The Problem It Solves and a Short History

Gateways exist because exposing many small services directly to the internet quickly becomes messy and risky.

In the old days, a company often built one large program, called a monolith, that did everything. It had one address, and security rules lived inside it. Over time, teams split large programs into many small services, called microservices, so they could be built and updated independently. This was great for speed, but it created a new puzzle: how do outsiders reach all those services?

One option is to let every service face the internet by itself. Then every team must build its own login checks, its own traffic limits, its own logging, and its own security fixes. Mistakes multiply. A forgotten check in one small service becomes a hole in the whole company. Clients also need to know a dozen addresses, and any change in the layout breaks them.

The API gateway pattern solves this by putting one shared layer in front. Common rules are written once and applied to every request. Services behind it can be simpler, because they can assume that the gateway already handled the basics. The pattern became very popular, and many products appeared, from open-source proxies to large commercial platforms.

Google Cloud offered several answers over time. An earlier product, Cloud Endpoints, used a proxy that you ran yourself next to your service. A fuller, enterprise-grade platform, Apigee, covers the entire life of APIs, including developer portals and analytics. API Gateway arrived as a simpler, fully managed option for serverless backends, built on the same proxy technology as Endpoints but without the need to run the proxy. How these products are positioned can evolve, so check the current documentation and product pages when choosing.

Analogy

Imagine a shopping centre where every shop opens its own street entrance, hires its own guard, and keeps its own visitor book. Some guards are excellent. Others fall asleep. A mall with one main entrance, a trained team, and a single visitor book is easier to secure and easier for shoppers to understand.

The pains it removes

1

Repeated security code

Login checks and key validation are done once in the gateway, not rewritten in every service.

2

Exposed internals

Clients see only the gateway’s address, not the number or layout of your backends.

3

Traffic floods

Quotas stop one noisy caller from overwhelming your functions and your bill.

4

Scattered logs

Every request passes one place, which makes monitoring and investigation far simpler.

5

Breaking changes

You can change what is behind the door without changing the address clients use.

i
Good to know

A gateway is not magic security. It is one layer. A backend that trusts everything that reaches it, or a gateway configured carelessly, can still be attacked. Good design uses several layers, and this guide shows how they fit together.

3Core Concepts: API, Config, Gateway, and Backend

Three main objects and a few helper ideas explain almost everything you will see in the console.

API

In Google Cloud API Gateway, an API is a named container. It represents one logical API, such as “orders-api”. By itself it holds no rules. It is a folder in which versions of your API definition are stored.

API config

An API config is a saved snapshot of your API’s rules. It is created from your OpenAPI document and describes the paths, methods, security checks, quotas, and which backend to call for each path. Once created, an API config does not change. If you want to change a rule, you create a new API config. This makes rollbacks safe: the old snapshot still exists.

Gateway

A gateway is the running doorway. It is created in a specific region, and it is attached to exactly one API config at a time. The gateway receives a public web address. When you want to publish a change, you update the gateway to use a newer API config. To roll back, you point it at an older one.

Backend

A backend is the service that does the real work, such as a Cloud Function, a Cloud Run service, or an App Engine app. Your API config tells the gateway the address of each backend.

OpenAPI document

The OpenAPI document is a structured text file in a widely used standard. It lists your paths and operations, the shape of requests and responses, the security methods, and Google-specific extensions that tell the gateway where to send calls. The gateway’s current support is for a particular version of the standard, so check the documentation for the exact version it accepts.

Supporting ideas

  • API key: a long random string that identifies a calling project or application.
  • JWT: a signed digital token, short for JSON Web Token, that proves who the caller is and carries facts about them.
  • Service account: an identity for a program, not a person. The gateway uses one to call your backends.
  • Quota: a limit on how many calls may be made within a period.
  • Managed service: the behind-the-scenes object that Google creates from an API config to enforce checks and collect data.
ObjectWhat it isCan it change?Everyday comparison
APIA named container for one logical APIIts description can be editedA folder labelled “Orders”
API configA snapshot of rules created from the OpenAPI documentNo; create a new one insteadA printed edition of the rule book
GatewayThe live doorway with a public addressYes; switch it to another configThe front desk using a given edition of the rule book
BackendThe service that does the workYes, independentlyThe kitchen or laundry
Analogy

Think of a hotel again. The API is the binder titled “Guest Service Rules”. Each API config is a dated printed edition of the rules inside it. The gateway is the front desk, which follows one edition at a time. When management issues a new edition, the desk switches over. The old edition stays on the shelf in case of a mistake.

4The Gateway Pattern and Where It Fits

Before diving into details, it helps to see the overall picture: who talks to the gateway, what it talks to, and what it replaces.

The overall picture

Clients, such as mobile apps, websites, partner systems, and other services, send requests over the internet. All of them are directed to the gateway’s address. The gateway checks and forwards each request to the correct backend, then returns the response. The backends in turn may talk to databases, queues, and other services, which are not visible to the outside world.

flowchart LR
  Mob["Mobile app"] --> GW["API Gateway: one public address"]
  Web["Website"] --> GW
  Par["Partner system"] --> GW
  GW -->|"/orders"| CF["Cloud Function: orders"]
  GW -->|"/payments"| CR["Cloud Run: payments"]
  GW -->|"/profile"| AE["App Engine: profiles"]
  CF --> DB[("Database")]
  CR --> DB
  AE --> DB
    
Figure 1: Many kinds of clients enter through one gateway, which routes each path to the right backend.

What a gateway is not

A gateway is easy to confuse with other tools. A load balancer spreads traffic across copies of the same service. A gateway chooses between different services and applies rules about callers. A reverse proxy forwards requests on behalf of servers, and a gateway is a special kind of reverse proxy with API-aware rules. A firewall blocks network traffic by addresses and ports, while a gateway understands the meaning of API requests. A service mesh manages traffic between internal services, and a gateway manages traffic between the outside world and those services.

ToolMain jobUnderstands API keys and tokens?
API gatewayFront door for APIs with identity checks, quotas, and routing by pathYes
Load balancerSpread traffic across identical copies and route by host or pathGenerally no, unless combined with other features
Reverse proxyForward client requests to servers and hide themDepends on how it is configured
FirewallAllow or block traffic by address and portNo
Service meshManage service-to-service traffic inside a companyUsually uses internal identities
Analogy

In an airport, the firewall is the perimeter fence, the load balancer is the person directing cars to open parking lots, and the API gateway is the check-in desk that reads your ticket and decides which gate you may use. They work together. None of them replaces the others.

i
Tip

It is common to combine a gateway with other layers. For example, a load balancer with web application protection can sit in front of the gateway to add extra filtering, and a custom domain name can be attached through it. We cover this in the chapter on networking.

5Architecture and Core Components

API Gateway is made of a control side, where you manage your APIs, and a data side, where real requests flow. Seeing the split makes the product much easier to understand.

Google does not publish every internal detail of how its managed services are built, which is normal. What we can describe with confidence is the conceptual architecture, based on how Google describes the product: a control plane for your configuration, and a data plane that handles live traffic using a proxy built on well-known open-source technology. Treat this chapter as a mental model, not a blueprint of Google’s internals.

The control plane

The control plane is where you create APIs, upload configs, and create gateways. It stores your configuration and tells the data plane what to enforce. You reach it through the Google Cloud console, the command line, or the programming interface. Behind the scenes, it relies on service management features that turn your OpenAPI document into rules, and on identity and access management to decide who may change them.

The data plane

The data plane is the running gateway. Google describes it as being based on a proxy called Envoy, adapted into a component known as the Extensible Service Proxy. For every request, the proxy consults the rules, asks a checking service whether the caller and the request are allowed, applies quotas, forwards the call to the backend, and later reports what happened for logging and metrics.

Supporting services

1

Service management

Turns each API config into a managed service definition that the data plane can enforce.

2

Service control

Checks API keys and quotas for each request and records usage for reports.

3

Identity and access management

Controls who may administer the API and which identity the gateway uses to call backends.

4

Logging, monitoring, and tracing

Collect request logs, metrics such as latency and error counts, and traces of slow calls.

5

The backends

Cloud Functions, Cloud Run, or App Engine, which receive forwarded requests.

flowchart TD
  Adm["Administrator: console, CLI, or API"] --> CP["Control Plane: APIs, configs, gateways"]
  CP --> SM["Service Management: builds managed service from config"]
  SM --> DP["Data Plane: gateway proxy in chosen region"]
  Cl["Client request"] --> DP
  DP --> SC["Service Control: check key, quota, and report usage"]
  DP --> JW["Token validation using provider public keys"]
  DP --> BE["Backend: Function, Cloud Run, or App Engine"]
  BE --> DP
  DP --> Cl
  DP --> OBS["Cloud Logging, Monitoring, and Trace"]
  IAM["IAM and service account"] --> CP
  IAM --> BE
    
Figure 2: A conceptual view of the control plane that manages configuration and the data plane that handles live requests.
Analogy

A theatre has a box office and a stage. The box office (control plane) sells tickets and decides which show runs when. The stage (data plane) is where the performance happens every night in front of the audience. If the box office is closed for a day, tonight’s show can still run. Likewise, the gateway can keep serving requests while administrators edit configs, because the data plane works with the configuration it already has.

Regions

A gateway is created in a particular geographic region, and the set of supported regions is limited and may grow. Choose a region near your users and your backends to reduce delay, and confirm the current list in the documentation.

6How a Request Travels Through the Gateway

Every request follows the same short journey. Knowing the order of checks explains almost every error message you will meet.

Step by step

1

The client sends a request

An app calls the gateway’s public address, with a path such as “/orders/42” and a method such as GET.

2

The gateway matches the route

It compares the path and method with those listed in the API config. If nothing matches, it answers with a “not found” or “method not allowed” style error.

3

Authentication

If the operation requires an API key, the gateway checks it. If it requires a token, the gateway verifies the signature, issuer, audience, and expiry. Failed checks return an “unauthorized” style response and the backend is never called.

4

Quota check

The gateway asks whether the caller has used up their allowance. If so, it answers “too many requests”.

5

Forwarding

The gateway builds a request to the backend, adds its own identity token so the backend knows the call came from the gateway, and applies any path rewriting.

6

The backend responds

The backend does the real work and replies. If it is too slow, the gateway cuts off the call after a configured time.

7

Response and recording

The gateway returns the reply to the client and records the details for logs and metrics.

sequenceDiagram
  participant C as Client
  participant G as API Gateway
  participant S as Service Control
  participant B as Backend
  participant L as Logs and Metrics
  C->>G: GET /orders/42 with API key or token
  G->>G: Match path and method to config
  G->>G: Validate token signature, issuer, audience, expiry
  G->>S: Check API key and quota
  S-->>G: Allowed
  G->>B: Forward request with gateway identity token
  B-->>G: Response with order data
  G->>S: Report usage
  G->>L: Write log entry and metrics
  G-->>C: Response
    
Figure 3: The order of checks for one request. If any check fails, the later steps never happen.

Why the order matters

The gateway rejects bad requests as early as possible. This is both a safety feature and a cost saver. A request without a valid key never wakes up a function and never costs backend time. Attackers who flood the gateway with junk are stopped at the door, not inside the building. This is also why backend logs may look quiet while the gateway logs show many rejected calls: the rejection happened before the backend was involved.

Analogy

At an office reception, the guard checks your name against the visitor list, then your photo ID, then whether you have already used your visit allowance this month. Only then do they ring the person you came to see. People who fail at the first check never disturb anyone upstairs.

i
Good to know

Common status codes you will see: 401 means the caller could not be identified, 403 means the caller is known but not allowed, 404 means no matching route, 429 means a quota was exceeded, and 5xx codes mean something went wrong at the gateway or backend. Learning these quickly cuts troubleshooting time.

7Describing Your API with OpenAPI

The OpenAPI document is the single source of truth for your gateway. Understanding what goes in it, in plain words, is the most useful skill for working with the service.

OpenAPI is a widely used standard for describing web APIs in a text file. Because it is a standard, many other tools can read it: documentation generators, testing tools, and code generators. API Gateway reads your OpenAPI document to create its rules. This chapter describes the parts of the document in words, without code, so you can follow the idea. The exact version of the standard that the gateway accepts, and the exact names of Google-specific extensions, are listed in Google’s documentation.

The main sections

Info

About the API

A title, a version label, and a description, so that humans know what the API is.

Paths

Addresses and operations

Each path, such as orders, lists the methods allowed, such as GET to read and POST to create.

Parameters

Inputs

What each request may include: values in the path, query strings, headers, or a body.

Responses

Outputs

The status codes and shapes of replies, such as a success with order details or a not-found error.

Security

Who may call

Definitions of API key and token methods, and which operations require them.

Extensions

Google-specific hints

Fields that tell the gateway the backend address, timeouts, and quota settings.

The backend hint

The most important extension tells the gateway where to send calls. It can be set for the whole API or for individual operations. It names the backend address, which may be the web address of a function or a Cloud Run service. It also sets how the path is rewritten when forwarded, and the time limit for the backend to respond. Path handling has two common styles: either the gateway sends all calls to a fixed backend address, or it adds the incoming path to the backend address. Choosing the right style matters because the wrong one makes a perfectly healthy backend look broken.

Security definitions

Security definitions describe the methods that callers may use to prove themselves: an API key sent in a header or query string, or a signed token from a named issuer, with details of where to find the issuer’s public keys and which audience value to expect. Each operation can then state which definitions apply. An operation with no security requirement is open to everyone, so every open operation should be a deliberate decision.

Quota definitions

The document can define named metrics that count calls, and limits that say how many calls are allowed per time period, usually per project. Operations are then linked to a metric with a cost, so some operations can consume more of the allowance than others. This allows you to treat a heavy search call as more expensive than a simple lookup.

flowchart TD
  Doc["OpenAPI Document"] --> Info["Info: title and version"]
  Doc --> Paths["Paths and operations"]
  Doc --> Sec["Security definitions: keys and tokens"]
  Doc --> Ext["Google extensions"]
  Paths --> Op1["GET orders: requires key"]
  Paths --> Op2["POST orders: requires token"]
  Ext --> BE["Backend address, path style, timeout"]
  Ext --> Q["Quota metrics and limits"]
  Op1 --> BE
  Op2 --> BE
  Sec --> Op1
  Sec --> Op2
    
Figure 4: How the parts of an OpenAPI document connect to produce gateway behaviour.
Analogy

An OpenAPI document is like the menu and house rules of a restaurant printed together: the list of dishes (operations), what each dish needs (parameters), what you get (responses), who may order what (security), and notes for the kitchen about which station cooks each dish (backend hints). Customers, waiters, and the kitchen all work from the same sheet.

i
Tip

Keep the OpenAPI document in version control, next to your code, and review changes to it like any other code change. It is the contract between your API and its callers, and a careless edit can open a door or break an app.

8Backends: Functions, Cloud Run, and App Engine

The gateway is only as useful as what stands behind it. This chapter explains the backends it commonly fronts and how calls reach them.

Cloud Functions

Cloud Functions runs small pieces of code, called functions, in response to requests or events. You write a function that takes a request and returns a response, and Google handles the servers and scaling. It is ideal for small, focused operations such as “look up an order” or “send a confirmation”. Functions may need a moment to start if they have been idle, which is called a cold start. Cold starts can add delay to the first request after a quiet period.

Cloud Run

Cloud Run runs containers, which are neat packages that hold a program and everything it needs. You can use almost any language or framework, and Cloud Run scales the number of running copies up and down automatically, even down to zero when there is no traffic. It suits larger services and teams that already package their programs as containers.

App Engine

App Engine is an older platform for hosting web applications with automatic scaling. Many companies still run important applications there, and the gateway can sit in front of them.

BackendWhat you provideGood forWatch for
Cloud FunctionsSmall pieces of codeSimple, event-like operationsCold starts and per-function limits
Cloud RunA container imageFull services, any languageChoosing concurrency and minimum instances
App EngineAn application and its settingsExisting web applicationsPlatform-specific limits and settings

Mixing backends behind one gateway

One of the gateway’s real strengths is that one API can send different paths to different backend types. A company may keep a few legacy paths on App Engine, new features on Cloud Run, and tiny helper operations on Functions, and present them all to clients as one seamless API. This allows gradual modernization: you can move a path from one backend to another by changing the config, and clients never notice.

flowchart LR
  GW["API Gateway"] -->|"/legacy/reports"| AE["App Engine app"]
  GW -->|"/orders"| CR["Cloud Run service"]
  GW -->|"/notify"| CF["Cloud Function"]
  CR --> DB1[("Orders database")]
  CF --> Q["Message queue"]
  AE --> DB2[("Legacy database")]
    
Figure 5: Different backend types behind one gateway, hiding the mix from clients.

Timeouts and deadlines

Each backend call has a time limit. If the backend is slower than the limit, the gateway gives up and returns an error. You set the limit per operation. Pick a value that fits what the operation truly needs. A very short limit causes false failures on slow days. A very long one ties up resources and lets slow calls pile up. Also remember that the gateway has its own maximum limits, which may differ from those of the backend, so check the documentation for current values.

Backends that are not covered

The gateway is designed around Google Cloud serverless backends reachable through web addresses. Backends that live only inside a private network, on virtual machines with no public front, or in other clouds may not be reachable directly. Teams in that situation often put another layer in between, such as a load balancer or a proxy service, or choose a different gateway product. Check the current capabilities for your exact case.

Analogy

A hotel front desk can route a guest request to the kitchen, the laundry, or the concierge, even though each department works differently. The desk does not care how the kitchen cooks. It only needs to know where to send the request and how long to wait for an answer.

9Authentication: Proving Who Is Calling

Authentication means checking that callers are who they say they are. The gateway supports several methods, each suited to different callers.

API keys

An API key is a long secret string that identifies the calling project or application. The caller adds it to each request. The gateway checks that the key is valid and belongs to a project that has permission to use the API. Keys are simple and popular for public data and for tracking usage per partner. But a key is only a shared secret: anyone who steals it can pretend to be the owner. Keys also identify applications, not individual human users. Use them for identification and quota control, and do not treat them as strong proof of a person’s identity.

JSON Web Tokens

A JSON Web Token, or JWT, is a digitally signed message created by an identity provider after a user signs in. It contains facts such as who the user is, who issued the token, who it is intended for, and when it expires. The gateway can verify the token’s signature using the provider’s public keys, without calling the provider on every request. If the signature is valid and the facts match the expected values, the request proceeds. This method is stronger than an API key for identifying individual users, because tokens are short-lived and tied to a sign-in event.

The gateway can validate tokens from several kinds of providers, including Google sign-in, Firebase Authentication, and other providers that follow the same open standard, such as Auth0 or Okta. You configure the issuer name, the audience value your API expects, and where to find the public keys.

Service account tokens

When one program calls another, there is no human to sign in. Instead, the caller uses a service account, an identity for programs, and obtains a signed token for it. The gateway can be configured to accept tokens from specific service accounts, which makes it suitable for protecting internal or partner machine-to-machine calls.

MethodIdentifiesStrengthBest for
API keyAn application or projectBasic; a stolen key works until removedUsage tracking, quotas, low-risk public data
JWT from an identity providerAn individual signed-in userStrong, short-lived, verifiableMobile apps and websites with user sign-in
Service account tokenA program or serviceStrong, with managed credentialsMachine-to-machine and partner integrations

Combining methods

Many APIs use more than one method together. For instance, a key identifies the calling application for quota purposes, while a token identifies the user. An operation can require either of several methods or all of them, depending on how the document is written. Decide per operation what it truly needs.

flowchart TD
  R["Incoming request"] --> K{"Operation needs API key?"}
  K -->|"Yes"| KC["Validate key and project"]
  K -->|"No"| T
  KC -->|"Invalid"| X1["Reject: 401 or 403"]
  KC -->|"Valid"| T{"Operation needs token?"}
  T -->|"Yes"| TC["Validate signature, issuer, audience, expiry"]
  T -->|"No"| OK["Continue to quota check"]
  TC -->|"Invalid"| X2["Reject: 401"]
  TC -->|"Valid"| OK
    
Figure 6: How the gateway applies key and token checks in sequence.
Analogy

An API key is like a company’s membership card: it tells the receptionist which organization you come from. A signed token is like a passport stamped by a trusted authority, showing who you personally are and until when it is valid. A service account token is the pass issued to a delivery robot. Different visitors, different documents.

!
Never ship keys in public code

API keys placed inside mobile apps or website code can be extracted by anyone. If a key must live in a client, restrict what it can do, monitor its use, and be ready to rotate it. Never use a key alone to guard sensitive or personal data.

10Authorization and Protecting the Backends

Checking identity is only half the job. Systems must also decide what each identity may do, and make sure nobody can slip around the gateway to hit the backends directly.

Authentication versus authorization

Authentication asks, “Who are you?” Authorization asks, “Are you allowed to do this?” The gateway handles the first well and can handle some of the second, such as requiring a certain audience or scope. Fine-grained decisions, such as “this user may only see their own orders”, usually need the business knowledge that lives in the backend. A good design splits the work: the gateway rejects clearly invalid callers, and the backend enforces rules about the data itself.

The gateway’s own identity

When the gateway forwards a request, it acts as a particular service account, which you choose when you create the gateway. The gateway attaches a signed token for that account to the call. The backend can be set so that it accepts only calls carrying a valid token from this account. To make that work, you grant that service account permission to invoke the backend, using the invoker role of the relevant service.

Closing the side doors

A very common mistake is to leave the backend open to the world. Then an attacker simply ignores the gateway and calls the function or service directly, bypassing keys, tokens, and quotas. The correct design is to require authentication on every backend and allow only the gateway’s service account to invoke it. Some platforms also let you limit which network paths may reach a backend, and you should use those controls where they are available and appropriate.

flowchart TD
  Atk["Attacker"] -->|"Direct call to backend"| BE["Backend requires authenticated invoker"]
  BE -->|"No valid token"| Den["Rejected"]
  Cl["Legitimate client"] --> GW["API Gateway"]
  GW -->|"Call with gateway service account token"| BE
  BE -->|"Invoker permission granted to gateway account only"| OK["Request served"]
    
Figure 7: Requiring a valid gateway identity at the backend closes the side door.

Passing identity information along

Once the gateway has verified a user’s token, the backend often wants to know who the user was. The gateway can pass the verified information onward, typically in a header, so the backend can apply rules such as “this user may only view their own records”. Backends should rely on information the gateway has verified, and should never trust identity claims that come from the client without verification. Check the documentation for exactly how verified identity data is forwarded.

Least privilege everywhere

Gateway

Dedicated service account

Give the gateway its own account, not a shared or powerful one.

Invoker

Only invoke what is needed

Grant the invoker role only on the specific backends the API uses.

Admin

Limit who edits configs

Changing a config can open or close doors. Keep that permission with a small group.

Backend

Authorize inside too

Check ownership and roles for each record inside the service, not only at the gateway.

Analogy

If the hotel kitchen has a back door onto the street that is never locked, the front desk’s careful checks are pointless. A thief walks around the building and in through the back. Lock the kitchen so that only staff with the right badge may enter, and the front desk becomes the only door that matters.

11Quotas, Rate Limiting, and Abuse Protection

Even honest callers can send too much traffic by accident, and dishonest ones do it on purpose. Limits protect your backends and your budget.

Why limits matter

Serverless backends scale up automatically when traffic grows. That is wonderful for real customers but dangerous against abuse, because the service will happily scale up, and charge you, to answer a flood of junk requests. A quota is a limit on how many calls may be made in a period, such as a minute. When the limit is reached, further calls receive an error until the period resets. Quotas turn a potentially unlimited bill into a bounded one.

How quotas work in the gateway

In your API definition, you declare named metrics that count requests, and limits that set the allowed amount per time period, typically counted per project, which in practice means per API key owner. Operations are linked to metrics, and each call consumes a chosen cost. The gateway asks the checking service on every request whether quota remains and returns a “too many requests” response when it does not. Details such as available time windows and how precisely counts are enforced are in the documentation. In particular, counting across a distributed system is approximate, so treat limits as strong guard rails, not as exact accounting.

Different limits for different callers

Because quotas are tied to the calling project, you can offer different tiers. A free partner may be allowed a small number of calls per minute, while a paying partner gets more. To do this in practice, you give each partner a separate project and key and adjust their quota. How flexible the per-consumer controls are depends on the product, which is one reason larger programmes look at fuller API platforms.

Other protections

  • Request size limits: the gateway and backends enforce maximum body sizes. Keep your limits as small as your use case allows.
  • Timeouts: stop slow calls from tying up capacity.
  • Backend scaling caps: set a maximum number of instances on the backend as a final safety net against runaway cost.
  • Web application firewall: for protection against common web attacks and large floods, many companies place a load balancer with a protection service in front of the gateway. Check current documentation for supported combinations.
  • Budgets and alerts: set billing alerts so unexpected growth is noticed quickly.
flowchart LR
  Fl["Traffic flood or heavy partner"] --> WAF["Optional: load balancer with web protection"]
  WAF --> GW["API Gateway"]
  GW --> Q{"Quota remaining?"}
  Q -->|"Yes"| BE["Backend with max instance cap"]
  Q -->|"No"| R429["Return 429 Too Many Requests"]
  BE --> Bill["Bounded cost"]
    
Figure 8: Layers of protection that keep floods away from backends and bills.
Analogy

A water company installs a meter and a flow limiter on each connection. A leaking pipe in one house does not drain the whole town’s supply. Quotas are the flow limiters for your API: a misbehaving app is slowed down, and everyone else keeps their water.

i
Tip

Start with generous but finite limits, watch real usage for a few weeks, then tighten. Limits that are too strict cause support calls, and limits that are too loose do not protect you. Measure first, then tune.

12Config Versions, Deployment, and Rollback

Changing a live API without breaking its callers is an art. The separation of API configs and gateways is the tool that makes it safe.

How a change reaches production

1

Edit the OpenAPI document

Make the change in version control and have it reviewed by a teammate.

2

Create a new API config

Upload the document. This creates a new, immutable snapshot. Nothing live changes yet.

3

Test it on a staging gateway

Point a test gateway at the new config and run your checks.

4

Update the production gateway

Switch the live gateway to the new config. The service applies the update without you running servers, though it may take a short time to take effect.

5

Watch the results

Check error rates and latency closely for a while.

6

Roll back if needed

If something is wrong, point the gateway back to the previous config, which still exists.

flowchart LR
  Git["OpenAPI file in Git"] --> C1["API Config v1"]
  Git --> C2["API Config v2"]
  C1 --> GS["Staging Gateway"]
  C2 --> GS
  C1 --> GP["Production Gateway"]
  C2 -.->|"promote after tests"| GP
  GP -.->|"rollback"| C1
    
Figure 9: Immutable configs let one gateway switch forward and back between versions safely.

Versioning your public API

There is a difference between the config version (your internal snapshot) and the API version that callers see, such as “v1” or “v2” in the address. Callers depend on the shape of requests and replies. If you must change them in a way that breaks old callers, publish a new version of the API alongside the old one, for example under a new path prefix, and give callers time to move. Retire the old version only after usage drops and callers have been notified.

Safe change patterns

  • Additive changes first: adding a new optional field or a new path rarely breaks callers.
  • Avoid removing or renaming: these break callers and need a new version.
  • Run old and new together: keep both versions live during migration.
  • Announce deprecations: tell callers early, repeat reminders, and show dates in documentation and, if possible, in response hints.
Analogy

A restaurant prints a new menu but keeps the old one on the shelf for a few days, in case the new prices cause trouble. If the kitchen cannot make a new dish, the waiter brings back yesterday’s menu. Config snapshots give your gateway the same safety net.

!
Mind the delay

Updates to a gateway are not always instant. Do not assume the new rules are active the very second the command returns. Allow time, and check actual behaviour before declaring a release done or a rollback complete.

13Custom Domains, Encryption, and Networking

Every gateway gets a default address, but companies usually want their own name on it. Here is how addresses, encryption, and network paths fit together.

The default address

When you create a gateway, Google assigns a default web address that ends in a Google-owned domain and includes a generated name. It works immediately and is protected by encrypted connections. It is perfectly good for testing and for internal use, but it is not pretty and cannot be changed.

Your own domain name

For a public product, clients should call something like “api.yourcompany.com”. At the time of writing, the common way to achieve this has been to place a Google Cloud load balancer in front of the gateway, using a special backend type that targets serverless services, and to attach your domain and a security certificate to the load balancer. This gives you extra benefits as well: you can add web protection, use a stable global address, and combine several gateways or backends behind one name. Google may offer more direct options over time, so check the current documentation.

Encryption in transit

Traffic between clients and the gateway is encrypted using the standard secure web protocol, often called HTTPS. This prevents eavesdroppers from reading or changing messages on the way. Between the gateway and backends hosted on Google Cloud, traffic is also sent over encrypted connections. Always require secure connections and never allow plain, unencrypted access to an API that carries any private information.

Regions and delay

Distance adds delay. If your users are mostly in India and your gateway is in a faraway region, every call pays that extra travel time. Choose a gateway region close to your main users, and place backends in the same region where possible so the gateway does not cross oceans to reach them. If you serve several parts of the world, you may run several gateways, one in each region, and use a global load balancer to direct users to the nearest one.

flowchart TD
  U1["Users in Asia"] --> LB["Global load balancer with your domain and certificate"]
  U2["Users in Europe"] --> LB
  LB --> W["Optional web protection policy"]
  W --> G1["Gateway in Asia region"]
  W --> G2["Gateway in Europe region"]
  G1 --> B1["Backends in Asia region"]
  G2 --> B2["Backends in Europe region"]
    
Figure 10: A multi-region design with a custom domain, shared protection, and nearby backends.
Name

Own domain

Looks professional and lets you change providers without changing client addresses.

Safety

HTTPS only

Encrypted connections protect data and credentials in transit.

Speed

Region near users

Shorter distance means lower delay on every request.

Resilience

More than one region

A second region helps keep service going if one region has a problem.

Analogy

A shop may have a long, ugly address on the land registry, but a clear signboard and a famous street name that customers remember. The load balancer with your domain is the signboard. Behind it, the real building can be moved or doubled without customers noticing.

14Monitoring, Logging, and Tracing

You cannot protect or improve an API you cannot see. The gateway provides a rich stream of records and measurements.

Logs

Each request produces a log entry, which is a time-stamped record of what happened: the path, the method, the response code, the delay, the size, and often which key or caller was involved. Logs go to Cloud Logging, where you can search and filter them. They answer questions like “Which calls failed in the last hour?” or “Who is calling this deprecated path?” Be careful not to log sensitive personal data, and set sensible retention periods.

Metrics

Metrics are numbers measured over time, shown as charts in Cloud Monitoring. Important ones include request count, error count by status class, and latency, which is the time to answer. A useful summary is called the four golden signals: traffic, errors, latency, and saturation, which means how close you are to a limit. Watching these four tells you most of what you need to know about health.

Tracing

A trace follows one request through the gateway and backend, showing where time was spent. If a call takes two seconds, a trace shows whether the gateway, the function startup, or a slow database was to blame. Tracing is invaluable for finding the slowest link.

Alerts worth setting

AlertWhy it mattersTypical response
High rate of server errorsBackend or gateway is failingCheck recent deployments and backend health; roll back if needed
High latencyUsers see slow responsesUse traces to find the slow step; check cold starts and database speed
Spike in unauthorized responsesPossible attack or a broken clientIdentify the source; block or contact the owner
Spike in quota exceeded responsesA caller is hitting limitsContact the caller or adjust limits
Sudden drop in trafficA client may be broken or the gateway unreachableCheck status pages, configs, and domain settings
Unusual spendAbuse or a runaway clientReview logs; tighten quotas and backend caps
flowchart TD
  Req["Every request"] --> Log["Log entry in Cloud Logging"]
  Req --> Met["Metrics: traffic, errors, latency"]
  Req --> Trc["Trace spans through backend"]
  Log --> Q1["Search and investigate"]
  Met --> Dash["Dashboards and SLO tracking"]
  Met --> Al["Alerts to on-call"]
  Trc --> Slow["Find the slowest step"]
  Al --> Resp["Respond and fix"]
    
Figure 11: Logs, metrics, and traces each answer different questions about the same requests.
Analogy

A hotel keeps a visitor book (logs), counts guests and complaints each day on a wall chart (metrics), and can follow one complaint from the front desk to the kitchen to see where the delay happened (trace). A manager who has all three can run the hotel with confidence.

i
Tip

Decide what “healthy” means before launch. Set targets, for example that ninety-nine percent of requests succeed and ninety-five percent finish within a given time. Alerts based on targets are more useful than alerts based on guesses.

15Security Deep Dive

A gateway is a security checkpoint, but it is not a magic shield. This chapter shows which risks it reduces and which remain your responsibility.

Common API risks

The security community maintains a well-known list of the most frequent API weaknesses. Several of them matter directly for gateway designs.

RiskWhat it meansWhat the gateway helps withWhat you must still do
Broken object-level accessA user reads or changes someone else’s record by changing an identifierVery littleCheck ownership of every record inside the backend
Broken authenticationWeak or missing identity checksKeys and token validation on every operationChoose strong methods; protect secrets; short token lifetimes
Excessive data exposureReplies contain more fields than callers needNothing automaticReturn only needed fields
Lack of resource limitsCallers can overload the systemQuotas and timeoutsBackend caps, size limits, budgets
Broken function-level accessNormal users reach admin operationsPer-operation security requirementsRole checks in the backend
Security misconfigurationOpen backends, verbose errors, permissive settingsSingle place to enforce rulesLock down backends; review configs
Improper inventoryForgotten old versions or test endpoints still liveOne list of what is exposedRetire old versions; review the definition regularly

Handling secrets

Secrets such as signing keys, passwords, and client credentials must never be written into the OpenAPI document, which is stored and often shared widely. Keep them in a dedicated secret store and let backends fetch them at runtime. Rotate them on a schedule and immediately after any suspected leak.

Cross-origin rules

Web browsers block a page from one site from calling an API on another site unless the API explicitly allows it. This protection is called cross-origin resource sharing, or CORS. If you build a website that calls your API from a different domain, you must configure the allowed origins and methods correctly. Be as specific as possible: allowing every origin may be fine for fully public data, but it is risky for anything personal.

Input validation

Never trust data from callers. Validate sizes, types, and allowed values. The OpenAPI document describes the expected shapes, but a gateway may not enforce every detail, so validate again inside the backend. Treat all input as potentially hostile, including headers and query strings.

Defense in depth

flowchart TD
  L1["Layer 1: Edge protection and rate controls"] --> L2["Layer 2: Gateway authentication and quotas"]
  L2 --> L3["Layer 3: Backend only accepts the gateway identity"]
  L3 --> L4["Layer 4: Backend authorizes each record"]
  L4 --> L5["Layer 5: Data store permissions and encryption"]
  L5 --> L6["Layer 6: Logging, alerts, and review"]
    
Figure 12: Several independent layers mean one mistake does not become a breach.
Analogy

A bank does not rely on the front door alone. There are guards, locked counters, a vault, cameras, and audits. If a thief gets past one layer, the next still stands. Treat your API the same way.

!
Do not confuse a gateway with full security

A gateway checks identity and limits traffic. It cannot know your business rules. The most damaging API breaches usually involve valid users reading data they should not see, and only your backend code can prevent that.

16Performance and Scalability

How fast is fast enough, and what happens when traffic grows tenfold? This chapter explains where the time goes and how to keep it small.

Where the time goes

Total response time for one call is the sum of several parts: the trip from the client to the gateway, the gateway’s own checks, the trip to the backend, the backend’s work, and the return journey. The gateway adds a small overhead for checks, usually a few milliseconds, which is tiny compared with network distance or a slow database. Most performance problems live in the backend and in geography, not in the gateway itself. Measure before you guess.

Cold starts

Serverless backends may need time to start when they have been idle or when traffic jumps suddenly. The first requests in such moments are slower. You can soften this by keeping a minimum number of instances warm, by making startup work lighter, and by choosing runtimes that start quickly. Warm instances cost a little money even when idle, so balance cost against the smoothness your users need.

Scaling behavior

The gateway itself is a managed service and is designed to handle changes in traffic without you adding servers. Documented limits on request rates and sizes exist, so for very large workloads confirm the current figures and, if needed, ask Google about higher capacity. The backends scale on their own rules, such as the number of simultaneous requests per instance. The weakest link sets the real limit, and it is often the database behind the backend.

Practical speed-ups

Distance

Place close to users

Choose regions near your main audience and keep the gateway and backends together.

Backend

Keep instances warm

Use minimum instances for the busiest, most latency-sensitive operations.

Data

Cache wisely

Cache replies that rarely change, either in the backend or in a layer in front of the gateway.

Payload

Send less data

Smaller replies travel faster. Offer paging and field selection.

Calls

Reduce chattiness

Combine several small calls into one operation where it makes sense.

Limits

Set sensible timeouts

Fail fast so slow calls do not pile up.

flowchart LR
  C["Client"] -->|"network: depends on distance"| G["Gateway checks: small overhead"]
  G -->|"network inside Google: small"| B["Backend startup: cold start if idle"]
  B --> W["Backend work and database: usually the biggest part"]
  W --> R["Response travels back"]
    
Figure 13: The gateway is a thin slice of total time; backends and distance dominate.
Analogy

A courier’s journey includes the drive to the shop, signing in at reception, the wait for the goods to be packed, and the drive back. Signing in at reception takes a minute. The packing takes an hour. If you want faster deliveries, hire more packers, not more receptionists.

i
Tip

Test with realistic load before launch. Increase traffic step by step and watch latency and errors. The first thing to break is rarely the thing you expected.

17Understanding the Cost

Money matters for every design. Prices change, so this chapter explains the shape of the costs rather than quoting numbers.

The pricing idea

API Gateway has generally been priced by the number of calls processed, often with a free allowance each month and a lower price per call at higher volumes, plus charges for data leaving Google Cloud. There is no cost for idle servers because there are no servers for you to run. Always read the current pricing page and use the pricing calculator for estimates, because details and amounts can change.

Costs beyond the gateway

The gateway call is often the smallest part of the bill. The larger costs are usually these.

  • Backend compute: functions or containers billed by run time, memory, and number of requests.
  • Data and databases: storage, reads and writes, and the instances that serve them.
  • Network traffic out: data sent to the internet or to other regions.
  • Load balancer and protection: if used for custom domains and web protection.
  • Logging and monitoring: large volumes of logs can become surprisingly expensive.
  • People time: building, maintaining, and supporting the API.

Controlling cost

1

Estimate

Predict calls per month, average reply size, and backend time per call.

2

Set budgets and alerts

Receive warnings at fifty, eighty, and one hundred percent of the plan.

3

Cap the backends

Limit maximum instances so a flood cannot create an unlimited bill.

4

Use quotas

Limit calls per caller so one customer cannot consume everything.

5

Review monthly

Look at the biggest cost lines and the busiest callers and ask what can be trimmed.

Cost comparison thinking

When comparing options, count the whole cost. A gateway that charges per call may look cheap or expensive depending on traffic. At low volume, a managed gateway with per-call pricing is usually the cheapest and simplest choice. At very high volume, fixed-capacity products or self-managed tools might cost less per call, but they bring operating costs and staff time. Compare at your expected volume, not at the extremes.

flowchart TD
  Cost["Monthly API cost"] --> A["Gateway per-call charges"]
  Cost --> B["Backend compute"]
  Cost --> C["Database and storage"]
  Cost --> D["Network egress"]
  Cost --> E["Load balancer and protection"]
  Cost --> F["Logs and monitoring"]
    
Figure 14: The gateway line is only one slice of the total monthly bill.
Analogy

Taking a taxi costs a fare per trip with no car to maintain. Owning a car costs more upfront but less per trip if you drive constantly. Neither is right for everyone. The best choice depends on how often you travel.

18Choosing Among Google Cloud Options

Google Cloud offers several ways to put a front door on a service. Picking the right one saves months of rework.

The main options

API Gateway is a light, managed gateway for serverless backends, driven by an OpenAPI document. Apigee is a full API management platform with developer portals, advanced policies, analytics, and monetization for large programmes. Cloud Endpoints is an earlier service that uses the same proxy technology and can be deployed with backends on other Google Cloud platforms, and it requires more setup of the proxy itself. Cloud Load Balancing is not a gateway in the API sense, but it distributes traffic, terminates secure connections, and supports web protection, and it is often combined with a gateway. Calling Cloud Run directly is the simplest option, where the service itself handles authentication and the public address.

NeedAPI GatewayApigeeCloud EndpointsLoad balancerDirect to Cloud Run
Simple, managed front doorStrong fitHeavier than neededMore setupNot API-awareSimplest
Developer portal and onboardingNot includedStrong fitLimitedNoNo
Rich policies and transformationsLimitedStrong fitLimitedLimitedNo
Per-consumer plans and billingBasic quotasStrong fitBasicNoNo
Custom domain and web protectionThrough a load balancerSupportedThrough a load balancerStrong fitSupported in several ways
Operating effortLowMedium to highMediumLowLowest

Product capabilities and lifecycle status change over time, so confirm the current documentation before deciding. This table is a teaching guide, not a feature guarantee.

A decision flow

flowchart TD
  S["Start: I need to expose an API"] --> Q1{"Only one service and simple needs?"}
  Q1 -->|"Yes"| D1["Call Cloud Run directly with built-in authentication"]
  Q1 -->|"No"| Q2{"Need developer portal, monetization, or advanced policies?"}
  Q2 -->|"Yes"| D2["Consider Apigee"]
  Q2 -->|"No"| Q3{"Serverless backends and OpenAPI contract?"}
  Q3 -->|"Yes"| D3["API Gateway"]
  Q3 -->|"No"| D4["Consider load balancer, Endpoints, or other tools"]
  D3 --> Q4{"Need own domain or web protection?"}
  Q4 -->|"Yes"| D5["Add a load balancer in front"]
  Q4 -->|"No"| D6["Use the default gateway address"]
    
Figure 15: A simple decision flow for choosing a front door.

Signs you have outgrown a simple gateway

  • External developers ask for sign-up pages, documentation portals, and test consoles.
  • You need different plans with different limits, and you want to bill by usage.
  • You need to transform messages, call several backends in one request, or apply many custom rules.
  • You must manage many APIs across many teams with central governance.
Analogy

A small shop needs a door and a lock. A department store needs a lobby, a directory, security staff, and a customer service desk. The right entrance depends on the size of the building. Do not buy a department store lobby for a corner shop, and do not expect a simple door to run a department store.

19The Lifecycle of an API and Its Data Flow

An API has a life: it is planned, built, released, used, changed, and eventually retired. The gateway supports each stage.

Stage by stage

1

Design

Agree on the paths, shapes, and rules in an OpenAPI document before writing code. This contract is the heart of everything that follows.

2

Build

Teams write backends that match the contract, and can use mock replies for early testing.

3

Test

Run checks against a staging gateway with realistic data and load.

4

Release

Create a config, update the production gateway, and watch carefully.

5

Operate

Monitor health, answer support questions, handle incidents, and tune limits.

6

Evolve

Add features through backward-compatible changes and publish new versions when needed.

7

Retire

Announce an end date, watch usage drop, and finally remove the old version.

Following the data

Understanding where data travels helps you protect it. A request body from a customer’s phone crosses the internet to the gateway, then moves inside Google’s network to a backend, which may store parts of it in a database or send it to a queue. The reply travels the same path in reverse. At every hop, ask three questions. Is it encrypted? Who can read it? How long does it stay? Logs also hold data, such as paths and sometimes identifiers, so include them in your thinking.

flowchart LR
  P["Customer phone"] -->|"Encrypted over internet"| GW["Gateway: reads headers, checks identity"]
  GW -->|"Encrypted inside Google network"| BE["Backend: processes data"]
  BE --> DB[("Database: stored and encrypted")]
  BE --> Q["Queue: temporary"]
  GW --> LG["Logs: metadata kept for a period"]
  BE --> LG
    
Figure 16: Data passes through several places; each deserves a protection and retention decision.
Analogy

A parcel passes through sorting centres, trucks, and doorsteps. A careful courier firm knows what happens to every parcel at each stage, who may open it, and how long records are kept. Your API data deserves the same tracking.

20Advantages, Disadvantages, and Trade-offs

Every tool is a bundle of benefits and costs. Here is an honest balance sheet.

Advantages

  • Fully managed: no servers, patches, or capacity planning.
  • One consistent front door for many serverless backends.
  • Authentication and quotas applied in one place.
  • Contract-first design through OpenAPI encourages clear agreements.
  • Immutable configs allow safe changes and quick rollbacks.
  • Pay-per-call pricing suits small and growing workloads.
  • Integrated logging, monitoring, and tracing.

Disadvantages

  • Limited policy and transformation features compared with full platforms.
  • No built-in developer portal or monetization.
  • Custom domains and web protection need extra components.
  • Config updates are not instant.
  • Focused on certain backend types; other targets need workarounds.
  • Per-consumer controls are basic.
  • Product direction and lifecycle should be checked regularly.

Key trade-offs

DecisionOption AOption BHow to choose
Simplicity vs featuresLight gatewayFull platformStart light; move up when real needs appear
Central vs local securityAll checks at the gatewayChecks in each serviceDo both: coarse at the gateway, fine in services
Speed vs costWarm instancesScale to zeroWarm for latency-sensitive paths only
One gateway vs manyShared by all teamsOne per team or productSeparate when teams release at different speeds
Strict vs flexible contractTight schemasLoose, evolvingPublic APIs deserve tighter contracts
Analogy

A small, nimble van delivers quickly and cheaply, but it cannot carry a piano. A large truck can carry anything, but costs more to run and park. Pick the vehicle for the load you actually carry most days, and hire a specialist for the rare big one.

21Design Patterns and Anti-patterns

Patterns are proven solutions to repeating problems. Anti-patterns are tempting mistakes that cause pain later.

Helpful patterns

PATTERN 01: Gateway per product or teamRecommended
Context

Several teams share one gateway and block each other’s releases.

Decision

Give each product its own API and gateway, with a shared platform team providing standards.

Consequence

Teams release independently; the platform team must maintain common guidelines so experiences stay consistent.

PATTERN 02: Contract firstRecommended
Context

Front-end and back-end teams wait for each other.

Decision

Write the OpenAPI document first, review it together, and build both sides against it.

Consequence

Fewer misunderstandings and parallel work; requires discipline to keep the contract current.

PATTERN 03: Gateway in front, identity at the backendRecommended
Context

Backends are reachable by anyone who learns their address.

Decision

Require authenticated invocation at the backend and allow only the gateway account.

Consequence

The gateway becomes the only door, at the price of managing service accounts and permissions.

PATTERN 04: Parallel versionsRecommended
Context

A breaking change would harm existing customers.

Decision

Publish the new version beside the old one and migrate customers gradually.

Consequence

Smooth migration, but two versions must be supported for a while.

Anti-patterns to avoid

Anti-patternWhy it hurtsBetter approach
Open backendsAttackers skip the gatewayRequire the gateway identity
Business logic in the gateway configHard to test, hard to readKeep logic in services
One giant shared gateway for everythingReleases collide; one mistake affects everyoneSplit by product or team
Editing production by handNo history; easy mistakesDeploy from version control through a pipeline
No quotasUnbounded cost and riskSet finite limits and caps
Using keys as user identityKeys identify apps, not peopleUse tokens for users
Never retiring old versionsGrowing maintenance burden and riskAnnounce and enforce end dates
Analogy

Good patterns are like well-marked roads, and anti-patterns are shortcuts through someone’s garden. The shortcut saves a minute today and causes an argument next month.

22Best Practices and Common Mistakes

A short, practical checklist drawn from everything so far.

  • Keep the OpenAPI document in version control and review every change.
  • Use a dedicated service account for each gateway, with minimum permissions.
  • Require authentication on every backend and allow only the gateway.
  • Choose authentication per operation, and use tokens for user-facing data.
  • Define quotas, timeouts, and backend instance caps from day one.
  • Test on a staging gateway before touching production.
  • Deploy through an automated pipeline, never by hand.
  • Watch error rate, latency, and spend after every release.
  • Version public APIs and announce deprecations early.
  • Place gateways and backends in regions close to users.
  • Use a load balancer when you need your own domain or web protection.
  • Document every operation with examples and clear error descriptions.

Common mistakes and quick fixes

MistakeSymptomFix
Gateway account lacks invoker permissionGateway returns authorization errors from the backendGrant the invoker role on the specific backend
Wrong audience in the backend settingsBackend rejects the gateway tokenAlign the audience with the backend address
Wrong path translation styleBackend receives unexpected paths and returns not foundChoose the correct translation option for that backend
Token issuer or audience mismatchValid users receive unauthorized errorsCompare configured values with token contents
Timeout too shortSporadic gateway timeout errors under loadMatch the deadline to real backend behavior
Required services not enabledConfig creation failsEnable the required services in the project
Expecting instant updatesOld behavior persists for a short timeWait and verify before concluding
Keys embedded in public appsAbuse and unexpected billsRestrict, monitor, and rotate; use tokens for sensitive paths
flowchart TD
  E["Error seen by client"] --> A{"Which status class?"}
  A -->|"401 or 403"| B["Check key or token, audience, and invoker permission"]
  A -->|"404"| C["Check path and translation style"]
  A -->|"429"| D["Check quota usage and limits"]
  A -->|"5xx"| F["Check backend health, timeouts, and recent releases"]
  B --> G["Fix and retest on staging"]
  C --> G
  D --> G
  F --> G
    
Figure 17: A quick triage map from error class to likely cause.
Analogy

Pilots use checklists not because they are forgetful but because the stakes are high and the steps are many. A checklist for releases turns hard-won lessons into habits so that every flight begins as safely as the last.

23Automating Releases and Testing the API

Manual changes to a live front door are how outages begin. A pipeline turns every release into the same careful routine.

What a good pipeline does

A pipeline is an automated series of steps that runs whenever someone proposes a change. For an API behind a gateway, the pipeline checks the contract, creates a new config, deploys to a staging gateway, runs tests, and only after success promotes the change to production. Because the pipeline always follows the same steps, results are repeatable and each release leaves a record of who changed what and when.

flowchart LR
  PR["Pull request with OpenAPI change"] --> LINT["Check contract style and rules"]
  LINT --> BUILD["Create new API config"]
  BUILD --> STG["Deploy to staging gateway"]
  STG --> TEST["Run functional and security tests"]
  TEST --> APPROVE{"Approved?"}
  APPROVE -->|"Yes"| PROD["Update production gateway"]
  APPROVE -->|"No"| STOP["Stop and report"]
  PROD --> WATCH["Watch errors and latency"]
  WATCH -->|"Problem"| BACK["Roll back to previous config"]
    
Figure 18: A release pipeline from proposed change to watched production deployment.

Kinds of tests

TestQuestion it answersWhen to run
Contract checkIs the OpenAPI document valid and consistent with our style rules?Every proposed change
Functional testDoes each operation return the expected result?On the staging gateway after each deployment
Security testDo missing, expired, or wrong credentials get rejected?On staging, every release
Backward compatibility testDo old callers still work with the new version?Before promoting any change
Load testDoes it hold up at expected and peak traffic?Before major launches and periodically
Smoke testIs the live system basically healthy right after release?Immediately after production deployment

Environments

Keep separate environments for development, staging, and production, each in its own project where possible. Separate projects keep keys, quotas, and permissions apart, so a test mistake cannot touch real customers. Staging should look as much like production as you can afford: same regions, same authentication, same shape of backends.

Infrastructure described as files

Many teams describe the gateway, the service accounts, and the permissions in configuration files managed by an infrastructure-as-code tool. That way the whole setup can be reviewed, repeated in a new project, and rebuilt quickly after a disaster. Whatever tool you choose, the principle is the same: the repository is the source of truth, and the live system should match it.

Analogy

A bakery that follows a written recipe and checks each batch before it goes on the shelf produces the same loaf every day. A baker who improvises every morning produces surprises. Customers prefer predictable bread, and predictable releases.

i
Tip

Include a “negative” security test in every release: confirm that a call with no credentials is rejected. It is the cheapest way to notice that a misconfiguration has accidentally opened a door.

24Failure Scenarios and Recovery

Things will go wrong. What matters is how quickly you notice, how little damage spreads, and how calmly you recover.

Scenario catalogue

ScenarioWhat users seeFirst checksRecovery
Bad config releasedSudden errors on some or all pathsRecent deployment historyPoint the gateway back to the last good config
Backend downServer errors or gateway timeoutsBackend logs and statusFix or roll back the backend; consider a fallback response
Backend slowTimeouts, long waitsTraces, database health, cold startsRaise capacity, warm instances, tune the slow step
Identity provider unreachableNew sign-ins fail; token checks may be affectedProvider statusWait or use a documented fallback; communicate clearly
Credential leakedUnexpected traffic and costLogs by key or callerRevoke and rotate the credential; tighten quotas
Traffic floodMany quota errors, higher latencyTraffic sources and patternsApply edge protection, lower quotas, cap backends
Regional problemCalls to one region failProvider status for that regionShift traffic to a second region if you built one
Certificate or domain expirySecure connection warningsCertificate dates and DNSRenew or fix records; add expiry alerts

An incident routine

1

Detect

An alert fires or a customer reports a problem.

2

Stabilize

Reduce harm first: roll back the last change, block abusive callers, or switch traffic. Do not hunt for the root cause while customers are suffering.

3

Communicate

Tell affected users what is happening and when to expect the next update.

4

Diagnose

Use logs, metrics, and traces to find the cause.

5

Fix

Apply a safe fix through the normal pipeline where possible.

6

Learn

Hold a blameless review. Record what happened, why, and what will change.

flowchart TD
  A["Alert: error rate high"] --> B{"Recent release?"}
  B -->|"Yes"| C["Roll back gateway config or backend"]
  B -->|"No"| D{"Backend healthy?"}
  D -->|"No"| E["Fix or scale backend"]
  D -->|"Yes"| F{"Traffic unusual?"}
  F -->|"Yes"| G["Throttle, block, or add edge protection"]
  F -->|"No"| H["Check dependencies and identity provider"]
  C --> I["Confirm recovery in metrics"]
  E --> I
  G --> I
  H --> I
    
Figure 19: A triage tree for a rising error rate.

Designing for graceful failure

  • Timeouts everywhere: never let a call wait forever.
  • Retries with care: callers should retry only safe operations, wait a little longer each time, and add random delay so they do not all retry together.
  • Clear errors: return useful messages and codes so callers know whether to retry, fix their request, or wait.
  • Fallbacks: for non-critical features, show cached or reduced content rather than failing completely.
  • Practice: run drills so that the first rollback is not also the first time anyone has tried it.
Analogy

Ships carry lifeboats and run drills even though they hope never to sink. The drill is not pessimism. It is the reason that, on the bad day, people know exactly where to go and what to do.

25Real-World and Industry Examples

The gateway idea appears in nearly every industry that exposes services over the internet. These are typical shapes, described loosely.

Retail

Mobile shopping app

One API serves product search, cart, and orders to the app. Tokens identify shoppers, and quotas protect search during big sales.

Finance

Partner integrations

Banks and payment companies give partners keys and service account access, with strict logging and short-lived credentials for audit.

Health

Appointment services

Clinics expose booking operations while keeping records behind the backend, with careful logging rules to avoid exposing personal data.

Media

Content delivery metadata

Streaming and publishing teams expose catalog and recommendation operations to many client apps with different quotas.

Logistics

Tracking for customers

A delivery firm lets customers and partners query shipment status through a stable API while internal systems change underneath.

Startups

Fast launch

Small teams ship a clean public API on serverless backends without hiring a platform team, then upgrade when growth demands.

A common growth story

Many companies follow the same path. They begin with a few functions or services called directly. As partners and mobile apps appear, they add a gateway for consistent authentication and quotas. As the API becomes a product with outside developers, they add a custom domain and web protection. Finally, if they need developer portals and advanced policies, they move to a full management platform. Each step solves a problem the previous step revealed.

flowchart LR
  S1["Stage 1: Direct calls to services"] --> S2["Stage 2: Add a managed gateway"]
  S2 --> S3["Stage 3: Own domain and web protection"]
  S3 --> S4["Stage 4: Full API management platform"]
    
Figure 20: A common maturity path for an API programme.
i
Note on examples

These examples describe typical public practice in each industry and are not claims about the internal systems of any named company. For real case studies, read the engineering blogs and customer stories published by the companies themselves.

26Learning Path and Glossary

If you are starting from zero, follow this ladder. Each rung takes a few days of reading and practice.

1

Web basics

Learn how requests, responses, status codes, headers, and secure connections work.

2

REST ideas

Understand resources, methods, and good naming of paths.

3

OpenAPI

Practice describing a small API in a document and viewing it in a documentation tool.

4

Serverless backends

Deploy one function and one container service and call each of them.

5

Identity

Learn service accounts, API keys, and tokens, and what each proves.

6

Gateway practice

Put a gateway in front of your test backend, add a key requirement, then a quota, then a token requirement.

7

Operations

Build dashboards and alerts, run a rollback drill, and automate the release.

Glossary

TermPlain meaning
APIA set of agreed requests that one program can make to another
API configAn immutable snapshot of an API definition that a gateway can run
GatewayThe running front door, bound to one config in one region
BackendThe service that does the real work behind the gateway
OpenAPIA standard file format for describing an API
API keyA secret string that identifies a calling application
JWTA signed token that proves facts about a caller
Service accountAn identity for a program rather than a person
QuotaA limit on how many calls may be made in a period
LatencyThe time taken to answer a request
Cold startExtra delay when an idle backend must start up
CORSBrowser rules about which websites may call an API
RollbackReturning to a previous known-good version
DeprecationAnnouncing that something will be retired
Analogy

Learning this subject is like learning to run a restaurant: first the kitchen basics, then the menu, then the doors and locks, and finally the daily routines. Skipping straight to the front desk is tempting, but it works best once you know what happens in the kitchen.

27A Worked Example: A Neighbourhood Delivery Start-up

This made-up story ties the ideas together. The company and its numbers are fictional.

Imagine a small company called QuickBasket that delivers groceries from local shops. It has a mobile app for customers, a tablet app for shop owners, and a few partner delivery firms. At first, the developers called three Cloud Functions directly from the apps. It worked, until a shop owner’s tablet app was copied by a curious teenager who started calling the order function in a loop. Overnight, the function scaled up and the bill jumped.

The team decided to add a gateway. They wrote an OpenAPI document with four operations: list shops, view the menu, place an order, and check order status. They created one API, one config, and one gateway in a region near their customers. For the customer app, they required sign-in tokens from their identity provider. For the shop tablets, they required a different token audience. For delivery partners, they issued API keys tied to separate projects so each partner had its own quota.

flowchart TD
  CA["Customer app"] -->|"User token"| GW["QuickBasket Gateway"]
  SA["Shop tablet app"] -->|"Shop token"| GW
  PA["Delivery partners"] -->|"API key per partner"| GW
  GW -->|"/shops, /menus"| F1["Function: catalog"]
  GW -->|"/orders"| R1["Cloud Run: orders service"]
  GW -->|"/status"| F2["Function: tracking"]
  R1 --> DB[("Orders database")]
  F2 --> DB
    
Figure 21: QuickBasket’s gateway serves three kinds of callers with three kinds of credentials.

What changed

Problem beforeFix with the gateway
Functions open to anyone with the addressFunctions require the gateway identity; the address alone is useless
One abusive caller could cause a huge billPer-caller quotas and backend instance caps
Shops and customers shared the same accessDifferent token audiences for each app
Releases broke the apps unexpectedlyStaging gateway, pipeline tests, and rollback to the previous config
No visibility into usageDashboards for traffic, errors, latency, and top callers

The bumps along the way

The first release failed because the gateway’s service account lacked permission to call the orders service, so every order returned an authorization error. A staging test caught it. A later change used the wrong path style, so the backend received doubled prefixes and returned not found. The team fixed it by switching the translation option and added a test for that path. When a partner’s key leaked into a public forum, the team revoked it, issued a new one, and lowered the quota, all without touching the apps used by customers.

Growth

A year later, QuickBasket opened its API to outside developers. They added a load balancer with their own domain and web protection in front of the gateway, and began evaluating a full API management platform because outside developers wanted a sign-up portal and usage plans. The simple gateway had served them well through the early stages, and the contract-first habit made the move easier because the OpenAPI documents carried over.

Analogy

QuickBasket’s story is like a street vendor who gets a shop with a lockable door, then a bigger store with a loading dock and a customer desk. Each upgrade arrived when the previous setup started to strain, not before.

28Governance, Ownership, and Team Habits

Technology alone does not keep an API healthy. Clear ownership and shared habits matter just as much as configuration.

Who owns what

Every API needs a named owner who answers questions, approves changes, and decides when versions retire. Without an owner, small problems linger, documentation rots, and nobody feels responsible when something breaks. Large organizations often split duties between a platform team, which provides the gateway standards, templates, and pipelines, and product teams, which own their specific APIs and backends.

RoleMain responsibilityTypical permissions
API ownerContract, versions, deprecation decisionsApprove changes to the OpenAPI document
Platform teamStandards, templates, shared pipelines, guardrailsManage gateway projects and shared settings
Backend teamService code, data rules, per-record authorizationDeploy and manage their own backends
Security reviewerReview authentication choices and exposureRead access to configs and logs
On-call engineerRespond to alerts and incidentsRoll back configs and adjust quotas

Standards that help

  • Naming: consistent path and field names make every API feel familiar.
  • Error format: one agreed shape for errors so callers handle them the same way everywhere.
  • Review checklist: a short list covering authentication, quotas, logging, and documentation before any release.
  • Deprecation policy: a written promise, such as a minimum notice period, so customers can plan.
  • Documentation: examples for every operation, kept in step with the contract.

Regular reviews

Schedule a periodic review of each API. Look at who calls it, which operations are unused, which credentials are old, and which permissions are broader than necessary. Remove what nobody needs. Forgotten endpoints and stale keys are the quiet source of many security incidents, and a calendar reminder is a cheap defence.

Culture over tools

The healthiest teams treat the API as a product with customers, even when those customers are colleagues in another department. They publish changelogs, answer questions quickly, collect feedback, and measure satisfaction through usage and support tickets. They celebrate quiet releases and learn from incidents without blaming individuals. Over time, this culture matters more than any single configuration option, because it keeps standards alive after the original authors have moved on to other projects.

flowchart LR
  PT["Platform team: standards and templates"] --> PA["Product team: owns API and backend"]
  PA --> SR["Security review"]
  SR --> PL["Pipeline release"]
  PL --> OC["On-call monitoring"]
  OC --> RV["Periodic review and cleanup"]
  RV --> PA
    
Figure 22: A governance loop keeps APIs owned, reviewed, and tidy.
Analogy

A building with many tenants still needs a caretaker, a rulebook, and regular inspections. Without them, doors are propped open, old keys circulate, and nobody knows who lives in which flat.

29Frequently Asked Questions

Q1What is API Gateway in one sentence?
It is a managed Google Cloud service that provides a single, secured, monitored front door for serverless backends, driven by an OpenAPI description.
Q2Do I need to manage servers?
No. Google runs and scales the gateway. You manage the API definition, permissions, and backends.
Q3What is the difference between an API config and a gateway?
The config is an immutable snapshot of the API definition. The gateway is the running instance in a region that serves traffic according to one config at a time.
Q4Which backends can it front?
It is designed mainly for Google Cloud serverless backends such as Cloud Functions, Cloud Run, and App Engine. Check the current documentation for other supported targets.
Q5How do I authenticate users?
Configure token validation for an identity provider, specifying the issuer, audience, and key location. Callers send the signed token with each request.
Q6Are API keys enough for security?
Keys identify applications and are useful for quotas, but a stolen key works for anyone. Use tokens for user data and always protect backends independently.
Q7Can someone bypass the gateway and call my backend directly?
Only if the backend allows it. Require authenticated invocation and grant access only to the gateway’s service account.
Q8How do I limit how much each caller can use?
Define metrics and limits in the API definition, and give each caller a separate project and key so counts are tracked per caller.
Q9Can I use my own domain name?
Commonly by placing a load balancer in front with your domain and certificate. Check current documentation for any more direct options.
Q10How do I update the API without downtime?
Create a new config, test it on a staging gateway, then update the production gateway to use it. Keep the old config for quick rollback.
Q11How do I roll back a bad release?
Point the gateway back to the previous config, then verify the behavior, remembering that updates can take a short time to apply.
Q12When should I choose Apigee instead?
When you need developer portals, usage plans and monetization, advanced policies, or central governance across many APIs and teams.
Q13Does the gateway slow down my API?
It adds a small overhead. Distance, cold starts, and database speed usually matter far more.
Q14How much does it cost?
Pricing has been based mainly on the number of calls, often with a free allowance. Backend, network, and logging costs can be larger, so use the official pricing page and calculator.
Q15What should I monitor first?
Traffic, error rate, latency, and spend. Add alerts for sudden changes in any of them, and for spikes in unauthorized or quota-exceeded responses.

30Summary and Key Takeaways

API Gateway gives serverless backends a single, managed front door. You describe your API in an OpenAPI document, turn it into an immutable config, and run it on a regional gateway that checks identity, applies quotas, forwards calls with its own identity, and records everything for monitoring. It is light, simple, and cheap to start with, and it deliberately leaves heavier features to larger platforms. Used with locked-down backends, contract-first design, automated pipelines, and sensible limits, it lets small teams offer reliable, secure APIs without running any gateway servers.

A good gateway is a calm front desk: it checks who you are, keeps the queue fair, points you to the right department, and writes everything down.

Key Takeaways

  • One managed front door: the gateway gives many serverless backends a single address, consistent security, and shared monitoring.
  • Contract first: the OpenAPI document is the source of truth; configs are immutable snapshots that enable safe releases and quick rollbacks.
  • Authenticate at the gateway, authorize in the backend: keys identify apps, tokens identify users, and fine-grained access rules belong in your services.
  • Close the side doors: require the gateway identity at every backend so nobody can bypass the checks.
  • Limit everything: quotas, timeouts, request sizes, and backend instance caps keep floods and bills bounded.
  • Automate and observe: deploy through pipelines, test security on staging, and watch traffic, errors, latency, and spend.
  • Choose by need: start with a light gateway, add a load balancer for domains and protection, and move to a full platform when portals and plans become necessary.