Lambda — Serverless Functions
AWS Lambda in depth — the execution model, invocation types (synchronous, asynchronous, event source mappings), cold starts and how to reduce them, concurrency, memory and CPU, limits, the execution role, packaging with layers and container images, error handling with retries and DLQs, idempotency, and when not to use Lambda.
AWS Lambda runs your code in response to events without you managing servers. You upload a function, choose memory, and AWS runs as many copies as there are concurrent events — from zero to thousands — billing per request and per millisecond of execution. The general serverless model is covered in Serverless and edge; here's how Lambda actually behaves.
A function
# handler.py — invoked as handler.lambda_handler
import json, os, boto3
table = boto3.resource("dynamodb").Table(os.environ["TABLE"]) # created once per execution environment
def lambda_handler(event, context):
order = json.loads(event["body"])
table.put_item(Item={"pk": f"ORDER#{order['id']}", "total": order["total"]})
return {"statusCode": 201, "body": json.dumps({"id": order["id"]})}// index.ts — invoked as index.handler
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient, PutCommand } from "@aws-sdk/lib-dynamodb";
import type { APIGatewayProxyHandlerV2 } from "aws-lambda";
const db = DynamoDBDocumentClient.from(new DynamoDBClient({})); // reused across invocations
export const handler: APIGatewayProxyHandlerV2 = async (event) => {
const order = JSON.parse(event.body ?? "{}");
await db.send(new PutCommand({ TableName: process.env.TABLE, Item: { pk: `ORDER#${order.id}`, total: order.total } }));
return { statusCode: 201, body: JSON.stringify({ id: order.id }) };
};public class Handler implements RequestHandler<APIGatewayV2HTTPEvent, APIGatewayV2HTTPResponse> {
private static final DynamoDbClient DB = DynamoDbClient.create(); // static: reused while warm
@Override
public APIGatewayV2HTTPResponse handleRequest(APIGatewayV2HTTPEvent event, Context ctx) {
Order order = Json.parse(event.getBody(), Order.class);
DB.putItem(r -> r.tableName(System.getenv("TABLE")).item(order.toItem()));
return APIGatewayV2HTTPResponse.builder().withStatusCode(201).build();
}
}Note the pattern in every language: create clients outside the handler. That code runs once per execution environment and is reused by later invocations.
The execution model
- Each execution environment is a Firecracker micro-VM that handles one request at a time. Ten simultaneous requests need ten environments.
- After an invocation the environment is frozen and may be reused for minutes — globals,
/tmpcontents and open connections survive. Never rely on it, but exploit it for caching. - Cold start = creating a new environment and running your init code. Typically ~100 ms–1 s for Node and Python, longer for the JVM or large packages, plus any VPC or heavyweight initialisation you do.
Reducing cold starts
| Technique | Effect |
|---|---|
| Smaller packages, fewer dependencies, lazy imports | Faster load and init |
| More memory | Proportionally more CPU, so init runs faster |
| SnapStart (Java, Python, .NET) | Snapshots the initialised environment and restores it |
| Provisioned concurrency | Keeps N environments initialised — no cold starts, but you pay for them |
| Lighter runtimes (Node, Python, Go/Rust on custom runtime) | Smaller startup overhead |
For most asynchronous workloads cold starts don't matter; for user-facing APIs with strict p99 targets they might.
Memory, CPU and limits
You set memory from 128 MB to 10,240 MB; CPU is allocated proportionally (about one full vCPU at 1,769 MB, up to 6 vCPUs at the top). A CPU-bound function often costs the same or less with more memory because it finishes faster — measure with Lambda Power Tuning.
| Limit | Value |
|---|---|
| Maximum duration | 15 minutes |
| Memory | 128 MB – 10,240 MB |
Ephemeral /tmp storage | 512 MB default, up to 10 GB |
| Synchronous request/response payload | 6 MB each way |
| Deployment package | 50 MB zipped direct upload, 250 MB unzipped; container images up to 10 GB |
| Concurrency | Account-level regional quota (commonly 1,000 to start; can be raised) |
Invocation types
| Type | Who waits | Retries | Examples |
|---|---|---|---|
| Synchronous | The caller waits for the result | Caller's responsibility | API Gateway, ALB, function URLs, SDK Invoke |
| Asynchronous | Lambda queues the event and returns 202 | Lambda retries 2 more times with backoff; then on-failure destination or DLQ | S3 notifications, SNS, EventBridge |
| Event source mapping | Lambda polls the source and invokes with batches | Per source: retried until success or expiry; partial batch failures supported | SQS, Kinesis, DynamoDB Streams, Kafka |
With SQS, a failing batch becomes visible again after the visibility timeout and eventually moves to the queue's dead-letter queue. With Kinesis and DynamoDB Streams, a poison record blocks its shard until it succeeds or expires — configure bisect-on-error, maximum retry attempts and an on-failure destination.
Idempotency is mandatory
Every invocation type can deliver the same event more than once (retries, at-least-once queues). Make handlers idempotent: use a natural idempotency key (order ID, message ID) and a conditional write — put_item with ConditionExpression="attribute_not_exists(pk)" in DynamoDB — or a library like Powertools for AWS Lambda's idempotency utility (Message queues).
Concurrency
Concurrency is the number of environments busy at once: roughly requests per second × average duration in seconds. 500 requests/s at 200 ms needs about 100.
- Reserved concurrency guarantees capacity for a function and caps it — use it to stop a runaway function exhausting the account limit, or to protect a fragile downstream database.
- When concurrency is exhausted, synchronous calls get 429 throttling errors; asynchronous events wait and retry.
- Lambda scales out fast — which can overwhelm a relational database with connections. Use RDS Proxy to pool them (RDS and Aurora).
Permissions, networking, packaging
- Execution role: what the function may do (write logs, read the table). Resource policy: who may invoke it (API Gateway, S3, another account) (IAM).
- VPC access: attach the function to private subnets to reach RDS or ElastiCache. It then has no internet access unless the subnet routes through a NAT gateway — prefer VPC endpoints for AWS services.
- Configuration: environment variables (encrypted at rest); secrets from Secrets Manager or Parameter Store fetched at init and cached.
- Packaging: zip archives, layers for shared dependencies, or container images for large or complex dependencies.
- Versions and aliases: publish immutable versions; point a
livealias at one and shift traffic gradually (10% to the new version) for safe deploys.
Observability
Logs go to CloudWatch Logs automatically. Emit structured JSON logs, use Embedded Metric Format for custom metrics, and enable X-Ray or OpenTelemetry tracing. Watch Errors, Throttles, Duration (p99), ConcurrentExecutions, and IteratorAge for stream sources (CloudWatch).
When Lambda fits — and when it doesn't
- Event processing: S3 uploads, queue messages, streams, webhooks
- Spiky or low-traffic APIs that sit idle much of the time
- Scheduled jobs and glue between AWS services
- Teams that want zero server management
- Jobs longer than 15 minutes
- Steady, high-throughput traffic (containers are often cheaper)
- Long-lived connections or large in-memory state
- Strict low-latency requirements where cold starts hurt
- GPU workloads
QWhat is a Lambda cold start and how can you reduce it?medium
A cold start happens when no idle execution environment is available, so Lambda must create a micro-VM, download the code, start the runtime and run initialisation code before the handler. Reduce it with smaller deployment packages and fewer dependencies, lazy loading, more memory (more CPU for init), lightweight runtimes, SnapStart for Java, Python and .NET, or provisioned concurrency for latency-critical paths. Reusing clients and connections declared outside the handler also makes subsequent warm invocations fast.
QHow do retries work for asynchronous Lambda invocations versus SQS triggers?hard
For asynchronous invocations, Lambda queues the event internally and retries a failed invocation up to two more times with backoff (configurable, along with a maximum event age); after that the event goes to an on-failure destination or dead-letter queue. With an SQS event source mapping, Lambda polls the queue and invokes with batches; if the function fails, the messages become visible again after the visibility timeout and are retried until the queue's maxReceiveCount sends them to the queue's DLQ. Reporting partial batch failures avoids reprocessing successful messages.
QYour Lambda function is overwhelming the database during traffic spikes. What do you do?medium
Limit concurrency with reserved concurrency so only N copies can run; put a queue (SQS) between the traffic and the function to absorb bursts and control the consumer rate with maximum concurrency on the event source mapping; use RDS Proxy to pool and share database connections; and cache reads where possible. If the load is steady and high, consider moving the workload to containers with a fixed connection pool.
- Lambda runs one request per execution environment, reusing warm environments; initialise clients outside the handler.
- Cold starts come from creating environments; reduce them with small packages, more memory, SnapStart or provisioned concurrency.
- Memory (128 MB–10 GB) also scales CPU; max duration is 15 minutes.
- Synchronous, asynchronous and event-source-mapping invocations have different retry semantics — always configure DLQs or failure destinations.
- Events can arrive more than once, so handlers must be idempotent.
- Control concurrency to protect downstream systems; use RDS Proxy and VPC endpoints when in a VPC.