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 |
Auth optionsChọn auth
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=0if IAM allows.Client bỏ qua cache bằngCache-Control: max-age=0nế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 |
|---|---|---|
| 400 | Bad Request | Malformed requestRequest lỗi format |
| 403 | Access Denied | WAF, IAM, resource policyWAF, IAM, resource policy |
| 429 | Throttled | Usage plan or account quotaUsage plan hoặc quota account |
| 502 | Bad Gateway | Lambda proxy returned wrong shapeLambda proxy trả sai shape |
| 503 | Service Unavailable | Backend down / degradedBackend chết / suy giảm |
| 504 | Gateway Timeout | Backend 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:SourceVpcandaws:SourceVpceto allow specific VPCs / endpoints, even across accounts.Resource policy dùngaws:SourceVpcvà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.
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.
OPTIONS, static responses, prototypes.API Gateway tự trả lời. CORS OPTIONS, response tĩnh, prototype.
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ại | request → responserequest → response | request → responserequest → response | server 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 native | via Lambda authorizer / Cognitoqua Lambda authorizer / Cognito | ✓ | ✗ |
| Endpoint typesLoại endpoint | Edge-optimized · Regional · PrivateEdge-optimized · Regional · Private | RegionalRegional | RegionalRegional |
- 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 storesconnectionIdin 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ưuconnectionIdvà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ủa429— 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ũPUTthì 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.