Amazon API Gateway: REST vs HTTP vs WebSocket APIs
Choose the right API Gateway API type for a banking workload using a verified feature matrix, real prices, quotas and a decision table, then build and tear down an HTTP API from the CLI.
Assumes: .NET 10 LTS · AWS SDK for .NET v4 (AWSSDK.ApiGatewayManagementApi 4.1) · Amazon.Lambda.APIGatewayEvents · AWS CLI v2 · Region us-east-1. Verified against official sources on 2026-11-17.
Learning objectives
By the end of this lesson you can:
- Explain what REST APIs, HTTP APIs and WebSocket APIs are in Amazon API Gateway and what each one costs per million requests in us-east-1.
- Use a verified feature matrix to decide which API type a Harbourline Bank workload needs (WAF, API keys, private endpoints, caching, JWT authorizers, VPC links).
- Describe stages, deployments, custom domains and the quotas that bite in practice (integration timeout, payload size, WebSocket frames).
- Write a small .NET 10 WebSocket backend that pushes a payment-status update to a connected client through the
@connectionsAPI. - Create an HTTP API with the CLI "quick create" option, call it, and delete it.
Prerequisites
- REST API design for banking — resources, status codes and ProblemDetails
- OpenAPI contracts and contract testing — helpful, not required
- Tools: AWS CLI v2 with the
learn-sandboxSSO profile, .NET 10 SDK, PowerShell or Git Bash
Why this matters in banking
Harbourline's architecture board has three requests on the table. The mobile team wants a public Account Information API that the security team insists sits behind a web application firewall. The payments team wants a cheap internal proxy in front of a reconciliation service that only other AWS workloads call. The app team wants to push "payment settled" and "balance changed" events to the customer's phone without polling every five seconds.
Pick the wrong API Gateway type and you find out late: the WAF cannot attach, the private endpoint option is missing, or the bill is three times what finance approved. This lesson gives you the verified facts so the decision is made once, on paper, before anyone writes infrastructure code.
The idea in plain language
Amazon API Gateway is a managed front door for APIs. Clients call a URL that API Gateway owns; API Gateway checks the request (authentication, throttling, sometimes validation) and forwards it to a backend: a Lambda function, a container behind a load balancer, any HTTPS URL, or an AWS service API.
It comes in three products:
- REST API — the original, feature-rich product. It has API keys and usage plans, caching, request validation, AWS WAF, private endpoints and request/response transformation with mapping templates. It costs more.
- HTTP API — a leaner, cheaper product with fewer features. It does JWT authorizers, Lambda authorizers, IAM, CORS and private integrations well, and it is about 70% cheaper per request.
- WebSocket API — a long-lived, two-way connection. The client connects once; your backend can send messages to that client at any time.
Analogy: a REST API is the bank's staffed branch counter: identity checks, forms validated on the spot, a queue manager, a security guard at the door, and higher running costs. An HTTP API is the self-service kiosk: fast, cheap and fine for routine transactions, but no guard and no form checking. A WebSocket API is the open phone line to a relationship manager: once the call is connected, either side can speak.
The names are confusing. Both "REST API" and "HTTP API" serve RESTful HTTP endpoints. The name describes the product tier, not the architectural style.
What problem the AWS service solves
Without API Gateway you would run and patch your own reverse proxy fleet, terminate TLS, validate tokens, throttle abusive clients, and scale it all. API Gateway is serverless: no instances, pay per request, scales automatically within account quotas.
Verified feature matrix: REST API vs HTTP API
Checked against the official "Choose between REST APIs and HTTP APIs" page on 2026-11-17.
| Feature | REST API | HTTP API |
|---|---|---|
| Endpoint types | Edge-optimized, Regional, Private | Regional only |
| Mutual TLS (client certificates) | Yes | Yes |
| Certificates for backend authentication | Yes | No |
| AWS WAF | Yes | No |
| IAM authorization | Yes | Yes |
| Resource policies | Yes | No |
| Amazon Cognito user pool authorizer | Yes | Via JWT authorizer |
| Lambda authorizers | Yes | Yes |
| JWT authorizer (any OIDC/OAuth 2.0 issuer) | Yes (newer feature) | Yes |
| API keys, usage plans, per-client throttling | Yes | No |
| Developer portal (API Gateway portals) | Yes | No |
| Caching | Yes | No |
| Request validation | Yes | No |
| Request parameter transformation | Yes | Yes (parameter mapping) |
| Request body transformation (mapping templates) | Yes | No |
| Custom gateway responses | Yes | No |
| Canary release deployments | Yes | No |
| Automatic deployments | No | Yes |
| Test invocations in the console | Yes | No |
| Mock integrations | Yes | No |
| Execution logs, access logs to Data Firehose | Yes | No (access logs to CloudWatch only) |
| AWS X-Ray tracing | Yes | No |
| Private integration: NLB | Yes | Yes |
| Private integration: ALB | Yes (VPC link V2) | Yes |
| Private integration: AWS Cloud Map | No | Yes |
| Response streaming | Yes | No |
Two rows changed recently and many blog posts are out of date:
- JWT authorizers on REST APIs. REST APIs now have a native JWT authorizer that trusts one or more OIDC issuers, checks audiences (or
client_idfor Cognito access tokens), and requires scopes per method. Before this, REST APIs offered only the Cognito user pool authorizer or a Lambda authorizer. - ALB private integrations on REST APIs. Since November 2025 a REST API can reach a private Application Load Balancer through a VPC link V2, without the old "NLB in front of ALB" workaround. VPC link V1 (NLB only) is now called legacy. The container-backed APIs lesson covers this in depth.
WebSocket APIs in brief
A WebSocket API has routes selected by a route selection expression, usually $request.body.action. Three special routes exist: $connect (handshake; the place to authorize), $disconnect (best-effort clean-up) and $default (anything that matches no other route). Authorization uses IAM or a Lambda authorizer on $connect. AWS WAF cannot protect WebSocket APIs (they are not in the list of WAF-protectable resources).
Your backend sends data back to a client by calling the @connections management API: POST https://{api-id}.execute-api.us-east-1.amazonaws.com/{stage}/@connections/{connectionId}. Those calls are SigV4-signed, so the caller needs execute-api:ManageConnections permission.
Quotas that matter (checked 2026-11-17)
| Quota | REST API | HTTP API | WebSocket API |
|---|---|---|---|
| Integration timeout | 50 ms – 29 s; can be raised above 29 s for Regional and private APIs (may reduce your account throttle quota); not for edge-optimized | Max 30 s, cannot be raised | 50 ms – 29 s, cannot be raised |
| Payload size | 10 MB | 10 MB | 128 KB per message, 32 KB per frame |
| Connection limits | — | — | 2 h max connection, 10 min idle timeout, 500 new connections/s per account per Region (raisable) |
| Stages per API | 10 (raisable) | 10 (raisable) | 10 (raisable) |
| Authorizers per API | 10 | 10 | 10 Lambda authorizers |
Account-level throttling applies across REST, HTTP and WebSocket APIs together: in us-east-1 the default is 10,000 requests per second steady state with a token-bucket burst of 5,000 requests. The throttling lesson explains the token bucket.
Response streaming on REST APIs (responseTransferMode = STREAM, proxy integrations only) lets a response run for up to 15 minutes and exceed 10 MB, which is the honest way around the 29-second limit for long downloads such as statement PDFs. It disables caching, content encoding and VTL response transformation.
Pricing (us-east-1, checked 2026-11-17)
| Item | Price |
|---|---|
| HTTP API requests | USD 1.00 per million for the first tier, USD 0.90 per million above it (tier boundary about 300 million ⚠ VERIFY); metered in 512 KB increments |
| REST API requests | USD 3.50 per million (first 333 million), USD 2.80 (next 667 million), USD 2.38 beyond that tier |
| WebSocket | USD 1.00 per million messages (metered in 32 KB increments) + USD 0.25 per million connection minutes |
| REST API cache | Billed per hour by cache size; the pricing example uses USD 0.038 per hour for a 1.6 GB cache (other sizes ⚠ VERIFY) |
| Data transfer out | Standard EC2 data-transfer rates (examples use USD 0.09 per GB) |
The API Gateway pricing page lists a free tier of 1 million REST calls, 1 million HTTP calls, 1 million WebSocket messages and 750,000 connection minutes per month for 12 months for new customers. Accounts created on or after 2025-07-15 use the credit-based Free/Paid plans; whether this 12-month allowance still applies on top of credits is unclear ⚠ VERIFY in your Billing console under Free Tier. Either way, the lab in this lesson makes a handful of requests: well under one cent.
Worked example. Harbourline's mobile app makes about 50 million API calls a month. As a REST API that is 50 × 3.50 = USD 175; as an HTTP API, 50 × 1.00 = USD 50. The WAF that only REST can carry adds its own monthly fees (see AWS WAF and OWASP). For a public customer API, paying the REST premium for WAF is normally the right trade.
Stages, deployments and custom domains
- REST API: you edit resources and methods, then create a deployment (an immutable snapshot) and point a stage (for example
v1) at it. Forgetting to redeploy is the classic "my change does nothing" bug. Stages carry settings: throttling, logging, caching, WAF association, stage variables and canary settings that send a percentage of traffic to a new deployment. - HTTP API: stages can auto-deploy, and quick create gives you a
$defaultstage served at the root URL. - Custom domains: map
api.harbourline.exampleto one or more API stages with API mappings (for example/accounts→ accounts API stagev1). Certificates come from AWS Certificate Manager; a Regional custom domain needs the certificate in the same Region, an edge-optimized one needs it in us-east-1. Once the custom domain works, disable the defaultexecute-apiendpoint so clients cannot bypass it.
Microsoft / Azure comparison
| You know (Microsoft/Azure) | AWS equivalent | What's different |
|---|---|---|
| Azure API Management (APIM) instance | API Gateway REST, HTTP or WebSocket API | No "instance" or tier to size: you pick an API type per API and pay per request |
| APIM tiers: Consumption, Developer, Basic/Standard/Premium and the v2 tiers | REST API (feature-rich) vs HTTP API (cheap) | APIM tiers change capacity and features of one gateway; API Gateway types change features per API |
APIM XML policies (rate-limit-by-key, validate-jwt, set-header, cache-lookup) | Usage plans, JWT/Cognito/Lambda authorizers, parameter mapping, mapping templates, stage cache | No single policy pipeline: each capability is configuration on the API, stage, method or route |
| APIM developer portal (all tiers except Consumption) | API Gateway portals (REST APIs only, access controlled with Cognito) | Portals publish REST APIs only |
| APIM products and subscription keys | Usage plans and API keys | Keys identify and meter; they are not authentication |
| APIM in a VNet / private endpoint | Private REST API (interface VPC endpoint) and VPC links | HTTP APIs cannot be private endpoints |
| Azure Front Door WAF or Application Gateway WAF | AWS WAF on REST API stages, ALB or CloudFront | WAF cannot attach to HTTP or WebSocket APIs |
| Azure Web PubSub / SignalR Service | API Gateway WebSocket API | You manage connection IDs yourself; no hub/group abstraction |
Architecture
Security-boundary view. Everything left of API Gateway is untrusted internet. WAF and the authorizers are the first trust boundary; the backend Lambda functions and the private ALB sit in the trusted zone and never get a public address. The WebSocket notifier is an internal caller: it needs execute-api:ManageConnections on that API only, and it must never trust message content from the client for authorization decisions.
Step-by-step implementation
Classify each workload
For each API write down: caller type (customer app, partner, internal service), auth method, whether WAF is mandatory, whether it must be private, and peak requests per second. That table drives the choice.
Apply the decision table
| Harbourline use case | Choose | Why |
|---|---|---|
| Public customer Account Information API, security requires WAF and request validation | REST API (Regional) | Only REST APIs associate with AWS WAF and validate requests; JWT or Cognito authorizer with scopes |
| Open Banking-style partner (TPP) API with tiers and quotas | REST API | API keys and usage plans for per-partner metering; real auth via OAuth/mTLS |
| API callable only from inside Harbourline VPCs | Private REST API | HTTP APIs have no private endpoint type |
| Internal low-cost proxy to a private reconciliation service | HTTP API + VPC link | Cheapest per request; IAM or JWT auth; ALB, NLB or Cloud Map integration |
| Push balance and payment-status updates to the app | WebSocket API | Server-initiated messages; 2-hour connections, reconnect logic in the app |
| Statement PDF download that can exceed 29 s or 10 MB | REST API with response streaming, or a pre-signed S3 URL | Streaming lifts both limits; pre-signed URLs keep big files off the gateway |
Prototype the cheapest option first
Use the CLI quick create below to stand up an HTTP API in a minute, prove the backend contract, then decide whether the REST features justify the price.
Record the decision
Write a short architecture decision record (ADR) per API: chosen type, rejected types, and the features you depend on. When the business later asks for WAF on the "cheap" HTTP API, the ADR shows why that means a migration to REST.
AWS Console instructions
- Console → API Gateway → APIs → Create API. The page shows the three types with Build buttons, plus REST API Private.
- Choose HTTP API → Build → Add integration → HTTP, method
ANY, URLhttps://example.com. Name ithl-m04-l4-proxy. Keep the$defaultstage with Auto-deploy on, then Create. - Open the API → Stages → $default and copy the Invoke URL. Open Throttling to see route-level settings, and Monitor → Logging to enable access logs.
- Delete it afterwards: APIs → select → Actions → Delete.
AWS CLI
# 1. Quick create: an HTTP API with an HTTP_PROXY integration, a $default route
# and an auto-deploying $default stage. example.com is an IANA reserved domain.
aws apigatewayv2 create-api \
--name hl-m04-l4-proxy \
--protocol-type HTTP \
--target https://example.com \
--tags Project=cea-lab,Lab=m04-l4,Environment=learn,Owner=alex \
--profile learn-sandbox --region us-east-1
# 2. Capture the ID and endpoint
API_ID=$(aws apigatewayv2 get-apis --profile learn-sandbox --region us-east-1 \
--query "Items[?Name=='hl-m04-l4-proxy'].ApiId" --output text)
ENDPOINT=$(aws apigatewayv2 get-api --api-id "$API_ID" \
--profile learn-sandbox --region us-east-1 --query ApiEndpoint --output text)
# 3. Call it (any path is proxied to example.com)
curl -i "$ENDPOINT/"
# 4. Look at what quick create built: one integration, one route, one stage
aws apigatewayv2 get-routes --api-id "$API_ID" --profile learn-sandbox --region us-east-1
aws apigatewayv2 get-stages --api-id "$API_ID" --profile learn-sandbox --region us-east-1
# 5. Teardown
aws apigatewayv2 delete-api --api-id "$API_ID" --profile learn-sandbox --region us-east-1In PowerShell, replace API_ID=$(...) with $API_ID = aws apigatewayv2 get-apis ... and call Invoke-RestMethod "$ENDPOINT/".
Infrastructure as Code
using Amazon.CDK;
using Amazon.CDK.AWS.Apigatewayv2;
using Amazon.CDK.AwsApigatewayv2Integrations;
using Constructs;
namespace Harbourline.ApiGateway.Infra;
public sealed class ProxyApiStack : Stack
{
public ProxyApiStack(Construct scope, string id, IStackProps? props = null)
: base(scope, id, props)
{
// HTTP API whose default route proxies to a public HTTPS URL
var api = new HttpApi(this, "ProxyApi", new HttpApiProps
{
ApiName = "hl-m04-l4-proxy",
DefaultIntegration = new HttpUrlIntegration("ExampleUrl", "https://example.com"),
});
new CfnOutput(this, "ApiUrl", new CfnOutputProps { Value = api.ApiEndpoint });
}
}Note the namespaces: in CDK v2 the stable API Gateway v2 integrations and authorizers live in Amazon.CDK.AwsApigatewayv2Integrations and Amazon.CDK.AwsApigatewayv2Authorizers, while the core constructs are in Amazon.CDK.AWS.Apigatewayv2.
Complete code
A WebSocket backend for Harbourline's "payment status" push. One Lambda function handles $connect, $disconnect and $default; a notifier class pushes updates. Connection IDs are stored in DynamoDB (hl-m04-l4-connections, partition key connectionId, TTL attribute expiresAt). The customerId comes from a Lambda authorizer on $connect (see Lambda authorizers).
using System.Text.Json;
using Amazon.ApiGatewayManagementApi;
using Amazon.ApiGatewayManagementApi.Model;
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.Model;
using Amazon.Lambda.APIGatewayEvents;
using Amazon.Lambda.Core;
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]
namespace Harbourline.Notifications.Sockets;
public sealed record PaymentStatusUpdate(string PaymentId, string Status, decimal Amount, string Currency);
public sealed class PaymentStatusSocket
{
private const string Table = "hl-m04-l4-connections";
private readonly IAmazonDynamoDB _db = new AmazonDynamoDBClient();
public async Task<APIGatewayProxyResponse> HandleAsync(APIGatewayProxyRequest request, ILambdaContext context)
{
var ctx = request.RequestContext;
switch (ctx.RouteKey)
{
case "$connect":
if (ctx.Authorizer is null || !ctx.Authorizer.TryGetValue("customerId", out var customerId))
{
return new APIGatewayProxyResponse { StatusCode = 403 };
}
await _db.PutItemAsync(new PutItemRequest
{
TableName = Table,
Item = new Dictionary<string, AttributeValue>
{
["connectionId"] = new() { S = ctx.ConnectionId },
["customerId"] = new() { S = customerId.ToString() },
["expiresAt"] = new() { N = DateTimeOffset.UtcNow.AddHours(2).ToUnixTimeSeconds().ToString() },
},
});
return new APIGatewayProxyResponse { StatusCode = 200 };
case "$disconnect":
await DeleteConnectionAsync(_db, ctx.ConnectionId);
return new APIGatewayProxyResponse { StatusCode = 200 };
default:
context.Logger.LogInformation($"Ignoring client message on route {ctx.RouteKey}");
return new APIGatewayProxyResponse { StatusCode = 200 };
}
}
internal static Task DeleteConnectionAsync(IAmazonDynamoDB db, string connectionId) =>
db.DeleteItemAsync(new DeleteItemRequest
{
TableName = Table,
Key = new Dictionary<string, AttributeValue> { ["connectionId"] = new() { S = connectionId } },
});
}
public sealed class PaymentStatusNotifier(IAmazonDynamoDB db, string apiId, string stage)
{
private readonly AmazonApiGatewayManagementApiClient _client = new(new AmazonApiGatewayManagementApiConfig
{
ServiceURL = $"https://{apiId}.execute-api.us-east-1.amazonaws.com/{stage}",
});
public async Task<bool> PushAsync(string connectionId, PaymentStatusUpdate update, CancellationToken ct)
{
using var body = new MemoryStream(JsonSerializer.SerializeToUtf8Bytes(update));
try
{
await _client.PostToConnectionAsync(new PostToConnectionRequest
{
ConnectionId = connectionId,
Data = body,
}, ct);
return true;
}
catch (GoneException)
{
await PaymentStatusSocket.DeleteConnectionAsync(db, connectionId);
return false;
}
}
}Packages: Amazon.Lambda.Core, Amazon.Lambda.APIGatewayEvents, Amazon.Lambda.Serialization.SystemTextJson, AWSSDK.DynamoDBv2 and AWSSDK.ApiGatewayManagementApi (4.1.x). Deploy with runtime dotnet10 and handler Harbourline.Notifications.Sockets::Harbourline.Notifications.Sockets.PaymentStatusSocket::HandleAsync (assembly name assumed to match the namespace).
Code explained line by line
[assembly: LambdaSerializer(...)]— tells the .NET Lambda runtime to use System.Text.Json to turn the incoming WebSocket event intoAPIGatewayProxyRequest.PaymentStatusUpdate— a record withdecimal Amountand an ISO currency; money is neverdouble.HandleAsync— one function serves all three routes;ctx.RouteKeyholds$connect,$disconnector the matched custom route.ctx.Authorizer.TryGetValue("customerId", ...)— the Lambda authorizer on$connectputs the resolvedcustomer_idinto its context. The client never supplies its own customer ID.- Returning
403from$connectrejects the handshake; any 2xx accepts it. PutItemAsyncwithexpiresAt— stores the connection with a DynamoDB TTL two hours ahead, matching the maximum connection duration, so stale rows clean themselves up even if$disconnectnever fires.$disconnect— best effort; API Gateway does not guarantee delivery, which is why TTL exists.default— logs and ignores client messages; this socket is server-to-client only.PaymentStatusNotifier— called by the Payments Service (for example from an EventBridge rule) when a status changes.ServiceURL = https://{apiId}.execute-api.us-east-1.amazonaws.com/{stage}— the management endpoint; with a custom domain you drop the stage segment.PostToConnectionAsyncwith aMemoryStreambody — SigV4-signed by the SDK using the function's IAM role, which needsexecute-api:ManageConnections.GoneException— the client has gone (HTTP 410). Delete the stale connection and reportfalseso the caller can fall back to a push notification.
Security considerations
⚠ Learning shortcut — not for production
The CLI and CDK examples proxy to https://example.com with no authorization so you can see the moving parts. A real Harbourline API always has an authorizer (JWT, Cognito, IAM or Lambda), throttling, access logging with retention, and the default execute-api endpoint disabled behind a custom domain. Delete the example API as soon as you have called it.
- WAF is REST-only. If a public API needs WAF and you choose HTTP API, your only option is to put CloudFront (with WAF) in front, which adds cost and an origin-bypass risk you must close.
- Private means private. A private REST API is reachable only through an interface VPC endpoint and must have a resource policy; it is the right choice for internal banking APIs that must not be internet-reachable.
- WebSocket authorization happens once, at
$connect. A token that expires mid-connection is not re-checked; keep connections short-lived or re-authorize in your backend before sending sensitive data. - Data protection. Payment-status messages are personal data under UK GDPR. Send identifiers and statuses, not full account details, and get your data-protection officer's review before pushing balances.
- Tracing. API Gateway REST stages can emit X-Ray traces, but the X-Ray SDKs are in maintenance mode; instrument .NET code with OpenTelemetry (ADOT) and keep X-Ray as the backend.
Banking use case
Harbourline's architecture board signs off three APIs: hl-accounts-public (Regional REST API, Cognito JWT authorizer with scopes, WAF with managed rules and a rate-based rule, request validator, access logs for 90 days); hl-recon-internal (HTTP API with IAM authorization and a VPC link to a private ALB, used only by the nightly reconciliation job); and hl-payment-status (WebSocket API, Lambda authorizer on $connect, DynamoDB connection table with TTL, app falls back to a push notification when it receives GoneException). Finance gets the cost estimate from the pricing table above.
Common mistakes
- "HTTP API is just the new REST API." It is a cheaper product with fewer features. Check the matrix before migrating.
- Changing a REST API and not redeploying. Changes only go live after a new deployment to the stage.
- Assuming 29 s can be ignored. A slow core banking call behind API Gateway returns 504 at the integration timeout even if the backend finishes later. Use asynchronous patterns (202 Accepted + polling) or streaming.
- Sending more than 32 KB in one WebSocket frame. The connection closes with code 1009; split larger messages.
- Treating
$disconnectas guaranteed. Always expire connection records with TTL.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
{"message":"Not Found"} from an HTTP API | No route matches and no $default route | Add the route or a $default route |
| REST change not visible | Not redeployed | aws apigateway create-deployment --rest-api-id ... --stage-name v1 |
| 504 after about 29 s | Integration timeout | Make the backend faster, go asynchronous, use response streaming, or request a timeout increase (Regional/private REST only) |
| Cannot select the API in WAF | It is an HTTP or WebSocket API | Use a REST API, or WAF on CloudFront/ALB |
GoneException on PostToConnection | Client disconnected | Delete the connection record; fall back to another channel |
ForbiddenException on PostToConnection | Missing execute-api:ManageConnections or wrong stage in the URL | Fix the IAM policy resource ARN and ServiceURL |
Cost and cleanup
This lesson is cost: free: a few HTTP API requests cost a fraction of a cent, and the CDK/Terraform stacks contain no hourly resources. Tear down and verify:
aws apigatewayv2 delete-api --api-id "$API_ID" --profile learn-sandbox --region us-east-1
# If you deployed the CDK stack instead:
# cdk destroy --profile learn-sandbox
# Final check: nothing tagged for the course should remain
aws resourcegroupstaggingapi get-resources \
--tag-filters Key=Project,Values=cea-lab \
--profile learn-sandbox --region us-east-1Exercises
- 🟢 Guided: run the CLI section, call the API, then add a second route with
aws apigatewayv2 create-route --api-id $API_ID --route-key "GET /health" --target integrations/<integration-id>and call it. Delete the API. - 🟡 Challenge: using only the pricing table, compute the monthly API Gateway cost for 120 million requests as REST vs HTTP, and for 20,000 app users who each keep a WebSocket open for 30 minutes a day and receive 10 messages a day (30-day month).
- 🔴 Live problem: a product owner wants a partner API with per-partner quotas, WAF, and calls that sometimes take 45 seconds. Write the ADR: which API type, what you do about the 45 seconds, and what you tell the partner.
Assignment
Add docs/adr/0004-api-gateway-type.md to your portfolio repository: for each of Harbourline's three APIs, record the chosen type, the features relied on (cite the matrix), the expected monthly cost at 10 and 100 million requests, and the migration trigger that would make you switch type.
Solutions
Find the integration ID with aws apigatewayv2 get-integrations --api-id $API_ID --query "Items[0].IntegrationId" --output text, then create the route with --target integrations/<id>. Because the $default stage auto-deploys, the new route is live within seconds; on a REST API you would need a new deployment. Example.com has no /health page, so expect whatever example.com returns for that path — the point is that routing worked.
REST: 120 million requests = 120 × 3.50 = USD 420. HTTP: 120 × 1.00 = USD 120 (still in the first tier). WebSocket: connection minutes = 20,000 × 30 × 30 = 18 million → 18 × 0.25 = USD 4.50; messages = 20,000 × 10 × 30 = 6 million → USD 6.00; total about USD 10.50 plus Lambda and DynamoDB. WebSockets are cheap; the per-request REST premium is what dominates.
Choose a Regional REST API: WAF and usage plans exist only there. For 45-second calls, do not just raise the integration timeout (it may cost account throttle capacity): change the contract to 202 Accepted with a Location header and a status resource, or use response streaming if the response genuinely streams. Tell the partner the quota and throttling numbers per tier and that 429 responses must be retried with backoff.
Knowledge check
Answer: Only REST APIs (on a stage). HTTP and WebSocket APIs are not in the WAF list of protectable resources; put CloudFront or an ALB with WAF in front if you must.
Answer: REST, with the Private endpoint type plus an interface VPC endpoint and a resource policy. HTTP APIs support only Regional endpoints.
Answer: Up to 29 seconds. For Regional and private REST APIs you can request a higher value through Service Quotas, possibly at the cost of a lower account throttle quota. Edge-optimized REST APIs and HTTP APIs (max 30 s) cannot be raised.
Answer: The frame limit is 32 KB, so the connection is closed with code 1009. Messages up to 128 KB must be split into frames of 32 KB or less.
Answer: It calls the @connections management API (PostToConnection) with the connection ID, signed with SigV4, using an IAM identity that has execute-api:ManageConnections.
Interview questions
- "When would you choose an HTTP API over a REST API?" — When I need only routing, JWT/IAM/Lambda auth, CORS and private integrations, and cost matters: about USD 1.00 vs 3.50 per million in us-east-1. Not when I need WAF, API keys/usage plans, caching, request validation or a private endpoint.
- "How do you deal with the 29-second integration timeout?" — Design asynchronous APIs (202 + status resource), stream responses on REST APIs, or request a timeout increase for Regional/private REST APIs knowing it may reduce throttle capacity.
- "How would you push real-time balance updates?" — WebSocket API, authorize on
$connect, store connection IDs with TTL, push via@connections, handleGoneException, and fall back to mobile push notifications. - "How does API Gateway compare with Azure APIM?" — APIM is one gateway instance with a policy pipeline and a tier; API Gateway is per-API, per-request priced, with capabilities spread across API types, stages and authorizers.
- "What does a stage give you on a REST API?" — A named deployment target with its own throttling, logging, caching, WAF association, stage variables and canary settings.
Certification practice
A bank is building a public account-information API on Lambda. Security requires AWS WAF managed rules, per-partner quotas, and the lowest operational overhead. Which design meets the requirements?
A. HTTP API with a JWT authorizer and a WAF web ACL associated with the $default stage
B. Regional REST API with a Cognito or JWT authorizer, usage plans with API keys, and a WAF web ACL on the stage
C. WebSocket API with a Lambda authorizer and WAF on the API
D. HTTP API behind a Network Load Balancer with WAF on the NLB
Answer: B. REST API stages accept WAF associations and usage plans. A is wrong: HTTP APIs cannot be associated with WAF. C is wrong: WebSocket APIs are not WAF-protectable and do not fit request/response APIs. D is wrong: WAF does not attach to NLBs, and it adds operations.
A REST API (Regional) fronts a Lambda function that generates statement PDFs. Large statements fail with 504 after about 29 seconds, although the function's timeout is 120 seconds. What is the most suitable fix that keeps a synchronous download?
A. Raise the Lambda timeout to 900 seconds
B. Enable API caching on the stage
C. Configure the integration for response streaming (STREAM) and stream the PDF from the function
D. Switch to an HTTP API, whose timeout is 60 seconds
Answer: C. Streaming lets a REST API response run up to 15 minutes and exceed 10 MB. A is wrong: the gateway's integration timeout fires first. B does not help a first request and is incompatible with streaming. D is wrong: the HTTP API maximum is 30 seconds.
An internal payments API must be reachable only from the bank's VPCs, and requests from other accounts must be denied even if credentials leak. Which configuration fits?
A. HTTP API with IAM authorization
B. Private REST API with an interface VPC endpoint and a resource policy that allows only that endpoint (aws:SourceVpce)
C. Edge-optimized REST API with an IP allow list in WAF
D. Regional REST API with an API key required
Answer: B. Private REST APIs are reachable only through interface VPC endpoints, and the resource policy limits access to specific endpoints. A is still a public endpoint. C is public and edge-distributed. D: API keys are not an access control.
Completion checklist
- I can explain the REST vs HTTP vs WebSocket difference to a colleague in two sentences
- I can name four features that only REST APIs have
- I created and deleted an HTTP API with the CLI
- I can explain the 29-second timeout and three ways around it
- I ran the tag check and nothing tagged
Project=cea-labremains
Key takeaways
- REST API = features (WAF, API keys, caching, validation, private endpoints, streaming); HTTP API = price (about USD 1.00 vs 3.50 per million in us-east-1); WebSocket = server push.
- REST APIs gained JWT authorizers and ALB private integrations via VPC link V2; old comparisons are wrong on both.
- Account throttling is shared: 10,000 RPS steady and 5,000 burst per Region in us-east-1 across all API types.
- Timeouts and payload limits shape API design more than any feature: 29 s, 10 MB, 128 KB/32 KB for WebSocket.
- Write the choice down in an ADR; migrating between API types later is real work.
Further reading
- Choose between REST APIs and HTTP APIs
- Amazon API Gateway quotas
- Quotas for REST APIs
- Quotas for HTTP APIs
- Quotas for WebSocket APIs
- Control access to REST APIs using JWT authorizers
- Stream the integration response
- Use @connections commands in your backend service
- API Gateway portals
- Amazon API Gateway pricing
- Feature-based comparison of Azure API Management tiers
- Related: Module 5: Security · DVA-C03
Independent learning resource — not affiliated with, endorsed or sponsored by Amazon Web Services. AWS and related marks are trademarks of Amazon.com, Inc. or its affiliates. All banking data in examples is fictional. Sample architectures are for learning and are not automatically compliant with GDPR, PCI DSS or any banking regulation.
OpenAPI contracts and contract testing
Design the Account Information API in OpenAPI, generate it from ASP.NET Core 10, import it into API Gateway, generate a typed C# client with Kiota, and stop breaking changes with contract tests, Pact and oasdiff.
Authentication fundamentals: OAuth 2.0, OpenID Connect and JWTs
Understand OAuth 2.0 flows, OpenID Connect and JSON Web Tokens well enough to validate access tokens correctly in an ASP.NET Core API on AWS, and to spot the mistakes that leak banking data.