AlgoViz

AWS API Gateway

medium 28 min

Amazon API Gateway is a managed front door for HTTP and WebSocket APIs.

Video lesson · Chapter 1 of 5

A product lookup through a REST API

0:00 / 4:13

AWS API Gateway in 90 seconds

1:30Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

Amazon API Gateway is a service in which you describe an API, its paths, methods, checks and backends, and AWS runs the gateway that answers. You get a web address; there are no machines to size or patch.

It comes in three kinds. A REST API has the most features. An HTTP API has fewer and is cheaper. A WebSocket API keeps connections open and turns messages into calls to your backend.

The gateway is the front of your system, not its logic. What sits behind it is called an integration: a Lambda function, an HTTP server, a private service in your network, or another AWS service called directly.

Why it exists

Every public API needs the same things: TLS, checking who calls, limits per customer, logs, versions and a way to route a path to a program. Writing them into every service is repeated work, and the result is uneven.

Running a gateway yourself means capacity planning and patching. A managed one charges for requests instead, which is comfortable for small or uneven traffic. In return you accept its limits on size, time and control.

A short history

  1. July 2015

    Amazon API Gateway launches, with REST APIs.

  2. December 2018

    WebSocket APIs are added.

  3. December 2019

    HTTP APIs appear as a preview, announced as up to 71% cheaper than REST APIs.

  4. June 2024

    The integration timeout of Regional and private REST APIs can be raised above 29 seconds on request.

Words to know

Resource and method
A URL path and an HTTP verb on it, in a REST API. HTTP APIs call the pair a route.
Integration
What the gateway calls for a method.
Deployment
A fixed snapshot of a REST API's configuration.
Stage
A name such as prod that points to a deployment and has its own settings.
Authorizer
The check that decides who may call.
Usage plan
A rate, a burst and a quota for the API keys that belong to it.
VPC link
A private connection from the gateway into your network.
Mapping template
A script in the Velocity Template Language (VTL) that rewrites a request or response.
Token bucket
A limit where tokens refill at a rate and a full bucket allows a burst.

How it works

Step through the idea, or press Play.

Step 1 of 3

Arrive. TLS ends, the stage and route are found

Understand it

Start here

The garden toll booth

Imagine a botanical garden with three glasshouses and one booth at the gate. Nobody reaches a plant without passing the booth.

One booth for the whole garden
ROSESCACTIPALMSGARDENOne booth, three sections

The booth grows no plants. It checks, counts and points the way.

The idea

What it does for a system

One door, three kinds of backend

Apps and devices call API Gateway over HTTPS. Inside our AWS account it invokes Lambda functions, reaches a balancer and services in a private network through a VPC link, and writes directly to an SQS queue. Lambda and the services use one database.
Integrations can be functions, private services, public HTTP servers, AWS services, or a mock answer.
  • Managed

    Capacity, zones and patches are AWS's work. The service agreement names 99.95% monthly uptime per region.

  • Caller checks

    IAM signatures, JWT, Cognito, Lambda authorizers, mutual TLS, WAF in front of REST APIs.

  • API management

    Stages, canary releases, API keys, usage plans, custom domains, developer portals.

  • Less backend work

    Bad requests are refused early and GET answers can be cached.

  • Pay per request

    No minimum fee. Good for small and uneven traffic; compare at steady high traffic.

  • AWS inside

    Lambda, DynamoDB, SQS, SNS, S3 and Step Functions without a server between.

The general pattern, aggregation and a gateway per client type belong to API gateway. Signed tokens are in API authentication. Here we look at the product.

Types

REST, HTTP or WebSocket API

What each type has

REST APIHTTP APIWebSocket API
EndpointsEdge-optimized, Regional, privateRegionalRegional
CallersIAM, Cognito, JWT, Lambda, resource policyIAM, JWT (also Cognito), LambdaIAM or Lambda on connect
API keys and usage plansYesNoYes
AWS WAFYesNo (put CloudFront in front)No
Response cacheYesNoNo
Validation, body mappingYesParameters onlyMapping, validation
Canary, response streamingYesNoNo
DeploymentsBy handAutomatic if you wantBy hand or automatic
From AWS's comparison of REST and HTTP APIs in November 2026. Features move between types, so look again before deciding.

Which type?

Model

Resources, methods, integrations

One small API

PathMethodIntegration
/usersGETLambda, proxy
/ordersPOSTSQS, directly
/orders/{id}GETPrivate service through a VPC link
/healthGETMock: a fixed answer

Integration kinds

KindWhat happensNotes
Lambda proxyThe whole request becomes an event; the function returns status, headers and bodyThe usual choice
Lambda or HTTP, customYou map request and response with templatesREST APIs
HTTP proxyPassed to a URL as it isPublic servers or through a VPC link
AWS serviceThe gateway calls the service with a roleNo function to run or pay for
MockAnswer made in the gatewayREST APIs: tests, CORS

Asynchronous work. For a slow task, let the gateway write to a queue or start a workflow and answer 202 at once. The client asks later, or gets a webhook. See queues.

Request

The life of one request

A GET with an authorizer and a cache miss

The order of checks is simplified. Every check that fails saves a backend call.
  1. 1

    Arrive

    HTTPS to a Regional endpoint, or through AWS's own CloudFront distribution for an edge-optimized one.

  2. 2

    Route

    TLS ends. Path and method choose the configuration; stage variables hold values such as a function alias.

  3. 3

    Check the caller

    Signature, JWT or authorizer. A failure is 401 or 403.

  4. 4

    Count

    Usage plan, method and account throttles. Too many is 429.

  5. 5

    Validate and transform

    Required parameters and a JSON schema (REST). A bad request is 400. Templates may rewrite the body.

  6. 6

    Cache

    REST APIs can answer GET requests from the stage's cache.

  7. 7

    Integrate

    One backend call with a timeout. Too slow is 504.

  8. 8

    Answer

    Response mapping, access log, metrics, reply.

Reading the errors

CodeUsual causeLook at
400Validation failedModel, required parameters
401, 403Caller refused, key missing, WAF, resource policyAuthorizer logs, policy
403 "Missing Authentication Token"Often a path or method that is not deployed (REST)URL, stage, deployment
404No such route (HTTP API)Route key
413Payload too largeUpload to storage instead
429Throttle or quotaUsage plan, account limit
502The integration's answer could not be usedLambda errors, response shape
504The integration took too longBackend time; make it asynchronous

Callers

Authorizers

KindBest forWatch
IAM (Signature Version 4)Other AWS workloadsCallers need AWS credentials
JWT or CognitoUsers of an identity providerSigning keys are cached up to two hours, so plan key rotation
Lambda authorizerOwn rules: opaque tokens, a database look-upExtra call and cold starts; cache the result
API keyCounting a customer's callsNot a login. Never the only check

A Lambda authorizer with its cache

A TOKEN authorizer sees one header. A REQUEST authorizer sees headers, query, stage variables and context.

Limits

Throttling and quotas

Four layers, checked from narrow to wide

A token bucket with the default account values

accepted in t seconds≤B+r t5000+10000×2=25000\text{accepted in } t \text{ seconds} \le B + r\,t \qquad 5000 + 10000 \times 2 = 25000
Bucket 5,000 and rate 10,000 a second. A few newer regions start at 2,500 a second and 1,250. The rate is shared by all your APIs in that region.

AWS calls throttles and quotas best effort: targets, not guaranteed ceilings. Its advice is not to use them to control costs or block access. Use WAF to block, budgets to watch money, and concurrency limits at the backend to protect it. Methods are compared in rate limiter algorithms.

Shell
# A plan for one partner: 50 a second, bursts of 100, 10,000 a monthaws apigateway create-usage-plan --name BasicPlan \  --throttle burstLimit=100,rateLimit=50 \  --quota limit=10000,period=MONTH \  --api-stages apiId=abc123,stage=prodaws apigateway create-api-key --name ClientA --enabledaws apigateway create-usage-plan-key \  --usage-plan-id plan123 --key-id key456 --key-type API_KEY
The plan must be attached to a stage, and the method must require a key, or nothing is counted.

Shape

Validation, transformation and cache

Validation (REST): required parameters plus a JSON schema model. A malformed order is refused before a function runs. Transformation: templates in VTL reshape bodies and headers. They are powerful and easy to get wrong, so keep them short and test them; a template that fails gives a 5xx or an odd body.

Text
#set($inputRoot = $input.path('$')){  "userId": "$util.escapeJavaScript($input.params('id'))",  "requestId": "$context.requestId",  "sourceIp": "$context.identity.sourceIp",  "contentType": "$util.escapeJavaScript($input.params().header.get('Content-Type'))",  "body": $input.json('$')}
A VTL request template. Escape values that callers control.

The stage cache (REST only)

FactValue
Lifetime300 s by default, 0 to 3,600 s
MethodsGET by default; others only if you override them
Largest item1,048,576 bytes
KeyPath, plus the parameters and headers you mark as cache keys
CostBy the size you reserve, used or not
PromiseBest effort: hits are not guaranteed

Release

Stages, deployments and canaries

Editing a REST API changes a draft. A deployment is a snapshot, and a stage points to one. Forgetting to deploy is the classic "my change does nothing". HTTP APIs can deploy automatically.

A canary release on one stage

Watch errors and latency of the canary, then promote or remove it. REST APIs only.
Shell
aws apigateway create-deployment --rest-api-id abc123 \  --stage-name prod --description "add GET /users"curl -i "https://abc123.execute-api.us-east-1.amazonaws.com/prod/users" \  -H "Authorization: Bearer $TOKEN"

Custom domains replace the generated address. Certificates come from ACM: in us-east-1 for edge-optimized endpoints, in the API's own region for Regional ones. Path mappings send /v1 and /v2 to different APIs or stages; see API versioning.

Network

Endpoints, VPC links and regions

Endpoint types

TypePathUse
RegionalStraight to the regionDefault; clients nearby, or your own CloudFront in front
Edge-optimized (REST)Through AWS-managed CloudFront locationsClients far apart. It shortens connections; it is not a cache
Private (REST)Interface endpoint in your VPCInternal APIs

A VPC link lets the gateway call services that have no public address. HTTP APIs can target an ALB, an NLB or Cloud Map. REST APIs now support ALB and NLB through VPC links V2; older REST links reach an NLB only. A V2 link with no traffic for 60 days becomes inactive, and waking it takes minutes.

Two regions behind one name

Users resolve a name in Route 53, which sends them to the nearest of two regions. Each region has its own gateway, functions and table replica.
API Gateway is regional. You deploy twice, route with Route 53 latency or failover records, and replicate the data.

Use Regional endpoints with the same custom domain name in both regions, a health check that tests the whole path, and one API definition in code so that they stay alike. With DynamoDB global tables, plan for conflicting writes.

Numbers

Limits that shape a design

Default quotas, November 2026

LimitREST APIHTTP APIWebSocket API
Payload10 MB10 MB128 KB message, 32 KB frame
Integration timeout29 s; raise on request if Regional or private30 s, fixed29 s
Rate per account and region10,000 a second, bucket 5,000Shared with the othersShared with the others
Connections--2 hours at most, 10 minutes idle
Routes or resources300300300
Stages101010

Streaming. A REST API with a proxy integration can stream a response for up to 15 minutes, beyond 10 MB, with the part above 10 MB limited to 2 MB a second. Caching and VTL then do not work. Uploads go to storage with a presigned URL; see Amazon S3 and file upload APIs.

Steady traffic in requests a month

200 reqs×86400 s×30=518,400,000≈518 million a month200\,\tfrac{\text{req}}{\text{s}} \times 86400\,\text{s} \times 30 = 518{,}400{,}000 \approx 518\ \text{million a month}
Multiply by the price per million of each API type, and compare with a load balancer's hourly and usage price. At steady high traffic the balancer is often cheaper.

Run it

Operations

  • Metrics

    Count, 4XXError, 5XXError, Latency and IntegrationLatency. The difference of the last two is the gateway's own share.

  • Access logs

    Switch them on per stage with request ID, route, status and integration error.

  • Tracing

    X-Ray for REST APIs. Pass the request ID on to your services.

  • Configuration as code

    OpenAPI, SAM, CDK or Terraform, and a deployment per release.

Retries. A 504 does not mean that nothing happened: the function may still finish. Clients should retry with backoff and an idempotency key.

Decide

When to choose it, and when not

Choose it when

  • You need auth, throttling and analytics without servers
  • Backends are Lambda functions
  • Each customer needs a rate and a quota
  • You must reshape requests without touching the backend
  • A mobile or web app needs its own backend (BFF)
  • AWS services should be reachable as an API
  • You need WebSockets without managing connections

Look elsewhere when

  • Every millisecond counts between internal services: gRPC or an ALB
  • Payloads are above 10 MB
  • Calls run longer than the timeout: queue, Step Functions
  • You only need to spread load: ALB or NLB
  • Traffic is very high and steady, and cost decides
  • The protocol is not HTTP or WebSocket
  • You need your own plugins in the proxy: Kong, Envoy

Neighbours

ProductAlikeDifferentChoose it for
Application Load BalancerHTTP, path routing, WebSocket, Lambda targetsHourly and capacity price, gRPC, no usage plans; signs users in through Cognito or OIDCHigh steady traffic
Kong GatewayAuth, limits, several backendsSelf-hosted or their cloud, own plugins, any cloudControl, several clouds
ApigeeManaged API platformMonetization and deep analytics, Google CloudAPI programmes of large companies
AWS AppSyncManaged, serverlessGraphQL and subscriptionsGraphQL, live data

Strengths

  • Nothing to run
  • Many API features in one place
  • Direct use of Lambda and AWS services
  • IAM, JWT, WAF, mutual TLS
  • Logs, metrics and traces

Costs

  • Fixed size and time limits
  • An extra hop on every call: measure it
  • Price per call at high traffic
  • No code of your own inside the proxy
  • Cold starts of an authorizer add to the first call

Summary

The whole topic in one minute.

API Gateway gives an API its front door: addresses, TLS, caller checks, throttling, validation, transformation, caching and logs, then one call to the integration. REST APIs have the full set; HTTP APIs the smaller, cheaper one; WebSocket APIs keep connections.

Design around its numbers: 10 MB, about 30 seconds, 10,000 requests a second per account and region by default. Send big files straight to storage, turn long work into jobs, treat throttles as targets rather than guarantees, and redeploy after a change.

  • REST for features, HTTP for simple and cheap, WebSocket for push.
  • Route, check, count, validate, cache, integrate, answer.
  • 10 MB, about 30 seconds, 10,000 a second per account and region by default.
  • Throttles are best effort; API keys are not authentication.
  • REST changes need a deployment; cached policies must cover all methods.

Sources