API Gateway & Step Functions
Building serverless APIs and workflows — API Gateway REST vs HTTP vs WebSocket APIs, integrations, authorisers (IAM, Cognito, JWT, Lambda), throttling and usage plans, stages and custom domains, Lambda function URLs; Step Functions state machines, states, retries and catches, Standard vs Express workflows, the saga pattern, and a serverless reference architecture.
Two services turn Lambda functions and other AWS services into complete applications: API Gateway puts an HTTP front door in front of them, and Step Functions coordinates multi-step workflows with state, retries and error handling.
API Gateway
API Gateway is a managed service for publishing APIs: it terminates TLS, authenticates and throttles requests, transforms them if needed, and forwards them to a backend (integration).
Three API types
| HTTP API | REST API | WebSocket API | |
|---|---|---|---|
| Positioning | Simple, fast, cheaper | Full-featured | Two-way real-time |
| Auth | IAM, JWT (Cognito or any OIDC), Lambda authorisers | IAM, Cognito, Lambda authorisers, API keys | IAM, Lambda authoriser on connect |
| Extras | Auto-deploy, CORS built in | Usage plans and API keys, request validation, mapping templates, caching, WAF, private APIs, edge-optimised endpoints | Routes on message content; push to clients via the connection ID |
| Choose when | Most new Lambda/HTTP backends | You need its specific features | Chat, live dashboards, games (WebSockets) |
Integrations: Lambda (proxy integration passes the whole request as an event), HTTP backends, private resources in a VPC through VPC Link (an ALB/NLB or Cloud Map), and direct AWS service integrations — e.g. POST /events writes straight to SQS or EventBridge with no Lambda at all.
Security and protection
- Authorisers: IAM (SigV4-signed calls between services), JWT authorisers validating tokens from Cognito, Auth0 or Okta, or Lambda authorisers for custom logic (with cached results) (Authentication).
- Amazon Cognito user pools provide sign-up, sign-in, MFA, social and SAML federation, and issue the JWTs.
- Throttling: account-level and per-route rate and burst limits (token bucket); clients receive
429 Too Many Requests(Rate limiting). REST APIs add usage plans with API keys for per-customer quotas — keys identify clients, they are not authentication. - WAF in front of REST APIs; mutual TLS on custom domains.
Operational details
- Stages (
dev,prod) with stage variables; custom domains with ACM certificates and base-path mappings for versioning (api.example.com/v2) (API design). - Integration timeout defaults to 29 seconds — long-running work should be asynchronous: accept the request, enqueue it, return
202 Acceptedwith a status URL. - Access logs and metrics (count, 4xx, 5xx, latency vs integration latency) in CloudWatch; X-Ray tracing.
Simpler alternatives
Lambda function URLs give a function its own HTTPS endpoint with IAM or no auth — fine for webhooks and simple services. An ALB can also invoke Lambda. Reach for API Gateway when you need authorisers, throttling, multiple routes and backends, or direct service integrations.
Step Functions
Business processes span many steps — charge a card, reserve stock, create a shipment, email the customer — each of which can fail. Chaining Lambdas that call each other hides the flow, loses state on failure and makes retries ad hoc. Step Functions makes the workflow explicit: a state machine defined in JSON (Amazon States Language) or visually in Workflow Studio, with every execution's state and history recorded.
States
| State | Purpose |
|---|---|
| Task | Do work: invoke Lambda, or call one of 200+ AWS services directly via SDK integrations (DynamoDB PutItem, ECS RunTask, Bedrock InvokeModel, SNS Publish) |
| Choice | Branch on data |
| Parallel | Run branches concurrently, wait for all |
| Map | Run steps for each item in an array — or Distributed Map over millions of S3 objects |
| Wait | Pause for a duration or until a timestamp |
| Pass, Succeed, Fail | Shape data, end the execution |
Error handling built in
"ChargeCard": {
"Type": "Task",
"Resource": "arn:aws:states:::lambda:invoke",
"Parameters": { "FunctionName": "charge-card", "Payload.$": "$" },
"Retry": [{
"ErrorEquals": ["PaymentGateway.Timeout", "Lambda.TooManyRequestsException"],
"IntervalSeconds": 2, "BackoffRate": 2.0, "MaxAttempts": 4, "JitterStrategy": "FULL"
}],
"Catch": [{ "ErrorEquals": ["States.ALL"], "ResultPath": "$.error", "Next": "RefundAndRelease" }],
"Next": "CreateShipment"
}Retry with exponential backoff and jitter for transient errors; Catch routes permanent failures to compensation steps (Reliability patterns).
Waiting for people and systems
The .waitForTaskToken pattern pauses an execution — for hours, days, up to a year in Standard workflows — until an external system (a warehouse, a human approval email) calls SendTaskSuccess with the token. The .sync pattern waits for a job (ECS task, Glue job, nested workflow) to finish.
Standard vs Express
| Standard | Express | |
|---|---|---|
| Max duration | 1 year | 5 minutes |
| Semantics | Exactly-once step execution | At-least-once (async) or at-most-once (sync) |
| History | Full visual history per execution | CloudWatch Logs |
| Pricing | Per state transition | Per execution, duration and memory |
| Use | Long-running business processes, human approvals | High-volume, short event processing, API orchestration |
The saga pattern
Distributed transactions across services can't use a single database transaction. A saga runs local steps in sequence and, if one fails, runs compensating actions for the completed steps in reverse — refund the payment, release the stock. Step Functions is a natural orchestrator for sagas: the flow, retries and compensations are visible in one place (Distributed transactions).
A serverless reference architecture
No servers to patch, scales to zero, pay per request — and each piece can be defined in a few dozen lines of CDK.
QHTTP API or REST API in API Gateway?medium
Choose HTTP APIs by default: they're lower latency, cheaper and simpler, with built-in JWT authorisers, Lambda and HTTP integrations, and CORS. Choose REST APIs when you need features only they have: usage plans with API keys for per-client quotas, request validation and mapping templates, response caching, AWS WAF integration, private APIs accessible only from a VPC, or edge-optimised endpoints.
QWhy use Step Functions instead of having Lambda functions call each other?medium
Chained functions couple services, pay for idle waiting, lose state on failure and spread retry logic everywhere, making the flow hard to see and debug. Step Functions makes the workflow explicit with durable state, built-in retries with backoff, catches that route to compensation, parallelism, waits up to a year and callback patterns, plus a visual history of every execution. It can also call many AWS services directly without Lambda glue code.
QHow would you handle an API request that takes several minutes to process?medium
Don't hold the HTTP request open — API Gateway's integration timeout is around 29 seconds by default and clients and proxies time out too. Accept the request, validate it, store a job record and enqueue the work (SQS, EventBridge or start a Step Functions execution), and return 202 Accepted with a job ID and status URL. The client polls the status endpoint or receives a webhook or WebSocket notification when the job completes.
- API Gateway HTTP APIs are the default for Lambda backends; REST APIs add usage plans, validation, caching, WAF and private APIs; WebSocket APIs handle real-time.
- Authenticate with IAM, JWT authorisers (Cognito or OIDC) or Lambda authorisers; throttle with rate and burst limits.
- Integrations can call AWS services directly; long-running work should be asynchronous with 202 responses.
- Step Functions make workflows explicit with durable state, retries, catches, parallelism, maps and callbacks.
- Standard workflows suit long, exactly-once business processes; Express suits high-volume short ones.
- Step Functions is a natural orchestrator for sagas with compensating actions.