Skip to content

Lambda

Serverless compute — run code without managing servers.


Ultra-Short Summary

Lambda runs your code in response to events. You upload a function, define what triggers it, and AWS handles everything else — provisioning, scaling, patching, availability. You pay only for the time your code actually runs (in 1ms increments). The constraint: functions must complete within 15 minutes and are stateless between invocations.


How Lambda Works

Event source triggers Lambda
Lambda service provisions an execution environment
Your function runs (max 15 min)
Result returned or sent downstream
Execution environment kept warm briefly, then discarded

Key Concepts

Invocation Types

Type How Use Case
Synchronous Caller waits for response API Gateway, SDK direct calls
Asynchronous Lambda queues the event S3 events, SNS, EventBridge
Poll-based Lambda polls a stream SQS, Kinesis, DynamoDB Streams

Cold Starts vs Warm Starts

Cold start → new execution environment provisioned
           → download code, initialise runtime, run init code
           → adds latency (typically 100ms–1s depending on runtime)

Warm start → execution environment already running
           → just run the handler function
           → much faster

Ways to reduce cold starts: - Provisioned Concurrency — pre-warm a specified number of environments (costs money) - Keep function packages small - Use Lambda SnapStart (Java only) - Choose runtimes with faster init (Python/Node.js faster than Java/.NET)


Triggers (Event Sources)

Lambda can be triggered by almost any AWS service:

Trigger Pattern
API Gateway HTTP request → Lambda → response
S3 File uploaded → Lambda processes it
SQS Message in queue → Lambda processes it
SNS Notification published → Lambda reacts
EventBridge Scheduled rule or AWS event → Lambda
DynamoDB Streams Record changed → Lambda reacts
Kinesis Stream record → Lambda processes it
CloudWatch Logs Log event → Lambda for processing
ALB HTTP traffic → Lambda as backend

Function Structure (Python)

import json
import boto3

def lambda_handler(event, context):
    """
    event   → dict containing the trigger event data
    context → object with runtime info (function name, timeout remaining, etc.)
    """

    # Example: triggered by S3
    bucket = event['Records'][0]['s3']['bucket']['name']
    key = event['Records'][0]['s3']['object']['key']

    print(f"Processing {key} from {bucket}")

    # Do work...

    return {
        'statusCode': 200,
        'body': json.dumps('Done')
    }

Important: Logging

Lambda automatically sends print() and logging output to CloudWatch Logs.

import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)

def lambda_handler(event, context):
    logger.info(f"Event received: {json.dumps(event)}")
    # ...

Log group: /aws/lambda/<function-name>


Limits to Know

Limit Value
Max execution time 15 minutes
Max memory 10,240 MB (10 GB)
Max deployment package size 50 MB (zipped), 250 MB unzipped
Max /tmp storage 10 GB
Default concurrency 1,000 per region (soft limit)
Free tier 1 million requests/month + 400,000 GB-seconds

Lambda + IAM

Lambda functions need an execution role — an IAM role that defines what AWS services the function can access.

Lambda function
    ↓ assumes
Execution Role (IAM)
    ↓ has policies like
  - AWSLambdaBasicExecutionRole  (write to CloudWatch Logs)
  - AmazonDynamoDBFullAccess     (if it needs DynamoDB)
  - AmazonS3ReadOnlyAccess       (if it reads from S3)

Always use least privilege — only grant what the function actually needs.


Deployment

Upload a .zip file directly in the console. Fine for small functions.

Package function as a Docker image (up to 10 GB). Good for large ML models or complex deps.

docker build -t my-function .
docker tag my-function:latest <account>.dkr.ecr.region.amazonaws.com/my-function:latest
docker push <account>.dkr.ecr.region.amazonaws.com/my-function:latest

Infrastructure-as-code deployment. Best practice for production.

# CDK example
lambda_.Function(self, "MyFunction",
    runtime=lambda_.Runtime.PYTHON_3_12,
    handler="index.lambda_handler",
    code=lambda_.Code.from_asset("lambda")
)


Common Patterns

S3 → Lambda → DynamoDB (event pipeline)

File uploaded to S3
        ↓ S3 Event notification
Lambda triggered
        ↓ parses the file
Writes records to DynamoDB

API Gateway → Lambda (REST API)

Client HTTP request
        ↓ API Gateway
Lambda function
        ↓ processes, queries DB
Returns JSON response
        ↓ API Gateway
Client receives response

EventBridge Scheduler (Cron)

EventBridge rule: "run every day at 9am UTC"
Lambda: sends a daily summary email, cleans up old records, etc.

Mental Model

Lambda = a function that runs in response to events
       = no server to manage
       = scales from 0 to thousands of concurrent executions automatically
       = you pay for time running, not for idle time

Think of it like:
  "I want something to happen when X happens"
  → Lambda is the answer

SAA Patterns

Scenario Answer
Process images uploaded to S3 S3 event → Lambda
Serverless REST API API Gateway + Lambda
Run code on a schedule EventBridge Scheduler + Lambda
React to DynamoDB changes DynamoDB Streams + Lambda
Process messages from a queue SQS → Lambda (poll-based)
Low latency requirement, no cold starts Lambda with Provisioned Concurrency
Function needs >15 minutes Not Lambda — use ECS Fargate or Batch
Function needs >10 GB memory Not Lambda — use ECS Fargate

30-Second Takeaway

  • Lambda = event-driven, serverless, stateless functions.
  • Max 15 minutes, scales automatically, pay per 1ms of execution.
  • Cold starts are a real consideration — provisioned concurrency is the fix.
  • Needs an IAM execution role — always least privilege.
  • Triggered by almost every AWS service: S3, SQS, API Gateway, EventBridge, etc.

Self-Quiz

  1. What's the maximum execution time for a Lambda function?
  2. What causes a cold start and how do you reduce it?
  3. What IAM construct does Lambda use to access other AWS services?
  4. Your Lambda needs to write logs. Where do they go? What IAM permission does it need?
  5. Difference between synchronous and asynchronous Lambda invocation?
  6. A task needs to run for 20 minutes. Can you use Lambda?
  7. How does Lambda scale automatically? What's the default concurrency limit?
  8. Walk through: user uploads image to S3 → thumbnail is created. What's the architecture?