Amazon API Gateway

Expose Lambda, HTTP backends, or any AWS API as a managed REST/HTTP/WebSocket endpoint. Adds auth, throttling, caching, and stages for free.

Expose Lambda, HTTP backend, hay bất kỳ AWS API nào thành REST/HTTP/WebSocket managed. Đi kèm auth, throttling, cache, stage mà không phải code.

Reach for itNên dùng

  • Public API in front of LambdaAPI công khai trước Lambda
  • Need throttling, quotas, per-key metering (usage plans)Cần throttling, quota, đo theo API key (usage plan)
  • Managed WebSockets to a stateful backendWebSocket managed cho backend stateful

Skip itBỏ qua

  • Long-lived streams / SSE — use ALB or directStream dài / SSE — dùng ALB hoặc direct
  • In-VPC service-to-service — go through ALB / private DNSService-to-service trong VPC — qua ALB / private DNS
  • Requests >10 MB — S3 presigned URL · long jobs — async + polling / Step FunctionsRequest >10 MB — S3 presigned URL · job dài — async + polling / Step Functions

Endpoint typesLoại endpoint

Edge-Optimized Regional Private
Where clients liveClient ở đâu GlobalToàn cầu Same regionCùng region Inside a VPC onlyChỉ trong VPC
CloudFrontCloudFront AutoTự động DIYTự thêm ❌
Cert locationNơi đặt cert us-east-1 Same region as APICùng region API —
Timeout > 29 sTimeout > 29 s ❌ Yes — Service QuotasĐược — Service Quotas Yes — Service QuotasĐược — Service Quotas
REST vs HTTP APIREST vs HTTP API HTTP APIs are ~70% cheaper, lower latency, with a native JWT/OIDC authorizer — but no usage plans / API keys, no caching, no request validation, no WAF, timeout fixed at 30 s. Exam tell: "cheap JWT proxy to Lambda" → HTTP API · "per-customer keys, quotas, caching" → REST API. HTTP API rẻ hơn ~70%, latency thấp hơn, có sẵn JWT/OIDC authorizer — nhưng không có usage plan / API key, không cache, không request validation, không WAF, timeout cố định 30 s. Dấu hiệu đề thi: "proxy JWT rẻ cho Lambda" → HTTP API · "key theo customer, quota, cache" → REST API.

Auth optionsChọn auth

AWS_IAM SigV4 · service-to-service in AWSSigV4 · service-to-service trong AWS
Lambda Authorizer Custom JWT / OAuth / SAMLJWT / OAuth / SAML tuỳ chỉnh
Cognito User Pools Managed JWT · out-of-the-box verifyJWT managed · verify tự động
Resource policy Deny by account / IP / VPC endpointDeny theo account / IP / VPC endpoint

Stages, caching, throttlingStage, cache, throttle

A stage = a deployment target. Cache and throttling settings live on the stage, method-level overrides allowed. Stage = target deploy. Cache và throttle gắn trên stage, có thể override ở method.

  • Deployment history is kept — rollback a stage to a previous deployment.Lịch sử deploy được giữ — có thể rollback stage về deploy cũ.
  • Cache is per-stage. Flip on for read-heavy endpoints, size the capacity (0.5 GB → 237 GB).Cache theo stage. Bật cho endpoint đọc nhiều, chọn size (0.5 GB → 237 GB).
  • Client can bypass cache with Cache-Control: max-age=0 if IAM allows.Client bỏ qua cache bằng Cache-Control: max-age=0 nếu IAM cho phép.
  • Max cached response = 1 MB per item. Cache is billed per hour while enabled — not free tier.Response cache tối đa 1 MB mỗi item. Cache tính tiền theo giờ khi bật — không thuộc free tier.
  • Canary release on a stage — route a % of traffic to a new deployment, promote or roll back. Blue/green for APIs.Canary release trên stage — dẫn % traffic sang deploy mới, promote hoặc rollback. Blue/green cho API.

Usage plans & API keysUsage plan & API key

API keys identify a customer; the usage plan meters them (throttle + quota). Burst = reserve tokens for spikes. API key nhận diện customer; usage plan đo lường (throttle + quota). Burst = token dự trữ cho spike.

  • 429 Too Many Requests = account-wide throttle across the region — default 10,000 rps, burst 5,000 (soft, shared by all APIs in the region).429 Too Many Requests = throttle toàn account trong region — mặc định 10,000 rps, burst 5,000 (soft, chia chung mọi API trong region).
  • Client must implement retry with backoff — API GW doesn't queue.Client phải retry có backoff — API GW không queue.

Error codes cheat sheetBảng code lỗi

Code MeaningÝ nghĩa Likely causeNguyên nhân hay gặp
400Bad RequestMalformed requestRequest lỗi format
403Access DeniedWAF, IAM, resource policyWAF, IAM, resource policy
429ThrottledUsage plan or account quotaUsage plan hoặc quota account
502Bad GatewayLambda proxy returned wrong shapeLambda proxy trả sai shape
503Service UnavailableBackend down / degradedBackend chết / suy giảm
504Gateway TimeoutBackend exceeded integration timeout (default 29 s)Backend vượt integration timeout (mặc định 29 giây)

Private APIsAPI riêng tư

  • Reached only via a VPC Interface Endpoint. One endpoint can serve multiple private APIs.Chỉ vào được qua VPC Interface Endpoint. Một endpoint có thể phục vụ nhiều private API.
  • Resource policy uses aws:SourceVpc and aws:SourceVpce to allow specific VPCs / endpoints, even across accounts.Resource policy dùng aws:SourceVpc và aws:SourceVpce để cho phép VPC / endpoint cụ thể, kể cả khác account.

Integrations — what the backend can beIntegration — backend có thể là gì

API Gateway has no "targets"; a backend is an integration. The trap is that REST and HTTP APIs have very different reach into AWS services directly — and the one everyone assumes is present, DynamoDB, is missing from HTTP API. API Gateway không có "target"; backend gọi là integration. Bẫy nằm ở chỗ REST API và HTTP API với tới các AWS service trực tiếp theo cách rất khác nhau — và cái ai cũng tưởng có, DynamoDB, lại vắng mặt ở HTTP API.

Lambda Proxy or custom integration. The default shape for serverless APIs.Proxy hoặc custom integration. Hình dạng mặc định cho API serverless.
AWS service, directlyAWS service, trực tiếp REST API: broad AWS integration — map a request onto DynamoDB PutItem, SQS SendMessage, Kinesis, Step Functions, EventBridge… no Lambda in the path.
HTTP API: only a fixed list of integration subtypes.
REST API: AWS integration rộng — map một request thành DynamoDB PutItem, SQS SendMessage, Kinesis, Step Functions, EventBridge… không cần Lambda ở giữa.
HTTP API: chỉ một danh sách integration subtype cố định.
Public HTTP endpointHTTP endpoint public Any reachable URL: a public ALB, an on-prem server, a third-party API.Bất kỳ URL nào tới được: ALB public, server on-prem, API bên thứ ba.
Private, via VPC LinkPrivate, qua VPC Link Reach a private ALB/NLB (or Cloud Map service) without exposing it to the internet. This is how API Gateway fronts EC2/ECS — never by instance ID.Với tới ALB/NLB private (hoặc service trong Cloud Map) mà không phơi nó ra internet. Đây là cách API Gateway đứng trước EC2/ECS — không bao giờ bằng instance ID.
Mock API Gateway answers by itself. CORS OPTIONS, static responses, prototypes.API Gateway tự trả lời. CORS OPTIONS, response tĩnh, prototype.
HTTP API's direct AWS integrations — the whole listDirect AWS integration của HTTP API — trọn danh sách EventBridge PutEvents · SQS SendMessage, ReceiveMessage, DeleteMessage, PurgeQueue · AppConfig GetConfiguration · Kinesis Data Streams PutRecord · Step Functions StartExecution, StartSyncExecution, StopExecution.
Support is per action, not per service — SendMessage is in, SendMessageBatch is not. DynamoDB, S3, SNS and SES are absent entirely, so those need a Lambda. Hence: "serverless API straight onto DynamoDB" ⇒ REST API; "HTTP API onto DynamoDB" ⇒ only via Lambda.
EventBridge PutEvents · SQS SendMessage, ReceiveMessage, DeleteMessage, PurgeQueue · AppConfig GetConfiguration · Kinesis Data Streams PutRecord · Step Functions StartExecution, StartSyncExecution, StopExecution.
Hỗ trợ theo từng action, không theo service — có SendMessage, không có SendMessageBatch. DynamoDB, S3, SNS và SES vắng mặt hoàn toàn, nên phải qua Lambda. Vì vậy: "API serverless đi thẳng vào DynamoDB" ⇒ REST API; "HTTP API vào DynamoDB" ⇒ chỉ qua Lambda.

Three API types, and the price of eachBa loại API, và giá của từng loại

REST API HTTP API WebSocket API
Conversation shapeKiểu hội thoạirequest → responserequest → responserequest → responserequest → responseserver can push, connection stays openserver đẩy được, giữ kết nối mở
Price (us-east-1, first tier)Giá (us-east-1, tier đầu)$3.50 / 1M req$1.00 / 1M req$1.00 / 1M msg + $0.25 / 1M connection-minutesphút kết nối
API keys · usage plans · per-client throttlingAPI key · usage plan · throttle theo client✓✗✗
Response cache · request validation · WAF · private endpointCache response · validate request · WAF · private endpoint✓✗✗
Native JWT/OIDC authorizerJWT/OIDC authorizer nativevia Lambda authorizer / Cognitoqua Lambda authorizer / Cognito✓✗
Endpoint typesLoại endpointEdge-optimized · Regional · PrivateEdge-optimized · Regional · PrivateRegionalRegionalRegionalRegional
  • WebSocket messages bill in 32 KB blocks: a 100 KB message counts as four. So you can't compare it to HTTP by request count.Message WebSocket tính theo khối 32 KB: một message 100 KB tính là bốn. Nên không so nó với HTTP bằng số request được.
  • WebSocket route keys: $connect, $disconnect, $default, plus your own. The usual pattern stores connectionId in DynamoDB so the backend can push to a client later.Route key của WebSocket: $connect, $disconnect, $default, cộng route riêng của bạn. Mẫu thường gặp là lưu connectionId vào DynamoDB để backend đẩy tin xuống client sau.
  • Edge-optimized ≠ multi-Region. It's AWS running a CloudFront distribution in front of a single-Region API. It shortens the public-internet leg for distant clients; it does not deploy anything anywhere else and gives no regional failover. If the Region dies, so does the API.Edge-optimized ≠ đa Region. Nó là AWS chạy một CloudFront distribution trước một API ở một Region. Nó rút ngắn chặng internet công cộng cho client ở xa; nó không deploy gì ở đâu khác và không có failover theo Region. Region chết là API chết.
  • A truly global API = a Regional stack per Region + Route 53 latency or failover routing + health checks, and a data layer that can span Regions (DynamoDB Global Tables for active-active).API global thật sự = mỗi Region một stack Regional + Route 53 latency/failover routing + health check, cùng một tầng dữ liệu trải được nhiều Region (DynamoDB Global Tables cho active-active).
  • Clients all near the Region? Regional is right and edge-optimized buys nothing. Clients worldwide? Edge-optimized, or your own CloudFront in front of a Regional endpoint when you need control over cache keys, TTLs or WAF.Client đều ở gần Region? Regional là đúng, edge-optimized chẳng thêm gì. Client toàn cầu? Edge-optimized, hoặc tự đặt CloudFront trước Regional endpoint khi cần kiểm soát cache key, TTL hay WAF.
  • Global Accelerator cannot take an API Gateway endpoint. Its endpoints are ALB, NLB, EC2 and Elastic IP.Global Accelerator không nhận endpoint API Gateway. Endpoint của nó là ALB, NLB, EC2 và Elastic IP.

Throttling the noisy clientBóp client ồn ào

When one identified caller is drowning the API, the fix is a usage plan bound to their API key with a rate and burst limit. They get 429, back off, and retry; everyone else is unaffected. Khi một caller đã định danh đang làm ngập API, cách sửa là usage plan gắn vào API key của họ với rate và burst limit. Họ nhận 429, lùi lại, rồi retry; những người khác không bị ảnh hưởng.

  • Client-side exponential backoff with jitter is the right partner to a 429 — but on its own it doesn't stop the flood, and retries can make it worse.Exponential backoff kèm jitter ở phía client là cặp đôi đúng của 429 — nhưng tự nó không chặn được cơn lũ, và retry có thể làm nặng thêm.
  • Lambda reserved concurrency is a per-function ceiling, blind to which client is calling — it throttles the well-behaved caller just as hard as the noisy one.Reserved concurrency của Lambda là trần theo function, không biết client nào đang gọi — nó bóp caller ngoan y hệt caller ồn ào.
  • Caching only helps reads. A flood of PUTs is untouched by an API cache.Cache chỉ giúp đọc. Một cơn lũ PUT thì cache API không đụng tới được.
  • Usage plans and API keys are REST-API only — needing per-client quotas is by itself a reason to choose REST over HTTP API.Usage plan và API key chỉ có ở REST API — cần quota theo từng client tự nó đã là lý do chọn REST thay vì HTTP API.