15.6
Amazon API Gateway
API types and endpoint types, integrations, security, throttling and caching, and API Gateway vs ALB.
24 min Reading + animations
Tip: tap or hover any dotted-underlined term to see what it means.
By the end of this lesson you will be able to
- Explain what Amazon API Gateway does as the front door of a serverless API (client → API Gateway → Lambda → DynamoDB), and list what it takes off your hands: routing, stages, security, API keys and usage plans, throttling, validation, transformation, caching, OpenAPI import, WebSocket.
- Choose between the three API types, REST, HTTP and WebSocket, from their features and prices.
- Connect an API to a Lambda function (proxy or custom), an HTTP backend, an AWS service such as Kinesis Data Streams, or a mock, and fix the missing permission behind a 500.
- Choose an endpoint type, edge-optimized, Regional or private, and put a custom domain on it with the ACM certificate in the right Region.
- Protect an API with IAM (SigV4), Cognito user pools, Lambda authorizers, resource policies and AWS WAF, and tell 401 from 403.
- Use the limits that shape designs (29-second integration timeout, 10 MB payload, 10,000 requests per second per account, cache TTL 300 s up to 3,600 s) and choose between API Gateway, an ALB and a Lambda function URL.
#Why an API needs a front door
A mobile app, a website or a partner’s server never talks to your database directly. It calls an API: a set of HTTPS addresses such as GET /products/42 or POST /orders. Something has to receive those calls, check who is calling, stop floods, send each call to the right code and return the answer. On a server-based design that is your web server plus a pile of middleware you write and patch.
Amazon API Gateway is a fully managed service that does this job. The notes call it the front door between clients (mobile apps, websites) and your backend (Lambda, EC2, DynamoDB). It helps you create, publish, maintain, monitor and secure APIs, and you pay per call, with no servers and nothing to pay while nobody calls.
#A serverless API, end to end
The classic serverless API has four boxes: the client sends HTTPS requests to API Gateway, which forwards them (as a proxy) to a Lambda function, which does CRUD on a DynamoDB table. None of the four needs a server you manage, all four scale with traffic, and the bill drops to almost nothing at 4 a.m. The notes’ first exam trick: a question that says “serverless architecture” or “expose AWS Lambda as a RESTful API” wants API Gateway.
Lambda itself is lessons 15.1 and 15.2; DynamoDB is lesson 15.4. Here we follow the request through the front door, first when everything works, then the five common ways it fails.
A serverless API: one request, end to end
A Dhaka e-commerce shop’s product API: the browser calls API Gateway, which invokes a Lambda function, which reads DynamoDB. No server anywhere is yours to patch. Then the five ways the same request goes wrong.
Scenario
The normal flow with a Lambda proxy integration: CRUD on DynamoDB behind a REST API.
The browser calls the API’s HTTPS address. API Gateway owns the front door: TLS, the URL routes (resource /products/{id}, method GET), and the stage in the path (prod).
#What API Gateway does for you
Behind the one word “gateway” sit many features. These are the ones the exam and real projects use:
| Feature | What it gives you | Example |
|---|---|---|
| No infrastructure | With Lambda behind it, nothing to patch or scale | A startup API that costs a few dollars a month |
| Routes and methods | Resources and methods (REST) or routes (HTTP) map each path and verb to a backend | GET /products/{id} → function A, POST /orders → function B |
| Stages | Several deployed copies of the same API: dev, test, prod, each with its own URL and settings | https://abc123.execute-api.ap-southeast-1.amazonaws.com/prod |
| Versioning | Keep v1 running while clients move to v2 (separate stages, separate APIs or paths) | Old app versions still call /v1/orders |
| Security | IAM, Cognito, Lambda authorizers, resource policies, WAF, mutual TLS | Riders sign in with Cognito |
| API keys, usage plans, throttling | Identify each client, limit its rate and its monthly quota | A free and a paid plan for partners |
| Request validation and transformation | Reject bad input before the backend runs; reshape requests and responses with mapping templates | 400 for an order without a product ID |
| Caching | Keep responses for a TTL so repeated calls skip the backend | Delivery zones cached for 5 minutes |
| OpenAPI (Swagger) import and export | Define the whole API in one file; export it to generate client SDKs and documentation | The mobile team gets a generated Android SDK |
| WebSocket | Two-way, long-lived connections with server push | Live rider location |
| Monitoring | CloudWatch metrics (Count, Latency, IntegrationLatency, 4XXError, 5XXError, CacheHitCount), access and execution logs, X-Ray tracing | An alarm on 5XX errors |
#Stages and deployments
On a REST API, changing a method does nothing for clients until you deploy it to a stage. A deployment is a snapshot of the API; a stage points at one deployment and adds its own settings: throttling, caching, logging, WAF, and stage variables (key–value pairs, for example lambdaAlias=prod, so the prod stage calls the prod alias of the function and dev calls dev). A canary setting on a stage sends a small percentage of traffic to a new deployment before everyone gets it. HTTP APIs can also auto-deploy every change to a stage, which is handy for dev.
The notes: stages let you run several versions or environments (dev, test, prod) of the same API side by side. Combined with Lambda aliases (lesson 15.1), that is how you release a new version without breaking the app already in people’s phones.
#REST, HTTP or WebSocket API
API Gateway offers three API types. The exam mostly says “API Gateway” and means a REST API; real projects should choose deliberately.
| REST API | HTTP API | WebSocket API | |
|---|---|---|---|
| Talks | Request–response | Request–response | Two-way, long-lived connection, server push |
| Endpoint types | Edge-optimized (default), Regional, private | Regional only | Regional |
| Price (us-east-1, first tier) | About $3.50 per million requests | About $1.00 per million requests | About $1.00 per million messages + $0.25 per million connection minutes |
| API keys, usage plans, per-client throttling | Yes | No | No |
| Caching | Yes (0.5–237 GB, per hour) | No | No |
| Request validation, body transformation, mock integration | Yes | No (parameter mapping only) | Route selection and some mapping |
| AWS WAF, resource policies, private endpoint | Yes | No | WAF no |
| Authorizers | IAM, Cognito user pool, Lambda | IAM, JWT (Cognito or any OIDC issuer), Lambda | IAM, Lambda (on $connect) |
| Integration timeout | 50 ms – 29 s (Regional/private can ask for more) | Up to 30 s, fixed | 29 s |
| Extras | Canary deployments, X-Ray, execution logs, developer portal, response streaming | Automatic deployments, private integrations to Cloud Map, lower latency | $connect, $disconnect, $default routes; @connections callback |
The rule of thumb from the AWS documentation: choose REST when you need API keys, per-client throttling, request validation, WAF, caching or private endpoints; choose HTTP when you do not, because it is cheaper and faster.
#WebSocket APIs in one paragraph
A WebSocket API keeps a connection open between the client and API Gateway. The client sends JSON messages; a route selection expression such as $request.body.action sends each message to a route (sendMessage, updateLocation), plus the special routes $connect (authorize and store the connection ID, for example in DynamoDB), $disconnect (clean up) and $default. To push a message to a client, the backend calls the @connections callback URL with that client’s connection ID. A connection lasts at most 2 hours and closes after 10 minutes idle; a message can be up to 128 KB (in 32 KB frames). Chat apps, live dashboards, multiplayer games and the ride-sharing map that moves the rider’s icon all fit here.
#Integrations: what sits behind the door
An integration connects a route or method to a backend. The slides list three high-level kinds, and REST APIs add a fourth.
- Lambda function. The easy way to expose a REST API backed by Lambda.
- Lambda proxy (
AWS_PROXY): the whole request (path, query string, headers, body, caller identity) becomes the event; the function returnsstatusCode,headersand a stringbody. This is what almost everyone uses. - Lambda custom (non-proxy,
AWS): mapping templates (written in VTL) reshape the request into the event and the function’s result into the HTTP response. Older and more work, but the function stays unaware of HTTP.
- Lambda proxy (
- HTTP. Forward to any HTTP endpoint: an ALB in front of EC2 or containers, an internal API on premises, a partner’s URL. Why put API Gateway in front of something that already works? To add rate limiting, caching, authentication and API keys without touching it. A backend inside a VPC (a private ALB or NLB) is reached through a VPC link.
- AWS service. Call any AWS API directly, with no Lambda in between:
SendMessageto SQS, start a Step Functions workflow,PutRecordinto Kinesis Data Streams,PutIteminto DynamoDB. API Gateway signs the call with an IAM role you give it. Why? To get authentication, a public HTTPS address and rate control in front of the service, without code. HTTP APIs offer the same idea as ready-made “first-class” integrations for SQS, EventBridge, Kinesis Data Streams and Step Functions, among others. - Mock (REST only): API Gateway answers by itself with a fixed response. Useful while the backend is not ready, or for a CORS preflight.
The slides’ AWS service example is a clickstream pipeline: client → API Gateway → Kinesis Data Streams → Data Firehose → S3 (.json files). It ingests events at any rate with no function of yours running (lessons 13.5 and 13.6).
What sits behind API Gateway
Three kinds of backend: a Lambda function, any HTTP endpoint, or an AWS service API called directly. Plus a mock, and the most common misconfiguration.
Scenario
The usual way to expose Lambda as a REST API.
The client calls POST /orders. The route is mapped to a Lambda integration in proxy mode (AWS_PROXY).
#Endpoint types and custom domains
An API always lives in one Region. The endpoint type decides how clients reach it.
| Endpoint type | How clients reach it | Pick it when |
|---|---|---|
| Edge-optimized (REST default) | Requests enter AWS at the nearest CloudFront edge location and ride the AWS backbone to the Region | Clients are spread around the world |
| Regional | Straight to the Region’s endpoint | Clients are in or near the same Region; or you want your own CloudFront distribution in front, with full control of caching and behaviours |
| Private (REST only) | Only from a VPC, through an interface VPC endpoint for execute-api (an ENI with a private IP, AWS PrivateLink) | Internal APIs that must never be reachable from the internet; access is defined by a resource policy |
Two clarifications the slides leave out. First, edge-optimized does not cache your responses at the edge; it only shortens the network path (API caching is a separate stage setting). Second, edge-optimized uses a CloudFront distribution that AWS manages and you cannot configure; if you want WAF on CloudFront, geo restriction or your own cache rules, use a Regional endpoint behind your own distribution. Interface endpoints themselves are lesson 22.2.
#Custom domain names and the ACM certificate
Nobody wants to print abc123.execute-api.ap-southeast-1.amazonaws.com on a partner contract. A custom domain name such as api.shop.example points at one or more APIs and stages (through API mappings, for example /v1 → API A stage prod). HTTPS for it needs a certificate from AWS Certificate Manager (lesson 21.4), and the Region of that certificate is a favourite exam detail:
- Edge-optimized custom domain → the certificate must be in us-east-1 (N. Virginia), because the CloudFront distribution behind it is global and CloudFront reads certificates from there.
- Regional custom domain → the certificate must be in the same Region as the API.
- Then create a Route 53 alias (A or AAAA) record, or a CNAME, that points the name at the domain’s target (a CloudFront name for edge-optimized, a Regional
d-…execute-apiname for Regional). Alias vs CNAME is lesson 8.2.
Since late 2024, private REST APIs can have custom domain names too, shared to VPC endpoints through an access association. In 2025 API Gateway also added dual-stack (IPv4 and IPv6) endpoints (March, for REST, HTTP and WebSocket APIs and custom domains) and routing rules on custom domains (June, REST APIs only: send traffic to an API by header or path, for example for a gradual v1 → v2 move). These are side notes; the exam asks about the certificate Region.
Edge-optimized, Regional or private
The API always lives in one Region. The endpoint type decides how clients reach it: through CloudFront edge locations, straight to the Region, or only from inside a VPC.
Scenario
The default for REST APIs: for clients all over the world.
Bangladeshi workers in the Gulf and in Europe use a remittance app whose API is in Singapore. With an edge-optimized endpoint their requests enter AWS at the nearest CloudFront edge location.
#Security: who may call the API
The slides list three ways to authenticate users; the full menu is a little longer.
| Mechanism | Who it suits | How it works |
|---|---|---|
IAM authorization (AWS_IAM) | Internal callers that already have AWS credentials: EC2, ECS tasks, Lambda, other accounts | The caller signs each request with SigV4; API Gateway checks the signature and the caller’s IAM policy for execute-api:Invoke. Cross-account needs the API’s resource policy too |
| Amazon Cognito user pool | External users: mobile and web app users, millions of them | Users sign in to Cognito and get JWT tokens; a Cognito authorizer (REST) or JWT authorizer (HTTP API) verifies the token’s signature and expiry with no code of yours (lesson 15.7) |
| Lambda authorizer (formerly “custom authorizer”) | Your own logic: a third-party identity provider, a bearer token from a partner, an API key stored in your database, a header check | API Gateway calls your function with the token (token type) or the headers and context (request type); it returns an IAM policy (Allow or Deny) and a principal ID. The result is cached for a TTL (default 300 s, up to 3,600 s) |
| Resource policy (REST) | Restrict by source: account, IP range, VPC, VPC endpoint | A JSON policy on the API, evaluated with the other checks; required for private APIs and for cross-account IAM access |
| AWS WAF (REST) | Attacks: SQL injection, cross-site scripting, bad bots, per-IP rate limits | A web ACL on the stage, evaluated before everything else (chapter 21, lesson 21.6) |
| Mutual TLS | Partners and devices with client certificates | The client must present a certificate trusted by your truststore in S3 (custom domain required) |
Read the status codes right. 401 Unauthorized means “who are you?”: no token, or an invalid or expired one. 403 Forbidden means “I know who you are, and no”: a Lambda authorizer returned Deny, IAM did not allow execute-api:Invoke, a resource policy or WAF blocked the source. Both are returned before your backend runs, so they cost you no Lambda time.
Who may call the API?
A ride-sharing app’s API checks every caller before the backend runs: a Cognito user pool for riders, a Lambda authorizer for a partner’s own tokens, IAM for internal services, plus resource policies and WAF.
Scenario
Riders log in; API Gateway checks the token by itself.
A rider signs in to the app. Cognito user pools hold millions of external users: sign-up, passwords, MFA, social login (lesson 15.7).
#Throttling, usage plans and caching
#Throttling: four layers
Throttling protects your backend and your bill from floods. API Gateway uses a token bucket: a steady rate (requests per second) plus a burst (the bucket size, how many can arrive at once). Over the limit, callers get 429 Too Many Requests and should retry with exponential backoff. Limits apply in this order, and the tightest wins:
- Per client (REST only): the usage plan limit for that client’s API key, optionally per method.
- Per method: a stage’s method-level limits, for example
POST /ordersat 200 per second. - Per stage: the default for every method in the stage.
- Per account and Region: by default 10,000 requests per second with a burst bucket of 5,000, shared by all REST, HTTP and WebSocket APIs in the account in that Region (some newer Regions start at 2,500). You can request an increase in Service Quotas.
The notes put the default at 10,000 per second; the detail that bites in production is the word shared: one API’s spike can make every other API in the account throttle. Set stage and method limits so no single API can eat the whole account limit.
#Usage plans and API keys
A usage plan (REST only) says how much a client may use: a throttle (rate and burst) and a quota (requests per day, week or month). A client gets an API key, the key is attached to a plan, and the plan is attached to API stages. Methods that need a key have API key required turned on. Over the rate, the client gets 429; over the quota, 429 with “Limit Exceeded” until the period resets. The notes’ exam trick: “usage plans”, “API keys” or “throttling third-party developers” mean API Gateway (and specifically a REST API).
#Caching responses
The notes’ second exam trick: “improve API performance and reduce backend load” → enable API caching. A REST API stage can have a cache:
- The TTL is 300 seconds (5 minutes) by default, configurable from 0 (no caching) to 3,600 seconds.
- The cache key is the method and path plus the parameters you choose (query strings, headers). Choose them carefully: forgetting a parameter serves one user’s answer to another.
- The cache costs money per hour by size, from 0.5 GB to 237 GB, whether it is used or not; a single cached response can be up to 1 MB.
- You can flush the whole stage cache, and you can override caching per method. A client can skip the cache for one request with
Cache-Control: max-age=0if it has the IAM permissionexecute-api:InvalidateCache; require that permission, or anyone can bypass your cache. - HTTP and WebSocket APIs have no built-in cache; put CloudFront in front if you need one.
Caching trades freshness for speed. A five-minute TTL on prices during a flash sale can show the old price; pick the TTL from how stale the data may be, and flush when you must.
Throttling, usage plans and the cache
A Pathao-style delivery platform sells its tracking API to other companies: a free plan and a paid plan, each identified by an API key. Then the account-wide limit, and the cache that keeps Lambda quiet.
Scenario
Free: 10 requests a second, 10,000 a month. Paid: 500 a second, 5 million a month.
The paid partner sends 400 requests a second with its API key in the x-api-key header. Its usage plan allows 500 a second.
#The limits that shape designs
| Limit | Value | What it means for design |
|---|---|---|
| Integration timeout, REST | 50 ms – 29 s by default; Regional and private REST APIs can request more (June 2024), possibly lowering the account’s throttle quota; edge-optimized cannot | Long work does not belong in a synchronous call: return 202 and process in the background (SQS, Step Functions) |
| Integration timeout, HTTP API | Up to 30 s, cannot be raised | Same |
| Payload size (REST and HTTP) | 10 MB | Upload files directly to S3 with a presigned URL (lesson 10.12) |
| Lambda synchronous payload | 6 MB request and response | Even under 10 MB, a Lambda backend fails above 6 MB |
| Account throttle | 10,000 rps, burst 5,000, per Region, shared | Stage/method limits, quota increase, caching |
| Cache TTL | Default 300 s, 0 – 3,600 s | |
| Lambda authorizer cache | Default 300 s, up to 3,600 s | A revoked token may pass until its cached policy expires |
| WebSocket connection | 2 hours maximum, 10 minutes idle | Clients must reconnect |
The 29-second timeout is the one exam questions love. The trap behind it: when API Gateway gives up and returns 504, the Lambda function keeps running to its own timeout (up to 15 minutes) and is billed, but its answer goes nowhere. Lambda’s timeout should be shorter than the API’s.
#Follow one request through the checks
Put it all together. Choose the API type, the token, the client’s traffic, the cache, how long the backend takes and the body size, then press the button and see which check stops the request, with what status code, after how long, and whether you paid for a Lambda run.
Follow one request through API Gateway
The delivery platform’s tracking API, protected by a Cognito authorizer, sold through usage plans, backed by Lambda. Set up the request, send it, and see which check stops it and why.
API type
Token
Client’s traffic
Cache
Backend time
Request body
Press “Send request” to follow it.
#API Gateway vs Application Load Balancer
Both receive HTTP traffic from clients and pass it to a backend. The notes’ comparison, with the corrections the inventory found:
| API Gateway | Application Load Balancer | |
|---|---|---|
| Main job | Manage and protect APIs, especially serverless ones (Lambda), but also HTTP backends and AWS services | Spread traffic across EC2 instances, ECS containers, IP addresses, and also Lambda functions (lesson 6.3) |
| Payment | Per request (plus cache hours, data out); nothing when idle | Per hour plus LCUs (load balancer capacity units); you pay while it runs, even at night |
| API management | Rate limiting, throttling, API keys, usage plans, request validation, transformation | None of these; it is a load balancer. A WAF rate-based rule can limit per IP |
| Caching | Built in (REST) | None |
| Authentication | IAM (SigV4), Cognito, Lambda authorizer, resource policies | Cognito and any OIDC identity provider, on HTTPS listeners |
| Timeouts and size | 29 s (30 s HTTP API), 10 MB | Idle timeout default 60 s, up to 4,000 s; 1 MB request and response for Lambda targets |
| WebSocket | WebSocket API (serverless) | Passes WebSocket connections through to your servers |
| Scale | Fully managed, 10,000 rps account default | Scales automatically with LCUs, millions of requests a second |
Which front door fits?
Pick a scenario, guess, then read why. Listen for the keywords: plans and keys, cheapest, push, servers or containers, private, one function, WAF and cache.
1. Choose a scenario(Right first time: 0/7)
A delivery platform opens its tracking API to other companies: a free plan with 10,000 calls a month and a paid plan with higher limits. Each company gets its own key, and nobody may starve the others.
2. Your answer
#What goes wrong
| Symptom | Likely cause | Fix |
|---|---|---|
| 504 after 29 seconds; the Lambda logs show it finished later | Work longer than the integration timeout | Make it asynchronous (202 + SQS or Step Functions + polling or WebSocket); speed it up; on Regional/private REST, request a higher timeout |
| 502 Bad Gateway “Malformed Lambda proxy response” | The function returned something other than statusCode, headers, string body, or threw an error | Return the proxy format; JSON.stringify the body; read the function’s logs |
| 500, log says “Invalid permissions on Lambda function” | No resource-based policy for apigateway.amazonaws.com | aws lambda add-permission with the API’s source ARN |
| 413 Request Entity Too Large | Body over 10 MB (or over 6 MB for Lambda) | Presigned S3 upload |
| 429 for one client only | Its usage plan rate or quota | Backoff and retry; upgrade the plan |
| 429 for everyone, across APIs | Account limit (10,000 rps per Region) reached by one API’s spike | Stage and method throttles; quota increase; caching |
| 401 | Missing, malformed or expired token | Send the Authorization header; refresh tokens |
| 403 “Missing Authentication Token” on a correct-looking URL | Wrong path or stage, or a method that does not exist | Check the stage name in the URL and the resource path |
| 403 from a valid user | Lambda authorizer Deny, IAM policy, resource policy or WAF | Check which layer denied (execution logs, WAF logs) |
| Browser console: CORS error, but curl works | No Access-Control-Allow-Origin in the preflight or in the proxy response | Enable CORS; in Lambda proxy, add the header in the function too |
| Changes in the console have no effect | REST API not redeployed to the stage | Deploy to the stage (or auto-deploy on HTTP APIs) |
| Users see old data for minutes | API cache TTL | Lower the TTL for that method, flush the cache, choose cache keys carefully |
| A revoked partner still gets through | Lambda authorizer result cached | Shorter authorizer TTL for sensitive APIs |
| Custom domain cannot find the certificate | Edge-optimized domain with the certificate outside us-east-1 | Request or import it in us-east-1 |
| Private API unreachable from a VPC | No interface endpoint for execute-api, or the resource policy does not allow that endpoint | Create the endpoint, allow aws:SourceVpce |
#API Gateway in system design
- Default serverless front door: client → API Gateway → Lambda → DynamoDB, with Cognito for users (the to-do app and blog designs in lesson 15.8).
- HTTP API by default, REST API when you need keys, plans, caching, validation, WAF or a private endpoint. Many companies run both: a cheap HTTP API for their own app and a REST API for partners.
- Keep synchronous calls short: under a few seconds. Anything longer goes through a queue or a workflow, and the client polls or listens on a WebSocket.
- Direct service integrations (SQS, Kinesis, Step Functions, DynamoDB) remove “glue” Lambda functions, which saves money, latency and concurrency.
- Protect in layers: WAF at the edge, authorizers for identity, usage plans per client, stage and method throttles, reserved concurrency on the functions behind (lesson 15.2), so one flood cannot drain everything.
- Cache what many people ask for, and only that; pick keys and TTLs per method.
- Stages per environment, Lambda aliases per stage, canary releases for risky changes; define everything in OpenAPI or infrastructure as code.
- Observe: alarms on
5XXError,LatencyandIntegrationLatency; access logs; X-Ray for slow paths.
#Try it yourself
An HTTP API in front of a function, then a REST API with a usage plan and a cache, in ap-southeast-1, account 111122223333. Outputs are shortened.
# 1. Quick-create an HTTP API with a Lambda proxy integration (one route, $default stage, auto-deploy)
aws apigatewayv2 create-api --name shop-http-example --protocol-type HTTP \
--target arn:aws:lambda:ap-southeast-1:111122223333:function:products-example
# { "ApiId": "a1b2c3d4e5", "ApiEndpoint": "https://a1b2c3d4e5.execute-api.ap-southeast-1.amazonaws.com", ... }
# Quick create adds the invoke permission; with a manual setup you must add it yourself:
aws lambda add-permission --function-name products-example \
--statement-id apigw-invoke --action lambda:InvokeFunction \
--principal apigateway.amazonaws.com \
--source-arn "arn:aws:execute-api:ap-southeast-1:111122223333:a1b2c3d4e5/*"
curl -s https://a1b2c3d4e5.execute-api.ap-southeast-1.amazonaws.com/products/42
# {"id":"42","name":"Panjabi","price":2450}
# 2. A REST API (Regional) for partners: create a usage plan with throttle and quota
aws apigateway create-usage-plan --name free-example \
--throttle burstLimit=20,rateLimit=10 --quota limit=10000,period=MONTH \
--api-stages apiId=x9y8z7w6v5,stage=prod
# { "id": "pl4n1d", "name": "free-example", "throttle": {"burstLimit": 20, "rateLimit": 10.0}, ... }
aws apigateway create-api-key --name shop-a-example --enabled
# { "id": "k3y1d", "value": "Ab12Cd34Ef56Gh78Ij90Kl12Mn34Op56Qr78St90", ... }
aws apigateway create-usage-plan-key --usage-plan-id pl4n1d --key-id k3y1d --key-type API_KEY
# 40 calls in one second from the free key: some come back 429
for i in $(seq 40); do curl -s -o /dev/null -w "%{http_code} " \
-H "x-api-key: Ab12Cd34Ef56Gh78Ij90Kl12Mn34Op56Qr78St90" \
https://x9y8z7w6v5.execute-api.ap-southeast-1.amazonaws.com/prod/track/7781 & done; wait
# 200 200 200 ... 429 429 200 429 ...
# 3. Turn on a 0.5 GB cache on the prod stage, TTL 600 s for all methods
aws apigateway update-stage --rest-api-id x9y8z7w6v5 --stage-name prod --patch-operations \
op=replace,path=/cacheClusterEnabled,value=true \
op=replace,path=/cacheClusterSize,value=0.5 \
op=replace,path=/*/*/caching/enabled,value=true \
op=replace,path=/*/*/caching/ttlInSeconds,value=600
# Data changed? Flush the stage cache
aws apigateway flush-stage-cache --rest-api-id x9y8z7w6v5 --stage-name prod
# 4. Check the account throttle limits for the Region
aws apigateway get-account --query throttleSettings
# { "burstLimit": 5000, "rateLimit": 10000.0 }
Watch the Count, 4XXError, 5XXError, CacheHitCount and CacheMissCount metrics in CloudWatch while you run the loop. Delete the cache when you are done: it is billed every hour it exists.
#Summary
Key takeaways
- API Gateway is the managed front door of an API: routing, stages, security, API keys and usage plans, throttling, validation, transformation, caching, OpenAPI import, SDK generation, WebSocket, pay per request. Classic serverless API: client → API Gateway → Lambda → DynamoDB. “Expose Lambda as a RESTful API” → API Gateway.
- Three API types: REST (all features: keys, usage plans, cache, validation, WAF, private endpoints; about $3.50 per million), HTTP (cheaper at about $1.00 per million, faster, JWT authorizer, Regional only, 30 s), WebSocket (two-way, server push,
$connect/$disconnect,@connections). - Integrations: Lambda proxy (function returns statusCode, headers, body) or custom with mapping templates; HTTP backends (ALB, on premises, VPC link) to add rate limiting, caching, auth and keys; AWS service APIs directly (Kinesis Data Streams → Firehose → S3, SQS, Step Functions) with an IAM role; mock. Lambda needs a resource policy for
apigateway.amazonaws.com. - Endpoints: edge-optimized (REST default, via CloudFront edges, still one Region, no edge caching), Regional (same-Region clients, or your own CloudFront), private (interface VPC endpoint + resource policy). Custom domain certificate in us-east-1 for edge-optimized, in the API’s Region for Regional; Route 53 alias or CNAME.
- Security: IAM/SigV4 for internal callers, Cognito user pools for external users (JWT checked by API Gateway), Lambda authorizer for your own logic (returns an IAM policy, cached 300 s by default), resource policies and WAF by source. 401 = who are you; 403 = not allowed. API keys are not authentication.
- Throttling: token bucket, 10,000 rps + 5,000 burst per account per Region, shared by all APIs; stage, method and per-client usage plan limits; over limit → 429. Throttling is not DDoS protection: use WAF and Shield.
- Caching (REST only): TTL 300 s default, 0–3,600 s, 0.5–237 GB billed hourly, per-stage, flushable; “improve performance and reduce backend load” → enable caching.
- Limits: 29 s integration timeout (504, the function keeps running; raise only on Regional/private REST; streaming up to 15 min since 2025), 10 MB payload (6 MB for Lambda), so long jobs go async and big files go to S3 via presigned URLs. CORS errors → enable CORS.
- API Gateway vs ALB: per request + API management + cache + IAM/Cognito/Lambda authorizers vs hourly + LCUs, load balancing for EC2/containers (and Lambda), Cognito/OIDC on HTTPS listeners. “Monolith on EC2/containers” → ALB; “usage plans, API keys, throttle third-party developers” → API Gateway; one function, one URL → function URL.
Answer on your own first, then read the explanation, even when you got it right.
Self-checkQuestion
A company wants to expose a set of AWS Lambda functions as a RESTful API for its mobile app, with no servers to manage. Which service should sit in front of the functions?
Self-checkQuestion
What is the default TTL of an API Gateway REST API cache, and what range can you set?
Self-checkQuestion
A single-page app on https://shop.example calls an API on https://api.shop.example. The API works with curl, but the browser console shows an error about the same-origin policy and the call is blocked. What should the developer do?
Self-checkQuestion
Which feature is available on a REST API but NOT on an HTTP API?
Self-checkQuestion
A startup’s React app calls 20 Lambda-backed routes. Users sign in with Amazon Cognito. It needs no API keys, caching or WAF, and wants the lowest cost and latency. Which option fits best?
Self-checkQuestion
A ride-sharing app must push the driver’s position to the passenger’s phone every few seconds over a long-lived two-way connection, without servers to manage. What should the architect use?
Self-checkQuestion
A news app sends clickstream events through API Gateway. The team wants them in Kinesis Data Streams and then as JSON files in S3, with no Lambda function to maintain. Which design fits?
Self-checkQuestion
An API with a Lambda proxy integration returns 502 Bad Gateway. CloudWatch Logs show the function ran and returned the product object. What is the most likely cause?
Self-checkQuestion
A report endpoint behind an API Gateway Regional REST API calls a Lambda function that runs for 45 seconds. Clients receive 504 errors. Which solution is the most appropriate for the exam?
Self-checkQuestion
An API Gateway integration timed out after 29 seconds and the client received 504. What happened to the Lambda function?
Self-checkQuestion
A seller uploads 25 MB product videos through the company’s API, and the uploads fail with 413. What is the recommended design?
Self-checkQuestion
Which two statements about API Gateway integrations are correct?
Choose 2
Self-checkQuestion
An API is created with the AWS CLI and integrated with a Lambda function. Every call returns 500, and the execution log says “Invalid permissions on Lambda function”. What is missing?
Self-checkQuestion
A remittance app has users in the Middle East, Europe and Asia; its REST API runs in ap-southeast-1. The team wants the network path improved for far-away users with the least effort. Which endpoint type fits?
Self-checkQuestion
A company creates the custom domain api.remit.example for its edge-optimized REST API in ap-southeast-1. Where must the ACM certificate be?
Self-checkQuestion
Which two are true for a private REST API?
Choose 2
Self-checkQuestion
A global API needs AWS WAF rules at CloudFront, geo restriction and its own cache behaviours, managed by the team. Which setup fits?
Self-checkQuestion
Internal microservices running on ECS with task roles must call an internal API. The company wants no tokens or passwords to manage. Which authorization should the API use?
Self-checkQuestion
A hotel partner calls the API with bearer tokens issued by the partner’s own identity system, which is neither IAM nor Cognito. How should the API verify them?
Self-checkQuestion
A partner’s contract ended and its token was revoked one minute ago, but its calls still succeed through the Lambda authorizer for a few more minutes. Why?
Self-checkQuestion
Which two responses does API Gateway return without running the backend at all?
Choose 2
Self-checkQuestion
A company sells its tracking API to other companies: a free tier limited to 10 requests per second and 10,000 requests a month, and a paid tier with higher limits. Which API Gateway feature implements this?
Self-checkQuestion
On Eid evening one API in an account receives 14,000 requests per second. A completely different API in the same account and Region starts returning 429 as well. Why?
Self-checkQuestion
An API’s steady limit is 10,000 requests per second with a token bucket of 5,000 for bursts. Traffic jumps to 14,000 requests per second and stays there. Roughly how long does the bucket absorb the excess, and what happens next?
Self-checkQuestion
A REST API costs too much because its Lambda backend reads the same list of delivery zones for every request. The data changes about once a day. What is the simplest way to improve performance and reduce backend load?
Self-checkQuestion
A team enables a 0.5 GB API cache on the prod stage of a REST API. The cache costs about $0.02 per hour in us-east-1. Roughly what does it cost in a 730-hour month, and when?
Self-checkQuestion
An API receives 50 million requests a month. Roughly how much do the requests cost on a REST API compared with an HTTP API, using first-tier prices of $3.50 and $1.00 per million?
Self-checkQuestion
A company runs a monolithic Java application on 12 EC2 instances in an Auto Scaling group with steady traffic all day, and some admin requests take two minutes. It needs HTTPS and health checks. Which front end fits best?
Self-checkQuestion
Which statement in the notes’ API Gateway vs ALB comparison needs correcting?
Self-checkQuestion
Which statement about throttling in API Gateway is NOT true?
Self-checkQuestion
A payment provider must call one Lambda function whenever a payment succeeds: one HTTPS URL, no routing, no API keys, no caching, and the least setup and cost. Which option fits best?
Self-checkQuestion
Which two are features of API Gateway listed in this lesson that an Application Load Balancer does NOT offer?
Choose 2