SkillSprout
Chapter 8 · Lesson 1
Intermediate
8 min read

Lambda

Overview

AWS Lambda is a serverless compute service that runs your code in response to events without you provisioning or managing servers. You upload a function (Python, Node.js, Java, .NET, Go, Ruby or a custom runtime/container image), define a trigger, and Lambda runs it on demand, scaling from zero to thousands of concurrent executions automatically.

You pay only for requests and execution time (billed in 1 ms increments by memory allocated, in GB-seconds); when nothing runs you pay nothing. Lambda handles the operating system, patching, scaling and high availability across multiple AZs, so you focus on business logic.

Lambda is the glue of AWS serverless architectures: it reacts to S3 uploads, DynamoDB changes, SQS messages, API Gateway requests, EventBridge schedules and many other sources. The exam tests its limits (15-minute timeout, memory, concurrency), invocation models, VPC access, and how to cut cold starts or protect downstream systems.

Key Concepts

  • Limits: timeout up to 15 minutes; memory 128 MB to 10,240 MB (CPU scales with memory); /tmp 512 MB to 10 GB; zip package 50 MB (250 MB unzipped), container image up to 10 GB.
  • Invocation types: synchronous (API Gateway, ALB, SDK), asynchronous (S3, SNS, EventBridge - 2 automatic retries) and event source mappings / polling (SQS, Kinesis, DynamoDB Streams).
  • Concurrency: default 1,000 concurrent executions per Region (soft limit); reserved concurrency guarantees and caps; provisioned concurrency keeps environments warm.
  • Cold starts occur when a new execution environment is created; mitigate with provisioned concurrency, SnapStart (Java, Python, .NET), smaller packages and Graviton (arm64).
  • The execution role (IAM) gives the function permission to call AWS; a resource-based policy lets services (S3, API Gateway) invoke the function.
  • VPC access: attach the function to subnets and security groups to reach private resources (RDS); add NAT Gateway or VPC endpoints for internet/AWS API access.
  • Failure handling: DLQ (SQS/SNS) or on-failure destinations for async invocations; batch item failures and DLQs for queue sources.
  • Other features: layers (up to 5), environment variables (4 KB total), versions and aliases with weighted traffic shifting, function URLs, Lambda@Edge.

Detailed Notes

How Lambda runs your code

When an event arrives, Lambda creates an execution environment (a micro-VM), loads your code, runs the init phase (imports, SDK clients) and then invokes the handler. The environment is reused for subsequent invocations (a warm start) and frozen between them, so initialise connections outside the handler.

python
import json, boto3, os

s3 = boto3.client("s3")             # initialised once per environment
BUCKET = os.environ["BUCKET"]

def handler(event, context):
    for rec in event["Records"]:    # S3 event
        key = rec["s3"]["object"]["key"]
        obj = s3.get_object(Bucket=BUCKET, Key=key)
        # ... process ...
    return {"statusCode": 200, "body": json.dumps("done")}

Limits worth memorising

SettingValue
Max timeout900 seconds (15 min)
Memory128 MB - 10,240 MB (about 6 vCPUs at max)
Ephemeral /tmp512 MB default, up to 10,240 MB
Deployment package50 MB zipped direct upload, 250 MB unzipped incl. layers, 10 GB container image
Synchronous payload6 MB request and response
Asynchronous payload256 KB (raised in 2025; still small)
Environment variables4 KB total
Concurrency1,000 per Region by default (can be raised)
Layers5 per function

Pricing is requests + GB-seconds, with a free tier of 1 M requests and 400,000 GB-seconds per month. arm64 (Graviton2) is about 20% cheaper per GB-second.

Invocation models

ModelSourcesBehaviour
SynchronousAPI Gateway, ALB, Function URL, SDK, CognitoCaller waits; you handle retries
AsynchronousS3, SNS, EventBridge, SESLambda queues the event; 2 retries, then DLQ / destination
Poll-based (event source mapping)SQS, Kinesis, DynamoDB Streams, MSKLambda polls and sends batches; failures retry the batch (until expiry)

SQS: set the queue visibility timeout to at least 6x the function timeout. For Kinesis and DynamoDB Streams, one failing record can block a shard, so use bisect-on-error, maximum retry attempts and on-failure destinations.

Concurrency and scaling

  • Reserved concurrency reserves capacity for a function and acts as its maximum - useful to protect a downstream database.
  • Provisioned concurrency pre-initialises environments for consistent low latency (you pay for it).
  • New environments scale rapidly (up to 1,000 additional concurrent executions every 10 seconds per function). When the limit is reached, synchronous calls get 429 throttling errors.

Security and networking

  • Execution role defines what the function can do; use least privilege.
  • A function attached to a VPC uses Hyperplane ENIs managed by Lambda; to reach the internet it needs a NAT Gateway; to reach S3/DynamoDB privately use gateway endpoints.
  • Store secrets in Secrets Manager / Parameter Store, not in plain environment variables; environment variables can be encrypted with KMS.
bash
aws lambda create-function --function-name thumbnailer \
  --runtime python3.12 --architectures arm64 \
  --handler app.handler --role arn:aws:iam::123456789012:role/lambda-s3-role \
  --zip-file fileb://function.zip --memory-size 512 --timeout 30

aws lambda put-function-concurrency --function-name thumbnailer \
  --reserved-concurrent-executions 100

Versions, aliases and deployment

$LATEST is mutable; published versions are immutable. Aliases (such as prod) point to versions and support weighted routing for canary releases (for example 10% to the new version), integrated with CodeDeploy for automatic rollback.

When not to use Lambda

Jobs longer than 15 minutes, steady high-throughput workloads (EC2/Fargate may be cheaper), and applications needing specialised hardware or very large memory belong on ECS/Fargate, Batch or EC2.

Real World Example

Scenario — a photo-sharing startup generates thumbnails and moderates images.

Users upload photos to an S3 bucket. Previously a fleet of EC2 workers polled a queue, idling most of the day and struggling during peak hours.

The team configures an S3 ObjectCreated event to trigger a Lambda function (Python, arm64, 1 GB memory). The function creates three thumbnail sizes and writes them to another bucket, then publishes a message to SQS for a second function that calls Amazon Rekognition for moderation. Failures after the built-in retries land in a dead-letter queue with a CloudWatch alarm. Reserved concurrency of 200 on the moderation function protects the downstream API from overload.

Costs dropped by about 80% because nothing runs during quiet hours, and the system absorbed a viral spike of 50,000 uploads per hour with no scaling work.

Architecture Diagram

Event-driven image processing with Lambda
Architecture
AWS Cloud
Users
Source bucket
Region
Thumbnail functionarm64, 1 GB
Thumbnail bucket
SQS queuebuffer
Moderation functionreserved: 200
Results table
Dead-letter queuefailed events
CloudWatch alarm

S3 events trigger Lambda asynchronously; SQS buffers work and failures go to a dead-letter queue.

  1. 1A user uploads an image to the source S3 bucket (often with a presigned URL).
  2. 2S3 invokes the thumbnail Lambda function asynchronously; Lambda retries twice on error.
  3. 3The function writes thumbnails to a second bucket and enqueues a message in SQS for moderation.
  4. 4A second function polls SQS in batches, stores results in DynamoDB, and failures go to a DLQ that triggers an alarm.

Best Practices

  • ✓Initialise SDK clients and connections outside the handler so warm invocations reuse them.
  • ✓Right-size memory (use AWS Lambda Power Tuning): more memory also means more CPU and often lower total cost.
  • ✓Choose arm64 (Graviton) where possible and keep packages small; use layers for shared dependencies.
  • ✓Use provisioned concurrency or SnapStart for latency-sensitive paths; use reserved concurrency to protect downstream systems.
  • ✓Make functions idempotent, because events can be delivered more than once; configure DLQs or on-failure destinations.
  • ✓Apply least-privilege execution roles, keep secrets in Secrets Manager, and only attach to a VPC when you need private resources.
  • ✓Put SQS between producers and Lambda to absorb bursts, and size the visibility timeout to 6x the function timeout.
  • ✓Use versions, aliases and CodeDeploy canary or linear deployments, and monitor with CloudWatch Logs, metrics and X-Ray.

Common Interview Questions

Exam Tips

SAA-C03 focus

  • Lambda max timeout = 15 minutes. Anything longer -> Fargate, Batch, EC2, or break up with Step Functions.
  • Memory 128 MB-10 GB also controls CPU; there is no separate CPU setting. /tmp up to 10 GB; package 50 MB zipped / 250 MB unzipped / 10 GB container.
  • Default concurrency 1,000 per Region. Throttling (429) -> request limit increase, reserved concurrency, or buffer with SQS.
  • Cold start mitigation: provisioned concurrency (any runtime), SnapStart (Java, Python, .NET).
  • S3, SNS and EventBridge invoke Lambda asynchronously (2 retries, DLQ). SQS / Kinesis / DynamoDB Streams use event source mappings that poll.
  • To reach RDS privately, attach the function to the VPC; use RDS Proxy to avoid connection exhaustion.
  • Lambda cannot be given an instance role; it uses an execution role. Cross-service invocation permission comes from a resource-based policy.
  • Lambda@Edge runs at CloudFront locations (viewer/origin request and response); CloudFront Functions are lighter for simple header/URL rewrites.

Finished this lesson?

0 of 64 lessons done · 0% of the course