AWS Lambda and Serverless Compute: Functions, Triggers, Concurrency, Layers, Limits and Best Practices
What Is Serverless?
Serverless does not mean no servers. It means you do not manage them. You upload code, AWS runs it when an event happens, scales it automatically, and you pay only for the time it runs.
| EC2 | Lambda |
| You manage OS, patches, scaling | AWS manages everything below your code |
| Pay while the instance runs (even idle) | Pay per request and per millisecond used |
| Good for long, steady workloads | Good for event-driven, spiky, short tasks |
| Any software, any duration | Limited to 15 minutes per run and size limits |
A First Function
python
# lambda_function.py
import json, os, boto3
s3 = boto3.client("s3") # created outside the handler: reused on warm starts
BUCKET = os.environ["BUCKET"]
def handler(event, context):
name = event.get("queryStringParameters", {}) or {}
who = name.get("name", "world")
s3.put_object(Bucket=BUCKET, Key=f"hits/{context.aws_request_id}.txt", Body=who.encode())
return {"statusCode": 200,
"headers": {"Content-Type": "application/json"},
"body": json.dumps({"message": f"Hello, {who}!"})}
bash
zip function.zip lambda_function.py
aws lambda create-function --function-name hello --runtime python3.13 --handler lambda_function.handler \
--zip-file fileb://function.zip --role arn:aws:iam::123456789012:role/lambda-hello-role \
--memory-size 256 --timeout 10 --environment Variables={BUCKET=acme-hits}
aws lambda invoke --function-name hello --payload '{"queryStringParameters":{"name":"Asha"}}' --cli-binary-format raw-in-base64-out out.json && cat out.json
aws lambda create-function-url-config --function-name hello --auth-type AWS_IAM
Check runtimes: Supported runtime versions change often. Use a currently supported runtime and check the Lambda runtimes page before deploying.
Execution Role
A Lambda function runs with an execution role: it needs the trust policy for lambda.amazonaws.com and permissions for what it calls. At minimum attach AWSLambdaBasicExecutionRole so it can write logs to CloudWatch Logs. Add only the S3, DynamoDB or other actions the function needs.
Triggers and Event Sources
| Trigger | Style | Example |
| API Gateway / ALB / Function URL | Synchronous | REST or HTTP API calls a function |
| S3 event | Asynchronous | Image uploaded, create a thumbnail |
| SNS / EventBridge | Asynchronous | Run a function on a schedule or an event rule |
| SQS | Polling (event source mapping) | Process a queue in batches |
| DynamoDB Streams / Kinesis | Polling (stream) | React to data changes |
| Cognito, CloudFront (Lambda@Edge / functions), Step Functions | Various | Custom auth, edge logic, workflows |
| Invocation type | Behavior | Errors |
| Synchronous | Caller waits for the result | Caller handles errors and retries |
| Asynchronous | Lambda queues the event, returns at once | Lambda retries twice; send failures to a DLQ or on-failure destination |
| Event source mapping (poll) | Lambda reads batches from SQS, Kinesis or DynamoDB | Batch retried until it succeeds or expires. Use partial batch response and DLQ / redrive |
Memory, CPU, Timeout
- Memory: 128 MB to 10,240 MB. CPU grows with memory (about one vCPU at 1,769 MB). More memory can make the function faster and sometimes cheaper. Use AWS Lambda Power Tuning to find the best value
- Timeout: up to 15 minutes
- Ephemeral storage
/tmp: 512 MB default, up to 10 GB
- Payload: 6 MB synchronous, 256 KB asynchronous
- Deployment package: 50 MB zipped (direct upload), 250 MB unzipped including layers; container image up to 10 GB
Concurrency and Cold Starts
Concurrency is the number of function instances running at once. Each concurrent request needs its own execution environment. A new environment must be created and initialized, which is the cold start. Reused environments are warm.
| Setting | Meaning | Use for |
| Account concurrency limit | Default 1,000 per Region (can be raised) | Shared by all functions in the Region |
| Reserved concurrency | Guarantees AND caps a number for one function | Protect a database from too many connections, or guarantee capacity for a critical function. Set to 0 to stop a function |
| Provisioned concurrency | Keeps environments pre-initialized (costs money) | Remove cold-start latency for APIs |
| SnapStart (supported runtimes) | Snapshot of initialized state for faster starts | Java and some other runtimes with slow init |
bash
aws lambda put-function-concurrency --function-name hello --reserved-concurrent-executions 50
aws lambda put-provisioned-concurrency-config --function-name hello --qualifier prod --provisioned-concurrent-executions 10
- Reduce cold starts: smaller packages, lazy imports, avoid heavy init, choose faster runtimes, use arm64 (Graviton) which is cheaper
- Throttling happens when concurrency is exceeded: synchronous callers get a 429, async events are retried
Versions, Aliases, Layers, Containers
- Version: an immutable snapshot. Alias: a pointer like
prod that can split traffic 90/10 between versions for canary releases
- Layers: shared libraries or runtimes, up to 5 per function, count toward the size limit
- Container image functions: package up to 10 GB with your own dependencies, from ECR
- Environment variables: encrypted with KMS, good for config. Use Secrets Manager for secrets
Lambda in a VPC
- By default a function runs in an AWS-managed network with internet access but cannot reach private resources like an RDS in your VPC
- Attach it to VPC subnets and a security group to reach RDS, ElastiCache or internal services
- A VPC function has no internet access unless the subnet routes through a NAT Gateway (or use VPC endpoints for AWS services like S3 and DynamoDB)
- Many connections to RDS can overload it: use RDS Proxy
Pricing in Short
| Part | How it is charged |
| Requests | Per million requests (a free monthly allowance exists) |
| Duration | GB-seconds: memory times time, billed per millisecond |
| Provisioned concurrency | Extra per GB-second kept ready |
| Ephemeral storage, data transfer | Beyond the free amounts |
When to Use Lambda (and When Not)
| Good fit | Poor fit |
| Event processing (S3, queues, streams) | Jobs longer than 15 minutes (use ECS Fargate, Batch or Step Functions) |
| Spiky or low traffic APIs | Constant high traffic where EC2 or containers are cheaper |
| Glue code, scheduled tasks, automation | Needs special hardware (GPU) or very large memory |
| Prototypes and small microservices | Apps needing long-lived connections or local state |
Best Practices
- Keep functions small and single-purpose
- Initialize SDK clients outside the handler
- Make handlers idempotent: events can be delivered more than once
- Use a DLQ or destination for failures
- Give least-privilege roles
- Use structured logs, X-Ray tracing and CloudWatch alarms on
Errors, Throttles, Duration
- Deploy with SAM, CDK or CloudFormation, not by clicking
Practice Tasks
- Create a function that returns a greeting through a Function URL
- Add an S3 trigger that writes the uploaded object's name to a DynamoDB table
- Set reserved concurrency to 1 and invoke it in parallel to see throttling
- Create an alias
prod with 10 percent traffic to a new version
- Change the memory from 128 MB to 1,024 MB and compare duration and cost
Conclusion
Lambda runs event-driven code with no servers: pay per request and millisecond, scale automatically up to account concurrency, run up to 15 minutes. Know synchronous vs asynchronous vs polling triggers, reserved vs provisioned concurrency, VPC and NAT rules, and use idempotent, least-privilege, well-monitored functions.
Quick Summary: serverless vs EC2; handler + CLI; execution role; triggers + invocation types; limits; concurrency types + cold start; aliases/layers; VPC + NAT; pricing; fit/poor fit; best practices.