Lambda, API Gateway & serverless patterns
Design an event-driven serverless API and know Lambda's limits.
By Invicly Tech, , in AWS Solutions Architect – Associate. About 12 minutes to read.
In short
Lambda runs your code in response to events without servers, billed per request and duration. API Gateway turns Lambda functions into HTTP APIs, and services like S3, SQS and EventBridge trigger functions automatically. Knowing Lambda limits helps you spot when serverless does not fit.
Explained simply
Serverless means you write code and AWS runs it, without you creating or looking after servers. With AWS Lambda, you upload a function, choose what should trigger it, and AWS starts as many copies as needed. When nothing is happening, nothing runs and you pay nothing.
Lambda functions are triggered by events. An event can be an HTTP request through API Gateway, a file landing in S3, a message in an SQS queue, or a schedule such as every night at 2 am. The function gets the event as input, does its work, and returns.
Amazon API Gateway is the front door for serverless web APIs. It receives HTTPS requests, checks who is calling, limits how fast they can call, and passes the request to Lambda. Lambda then talks to a database such as DynamoDB, and the answer flows back.
Lambda has limits you must know: a single run can last at most 15 minutes, memory is capped, and by default an account can run 1,000 copies at once per Region. Long jobs, very heavy compute or apps needing a constantly open connection usually belong on containers instead.
Press Play on a diagram to walk through it one step at a time.
- Step 1Client
Sends HTTPS request.
- Step 2API Gateway
Auth, throttling, routing and request validation.
- Step 3Lambda
Runs the handler; scales per request.
- Step 4DynamoDB
Stores and returns data.
- S3 bucket to SQS queue: ObjectCreated event1ObjectCreated event
- Lambda to SQS queue: Poll a batch of messages2Poll a batch of messages
- Lambda to DynamoDB: Write processed results3Write processed results
- Lambda to SQS queue: Delete batch on success4Delete batch on success
- 1Route 53 and CloudFront
Custom domain, TLS and caching at the edge.
- 2API Gateway
Auth, throttling, validation, routing.
- 3Lambda
Business logic, one function per route or domain.
- 4Data and messaging
DynamoDB, S3, SQS, EventBridge.
- 5Observability
CloudWatch Logs, metrics, alarms, X-Ray traces.
In depth
How Lambda runs your code
Each function copy runs in an execution environment, a lightweight microVM. On the first request, Lambda creates one: it downloads your code, starts the runtime, and runs everything outside your handler, such as imports and SDK client setup. This init phase is the cold start. Then it calls your handler with the event.
After the response, the environment is frozen and kept for a while. The next request can reuse it, skipping init: a warm start. Anything created outside the handler, such as database connections, and files in /tmp survive between warm invocations, so create clients once, outside the handler.
Each environment handles one request at a time. If ten requests arrive at once, Lambda runs ten environments. That number is concurrency, and it is roughly requests per second times average duration in seconds. Environments are eventually shut down, so never rely on local state.
- 1Init
Load code and runtime, run setup code.
- 2Invoke
Handler processes one event.
- 3Freeze
Paused between requests.
- 4Thaw and reuse
Warm start, setup skipped.
- 5Shutdown
Removed after idle time or update.
- Back to step 1
Three ways Lambda is invoked
Synchronous invocation: the caller waits for the result. API Gateway, Application Load Balancers, function URLs and direct SDK calls work this way. Errors go straight back to the caller, who must decide whether to retry.
Asynchronous invocation: the caller hands over the event and moves on. S3, SNS and EventBridge use this. Lambda puts the event in an internal queue, retries failed runs twice by default, and keeps events for up to six hours. Configure an on-failure destination or a dead-letter queue so failed events are not silently lost.
Event source mapping: Lambda itself polls a source and invokes your function with batches. This is used for SQS, Kinesis Data Streams, DynamoDB Streams and Kafka. Batch size, batching window and error handling are set on the mapping. For SQS, a failed batch returns to the queue after the visibility timeout; for streams, failures block that shard until they succeed or expire, unless you configure bisecting or a failure destination.
- Caller waits for result
- API Gateway, ALB, function URL
- Caller handles retries
- Errors returned directly
- Fire and forget
- S3, SNS, EventBridge
- 2 retries by default
- Destinations or DLQ for failures
- Lambda polls the source
- SQS, Kinesis, DynamoDB Streams
- Batches of records
- Retry rules per source
Limits and concurrency controls
The key limits: timeout up to 900 seconds (15 minutes); memory from 128 MB to 10,240 MB, with CPU added in proportion (about one full vCPU at 1,769 MB); /tmp storage from 512 MB to 10,240 MB; a 50 MB zipped upload or 250 MB unzipped including up to five layers; container images up to 10 GB; environment variables up to 4 KB; synchronous request and response payloads up to 6 MB.
Each Region starts with 1,000 concurrent executions shared by all functions in the account, which you can ask to raise. Each function can scale up by 1,000 concurrent executions every 10 seconds. Reserved concurrency sets aside capacity for one function and also caps it, which protects a database from too many connections; setting it to 0 stops the function. Provisioned concurrency keeps environments initialized for no cold starts, at an extra cost. SnapStart, for Java, Python and .NET, restores a snapshot of an initialized environment to cut cold starts cheaply.
- Max timeout 15 minutes
- Memory 128 MB to 10,240 MB; CPU scales with it
- 1,000 concurrent executions per Region by default
- Reserved concurrency: guarantee and cap
- Provisioned concurrency: no cold starts, extra cost
API Gateway choices
API Gateway has three API types. REST APIs have the most features: API keys and usage plans for selling or metering access, request validation, response caching, AWS WAF integration, private APIs reachable only from a VPC, and edge-optimized endpoints. HTTP APIs are simpler, cheaper and faster, with native JWT authorizers for OIDC providers such as Cognito, but fewer features. WebSocket APIs keep a two-way connection open for chat or live dashboards.
Authorization options include IAM (signed requests), Cognito user pools, JWT authorizers on HTTP APIs, and Lambda authorizers for custom logic. Throttling defaults to 10,000 requests per second per account per Region with a burst of 5,000, and you can set lower limits per stage, route or client.
The integration timeout is 29 seconds by default for REST APIs and 30 seconds for HTTP APIs. Anything longer should become asynchronous: accept the request, put work on a queue, and let the client check for the result.
- Usage plans and API keys
- Request validation and caching
- WAF and private endpoints
- Higher price per request
- Lower cost and latency
- Native JWT authorizers
- Simpler setup
- Fewer features
Event-driven patterns that work
Put a queue between producers and Lambda when traffic is bursty or downstream systems are fragile. SQS absorbs spikes, and Lambda drains it at a controlled rate. Set the queue's visibility timeout to at least six times the function timeout, configure a dead-letter queue with a maxReceiveCount, and return partial batch failures so one bad message does not force the whole batch to retry.
Design for at-least-once delivery. S3 events, SQS and SNS can deliver the same event twice, so make handlers idempotent: processing an event twice must give the same result, for example by using a conditional write keyed on the event ID.
Avoid recursive loops, such as a function that writes into the same bucket and prefix that triggers it. Use separate buckets or prefixes. For workflows longer than 15 minutes or with many steps, use Step Functions to orchestrate. For relational databases, use RDS Proxy so thousands of function copies share a small pool of connections.
- API backend
- API Gateway
- Lambda
- DynamoDB
- File processing
- S3 event
- SQS buffer
- Lambda batch
- Fan-out
- SNS topic
- Several SQS queues
- One function each
- Scheduled job
- EventBridge Scheduler
- Lambda
- Long workflow
- Step Functions
- Lambda per step
- Retries and waits
Learn it in 5 short steps
About 50m each. Track them with a timer in your plan.
- 1Write and deploy a Lambda function~50m
- 2Front Lambda with API Gateway~50m
- 3Trigger Lambda from S3 and SQS~50m
- 4Know Lambda limits and concurrency~50m
- 5Design an event-driven serverless API~50m
Key points
- Max timeout is 15 minutes; longer jobs belong on ECS, Batch or Step Functions.
- Memory ranges 128 MB to 10,240 MB, and CPU scales with memory.
- Default concurrency quota is 1,000 per Region; reserved concurrency caps a function.
- Provisioned concurrency removes cold starts for latency-sensitive APIs.
- Put SQS between producers and Lambda to buffer bursts and retry failures.
Key terms
Tap a card to flip it. 0/5 known
Examples
import json, boto3
table = boto3.resource("dynamodb").Table("orders")
def handler(event, context):
body = json.loads(event["body"])
table.put_item(Item={"id": body["id"], "total": body["total"]})
return {"statusCode": 201, "body": json.dumps({"ok": True})}Lambda handler behind API Gateway writing to DynamoDB.
SQS worker with partial batch failures
Orders arrive on an SQS queue and a Lambda function processes them in batches of 10. Step 1: create the event source mapping with --batch-size 10 and --function-response-types ReportBatchItemFailures. Step 2: in the handler, process each record separately and collect the message IDs that fail. Step 3: return them in batchItemFailures; Lambda deletes the successful messages and only the failed ones become visible again. Step 4: after maxReceiveCount attempts, SQS moves a poison message to the dead-letter queue, where an alarm alerts the team.
import json
def process(order):
if "id" not in order:
raise ValueError("missing id")
# write to DynamoDB with a condition on order id (idempotent)
def handler(event, context):
failures = []
for record in event["Records"]:
try:
process(json.loads(record["body"]))
except Exception:
failures.append({"itemIdentifier": record["messageId"]})
return {"batchItemFailures": failures}Will Lambda's concurrency be enough?
An API handles 500 requests per second normally, each taking 200 ms. Step 1: concurrency is 500 times 0.2, so about 100 environments, far below the 1,000 default. Step 2: on sale days, traffic reaches 3,000 requests per second and a slower database pushes duration to 400 ms: 3,000 times 0.4 is 1,200, above the default quota, so some requests would be throttled. Step 3: request a quota increase well before the sale. Step 4: give the checkout function reserved concurrency so other functions cannot starve it. Step 5: put RDS Proxy in front of the database, since 1,200 direct connections would overwhelm it, and add provisioned concurrency for the checkout path to avoid cold starts at peak.
Quick reference
- Timeout max 15 minutes; memory 128 MB to 10,240 MB; /tmp up to 10,240 MB
- Package: 50 MB zipped upload, 250 MB unzipped with layers; images up to 10 GB
- Concurrency is about requests per second times average duration in seconds
- Default 1,000 concurrent executions per Region; each function scales 1,000 per 10 s
- Async invokes retry twice by default; add an on-failure destination or DLQ
- SQS visibility timeout should be at least 6 times the function timeout
- API Gateway default integration timeout: 29 s for REST, 30 s for HTTP APIs
- Many functions hitting a relational database: use RDS Proxy
Common mistakes
- Choosing Lambda for a 2-hour batch job; it stops at 15 minutes.
- Creating DB connections inside the handler on every call; reuse them or use RDS Proxy.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Deploy a Python function called hello from a zip file and invoke it with a small JSON payload.
- Exercise 2medium
Put an HTTP API in front of the hello function and call it with curl.
- Exercise 3hard
Cap a batch function called report at 5 concurrent runs, and keep 20 warm environments for the live alias of a function called api.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- How much does Lambda cost?
- You pay per request and per GB-second of run time. The free tier includes 1 million requests and 400,000 GB-seconds per month, which covers many small apps.
- Can Lambda functions access resources in my VPC?
- Yes. Attach the function to private subnets and security groups. It can then reach RDS or ElastiCache, but needs a NAT gateway or VPC endpoints to reach the internet or AWS APIs.
- How long is a cold start?
- It depends on runtime, package size and setup code, often from about a hundred milliseconds to a few seconds. Smaller packages, lighter setup, SnapStart or provisioned concurrency reduce it.
- When should I not use Lambda?
- For jobs over 15 minutes, steady high-throughput workloads where containers are cheaper, apps needing GPUs, or software that needs a long-lived server process.