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.

Intermediate 6 min readLesson 14 of 19 Interview Q&A

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 APIREST APIWebSocket API
PositioningSimple, fast, cheaperFull-featuredTwo-way real-time
AuthIAM, JWT (Cognito or any OIDC), Lambda authorisersIAM, Cognito, Lambda authorisers, API keysIAM, Lambda authoriser on connect
ExtrasAuto-deploy, CORS built inUsage plans and API keys, request validation, mapping templates, caching, WAF, private APIs, edge-optimised endpointsRoutes on message content; push to clients via the connection ID
Choose whenMost new Lambda/HTTP backendsYou need its specific featuresChat, 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 Accepted with 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.

yesnoStartValidate orderLambdaParallelreserve stock · charge cardChoiceboth succeeded?Create shipmentSQS + wait for callbackCompensaterefund · release stockFail

States

StatePurpose
TaskDo work: invoke Lambda, or call one of 200+ AWS services directly via SDK integrations (DynamoDB PutItem, ECS RunTask, Bedrock InvokeModel, SNS Publish)
ChoiceBranch on data
ParallelRun branches concurrently, wait for all
MapRun steps for each item in an array — or Distributed Map over millions of S3 objects
WaitPause for a duration or until a timestamp
Pass, Succeed, FailShape data, end the execution

Error handling built in

JSON
"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

StandardExpress
Max duration1 year5 minutes
SemanticsExactly-once step executionAt-least-once (async) or at-most-once (sync)
HistoryFull visual history per executionCloudWatch Logs
PricingPer state transitionPer execution, duration and memory
UseLong-running business processes, human approvalsHigh-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

CloudFront + S3web appCognitosign-in, JWTAPI GatewayHTTP API + JWT authLambdabusiness logicDynamoDBEventBridgeOrderPlacedStep Functionsfulfilment saga

No servers to patch, scales to zero, pay per request — and each piece can be defined in a few dozen lines of CDK.

Interview questions
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.

Key takeaways
  • 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.