AWS Lambda and Serverless Compute: Functions, Triggers, Concurrency, Layers, Limits and Best Practices

AWS Solutions Architect 45 min min read Updated: Nov 17, 2026 Intermediate
AWS Lambda and Serverless Compute: Functions, Triggers, Concurrency, Layers, Limits and Best Practices
Intermediate Topic 3 of 4

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.

EC2Lambda
You manage OS, patches, scalingAWS manages everything below your code
Pay while the instance runs (even idle)Pay per request and per millisecond used
Good for long, steady workloadsGood for event-driven, spiky, short tasks
Any software, any durationLimited 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

TriggerStyleExample
API Gateway / ALB / Function URLSynchronousREST or HTTP API calls a function
S3 eventAsynchronousImage uploaded, create a thumbnail
SNS / EventBridgeAsynchronousRun a function on a schedule or an event rule
SQSPolling (event source mapping)Process a queue in batches
DynamoDB Streams / KinesisPolling (stream)React to data changes
Cognito, CloudFront (Lambda@Edge / functions), Step FunctionsVariousCustom auth, edge logic, workflows
Invocation typeBehaviorErrors
SynchronousCaller waits for the resultCaller handles errors and retries
AsynchronousLambda queues the event, returns at onceLambda retries twice; send failures to a DLQ or on-failure destination
Event source mapping (poll)Lambda reads batches from SQS, Kinesis or DynamoDBBatch 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.

SettingMeaningUse for
Account concurrency limitDefault 1,000 per Region (can be raised)Shared by all functions in the Region
Reserved concurrencyGuarantees AND caps a number for one functionProtect a database from too many connections, or guarantee capacity for a critical function. Set to 0 to stop a function
Provisioned concurrencyKeeps environments pre-initialized (costs money)Remove cold-start latency for APIs
SnapStart (supported runtimes)Snapshot of initialized state for faster startsJava 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

PartHow it is charged
RequestsPer million requests (a free monthly allowance exists)
DurationGB-seconds: memory times time, billed per millisecond
Provisioned concurrencyExtra per GB-second kept ready
Ephemeral storage, data transferBeyond the free amounts

When to Use Lambda (and When Not)

Good fitPoor fit
Event processing (S3, queues, streams)Jobs longer than 15 minutes (use ECS Fargate, Batch or Step Functions)
Spiky or low traffic APIsConstant high traffic where EC2 or containers are cheaper
Glue code, scheduled tasks, automationNeeds special hardware (GPU) or very large memory
Prototypes and small microservicesApps needing long-lived connections or local state

Best Practices

  1. Keep functions small and single-purpose
  2. Initialize SDK clients outside the handler
  3. Make handlers idempotent: events can be delivered more than once
  4. Use a DLQ or destination for failures
  5. Give least-privilege roles
  6. Use structured logs, X-Ray tracing and CloudWatch alarms on Errors, Throttles, Duration
  7. Deploy with SAM, CDK or CloudFormation, not by clicking

Practice Tasks

  1. Create a function that returns a greeting through a Function URL
  2. Add an S3 trigger that writes the uploaded object's name to a DynamoDB table
  3. Set reserved concurrency to 1 and invoke it in parallel to see throttling
  4. Create an alias prod with 10 percent traffic to a new version
  5. 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.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators