Claude Skill

lambda

AWS Lambda serverless functions for event-driven compute. Use when creating functions, configuring triggers, debugging invocations, optimizing cold starts, setting up event source mappings, or managing layers.

LLM Mart · 0 points · 0 views 0 listing impressions 0 install-command copies
Virus-scanned Reviewed automatically before listing.

Full trust report

Download itsmostafa-aws-agent-skills-skills_lambda-e786d25.zip · 8 KB
Part of itsmostafa/aws-agent-skills — 17 skills

Install

skills CLI npx skills add https://github.com/itsmostafa/aws-agent-skills/tree/main/skills/lambda
Claude Code claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install itsmostafa-aws-agent-skills@llmmart
Git git clone https://github.com/itsmostafa/aws-agent-skills.git

The skills CLI installs just this skill, for any of its supported agents. Claude Code installs the whole itsmostafa/aws-agent-skills collection as a plugin from our marketplace. Git is the plain clone.

Skill manifest

AWS Lambda

AWS Lambda runs code without provisioning servers. You pay only for compute time consumed. Lambda automatically scales from a few requests per day to thousands per second.

Table of Contents

Core Concepts

Function

Your code packaged with configuration. Includes runtime, handler, memory, timeout, and IAM role.

Invocation Types

Type Description Use Case
Synchronous Caller waits for response API Gateway, direct invoke
Asynchronous Fire and forget S3, SNS, EventBridge
Poll-based Lambda polls source SQS, Kinesis, DynamoDB Streams

Execution Environment

Lambda creates execution environments to run your function. Components:

  • Cold start: New environment initialization
  • Warm start: Reusing existing environment
  • Handler: Entry point function
  • Context: Runtime information

Layers

Reusable packages of libraries, dependencies, or custom runtimes (up to 5 per function).

Common Patterns

Create a Python Function

AWS CLI:

# Create deployment package
zip function.zip lambda_function.py

# Create function
aws lambda create-function \
  --function-name MyFunction \
  --runtime python3.12 \
  --role arn:aws:iam::123456789012:role/lambda-role \
  --handler lambda_function.handler \
  --zip-file fileb://function.zip \
  --timeout 30 \
  --memory-size 256

# Update function code
aws lambda update-function-code \
  --function-name MyFunction \
  --zip-file fileb://function.zip

boto3:

import boto3
import zipfile
import io

lambda_client = boto3.client('lambda')

# Create zip in memory
zip_buffer = io.BytesIO()
with zipfile.ZipFile(zip_buffer, 'w') as zf:
    zf.writestr('lambda_function.py', '''
def handler(event, context):
    return {"statusCode": 200, "body": "Hello"}
''')
zip_buffer.seek(0)

# Create function
lambda_client.create_function(
    FunctionName='MyFunction',
    Runtime='python3.12',
    Role='arn:aws:iam::123456789012:role/lambda-role',
    Handler='lambda_function.handler',
    Code={'ZipFile': zip_buffer.read()},
    Timeout=30,
    MemorySize=256
)

Add S3 Trigger

# Add permission for S3 to invoke Lambda
aws lambda add-permission \
  --function-name MyFunction \
  --statement-id s3-trigger \
  --action lambda:InvokeFunction \
  --principal s3.amazonaws.com \
  --source-arn arn:aws:s3:::my-bucket \
  --source-account 123456789012

# Configure S3 notification (see S3 skill)

Add SQS Event Source

aws lambda create-event-source-mapping \
  --function-name MyFunction \
  --event-source-arn arn:aws:sqs:us-east-1:123456789012:my-queue \
  --batch-size 10 \
  --maximum-batching-window-in-seconds 5

Environment Variables

aws lambda update-function-configuration \
  --function-name MyFunction \
  --environment "Variables={DB_HOST=mydb.cluster-xyz.us-east-1.rds.amazonaws.com,LOG_LEVEL=INFO}"

Create and Attach Layer

# Create layer
zip -r layer.zip python/

aws lambda publish-layer-version \
  --layer-name my-dependencies \
  --compatible-runtimes python3.12 \
  --zip-file fileb://layer.zip

# Attach to function
aws lambda update-function-configuration \
  --function-name MyFunction \
  --layers arn:aws:lambda:us-east-1:123456789012:layer:my-dependencies:1

Invoke Function

# Synchronous invoke
aws lambda invoke \
  --function-name MyFunction \
  --payload '{"key": "value"}' \
  response.json

# Asynchronous invoke
aws lambda invoke \
  --function-name MyFunction \
  --invocation-type Event \
  --payload '{"key": "value"}' \
  response.json

CLI Reference

Function Management

Command Description
aws lambda create-function Create new function
aws lambda update-function-code Update function code
aws lambda update-function-configuration Update settings
aws lambda delete-function Delete function
aws lambda list-functions List all functions
aws lambda get-function Get function details

Invocation

Command Description
aws lambda invoke Invoke function
aws lambda invoke-async Async invoke (deprecated)

Event Sources

Command Description
aws lambda create-event-source-mapping Add event source
aws lambda list-event-source-mappings List mappings
aws lambda update-event-source-mapping Update mapping
aws lambda delete-event-source-mapping Remove mapping

Permissions

Command Description
aws lambda add-permission Add resource-based policy
aws lambda remove-permission Remove permission
aws lambda get-policy View resource policy

Best Practices

Performance

  • Right-size memory: More memory = more CPU = faster execution
  • Minimize cold starts: Keep functions warm, use Provisioned Concurrency
  • Optimize package size: Smaller packages deploy faster
  • Use layers for shared dependencies
  • Initialize outside handler: Reuse connections across invocations
# GOOD: Initialize outside handler
import boto3
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('MyTable')

def handler(event, context):
    # Reuses existing connection
    return table.get_item(Key={'id': event['id']})

Security

  • Least privilege IAM roles — only grant needed permissions
  • Use Secrets Manager for sensitive data
  • Enable VPC only if needed (adds latency)
  • Encrypt environment variables with KMS

Cost Optimization

  • Set appropriate timeout — don't use max 15 minutes unnecessarily
  • Use ARM architecture (Graviton2) for 34% better price/performance
  • Batch process where possible
  • Use Reserved Concurrency to limit costs

Reliability

  • Configure DLQ for async invocations
  • Handle retries — async events retry twice
  • Make handlers idempotent
  • Use structured logging

Troubleshooting

Timeout Errors

Symptom: Task timed out after X seconds

Causes:

  • Function takes longer than timeout
  • Network call to unreachable resource
  • VPC configuration issues

Debug:

# Check function configuration
aws lambda get-function-configuration \
  --function-name MyFunction \
  --query "Timeout"

# Increase timeout
aws lambda update-function-configuration \
  --function-name MyFunction \
  --timeout 60

Out of Memory

Symptom: Function crashes with memory error

Fix:

aws lambda update-function-configuration \
  --function-name MyFunction \
  --memory-size 512

Cold Start Latency

Causes:

  • Large deployment package
  • VPC configuration
  • Many dependencies to load

Solutions:

  • Use Provisioned Concurrency
  • Reduce package size
  • Use layers for dependencies
  • Consider Graviton2 (ARM)
# Enable Provisioned Concurrency
aws lambda put-provisioned-concurrency-config \
  --function-name MyFunction \
  --qualifier LIVE \
  --provisioned-concurrent-executions 5

Permission Denied

Symptom: AccessDeniedException

Debug:

# Check execution role
aws lambda get-function-configuration \
  --function-name MyFunction \
  --query "Role"

# Check role policies
aws iam list-attached-role-policies \
  --role-name lambda-role

VPC Connectivity Issues

Symptom: Cannot reach internet or AWS services

Causes:

  • No NAT Gateway for internet access
  • Missing VPC endpoint for AWS services
  • Security group blocking outbound

Solutions:

  • Add NAT Gateway for internet
  • Add VPC endpoints for AWS services
  • Check security group rules

References

Files (aws-agent-skills)
  • debugging.md 8.5 KB
    # Lambda Debugging Guide
    
    Techniques for debugging and troubleshooting Lambda functions.
    
    ## CloudWatch Logs
    
    ### View Logs
    
    ```bash
    # Get log group
    aws logs describe-log-groups \
      --log-group-name-prefix /aws/lambda/MyFunction
    
    # Get recent log streams
    aws logs describe-log-streams \
      --log-group-name /aws/lambda/MyFunction \
      --order-by LastEventTime \
      --descending \
      --limit 5
    
    # View log events
    aws logs get-log-events \
      --log-group-name /aws/lambda/MyFunction \
      --log-stream-name '2024/01/15/[$LATEST]abc123' \
      --limit 100
    ```
    
    ### Filter Logs
    
    ```bash
    # Find errors
    aws logs filter-log-events \
      --log-group-name /aws/lambda/MyFunction \
      --filter-pattern "ERROR" \
      --start-time $(date -d '1 hour ago' +%s000)
    
    # Find specific request
    aws logs filter-log-events \
      --log-group-name /aws/lambda/MyFunction \
      --filter-pattern "request-id-12345"
    ```
    
    ### CloudWatch Logs Insights
    
    ```bash
    # Query for errors with context
    aws logs start-query \
      --log-group-name /aws/lambda/MyFunction \
      --start-time $(date -d '1 hour ago' +%s) \
      --end-time $(date +%s) \
      --query-string '
        fields @timestamp, @message, @requestId
        | filter @message like /ERROR/
        | sort @timestamp desc
        | limit 50
      '
    ```
    
    Common queries:
    
    ```sql
    -- Cold starts
    fields @timestamp, @duration, @billedDuration
    | filter @type = "REPORT"
    | filter @initDuration > 0
    | sort @timestamp desc
    | limit 50
    
    -- Slow invocations
    fields @timestamp, @requestId, @duration
    | filter @type = "REPORT"
    | filter @duration > 1000
    | sort @duration desc
    | limit 20
    
    -- Memory usage
    fields @timestamp, @requestId, @maxMemoryUsed, @memorySize
    | filter @type = "REPORT"
    | stats avg(@maxMemoryUsed), max(@maxMemoryUsed), avg(@memorySize) by bin(1h)
    
    -- Error rate
    fields @timestamp
    | filter @type = "REPORT"
    | stats count(*) as total,
            sum(strcontains(@message, "Error")) as errors,
            sum(strcontains(@message, "Error")) * 100.0 / count(*) as errorRate
      by bin(5m)
    ```
    
    ## X-Ray Tracing
    
    ### Enable X-Ray
    
    ```bash
    aws lambda update-function-configuration \
      --function-name MyFunction \
      --tracing-config Mode=Active
    ```
    
    ### Instrument Code
    
    ```python
    from aws_xray_sdk.core import xray_recorder
    from aws_xray_sdk.core import patch_all
    
    # Patch AWS SDK calls
    patch_all()
    
    def handler(event, context):
        # Create custom subsegment
        with xray_recorder.in_subsegment('process_data') as subsegment:
            subsegment.put_annotation('user_id', event.get('user_id'))
            result = process_data(event)
    
        return result
    ```
    
    ### Query Traces
    
    ```bash
    # Get trace summaries
    aws xray get-trace-summaries \
      --start-time $(date -d '1 hour ago' -u +%Y-%m-%dT%H:%M:%SZ) \
      --end-time $(date -u +%Y-%m-%dT%H:%M:%SZ) \
      --filter-expression 'service(id(name: "MyFunction")) AND responsetime > 1'
    ```
    
    ## Local Testing
    
    ### SAM Local
    
    ```bash
    # Invoke locally
    sam local invoke MyFunction --event event.json
    
    # Start local API
    sam local start-api
    
    # Debug with IDE
    sam local invoke MyFunction --event event.json --debug-port 5678
    ```
    
    ### Docker Lambda Runtime
    
    ```bash
    # Run function locally
    docker run --rm \
      -v $(pwd):/var/task \
      -e AWS_ACCESS_KEY_ID=$AWS_ACCESS_KEY_ID \
      -e AWS_SECRET_ACCESS_KEY=$AWS_SECRET_ACCESS_KEY \
      public.ecr.aws/lambda/python:3.12 \
      lambda_function.handler '{"key": "value"}'
    ```
    
    ### Unit Testing
    
    ```python
    import json
    import pytest
    from unittest.mock import patch, MagicMock
    
    # Import handler
    from lambda_function import handler
    
    class TestHandler:
        def test_successful_request(self):
            event = {"body": json.dumps({"name": "test"})}
            context = MagicMock()
    
            result = handler(event, context)
    
            assert result["statusCode"] == 200
    
        @patch('lambda_function.dynamodb')
        def test_dynamo_error(self, mock_dynamo):
            mock_dynamo.Table.return_value.get_item.side_effect = Exception("DB Error")
    
            event = {"id": "123"}
            context = MagicMock()
    
            result = handler(event, context)
    
            assert result["statusCode"] == 500
    ```
    
    ## Common Issues
    
    ### Timeout Debugging
    
    ```python
    import time
    import logging
    
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)
    
    def handler(event, context):
        start = time.time()
    
        # Log remaining time periodically
        def check_time(operation):
            elapsed = time.time() - start
            remaining = context.get_remaining_time_in_millis() / 1000
            logger.info(f"{operation}: elapsed={elapsed:.2f}s, remaining={remaining:.2f}s")
    
        check_time("start")
    
        result1 = step1()
        check_time("after step1")
    
        result2 = step2()
        check_time("after step2")
    
        return {"statusCode": 200}
    ```
    
    ### Memory Issues
    
    ```python
    import sys
    import tracemalloc
    
    def handler(event, context):
        tracemalloc.start()
    
        # Your code here
        result = process(event)
    
        current, peak = tracemalloc.get_traced_memory()
        print(f"Current memory: {current / 1024 / 1024:.2f} MB")
        print(f"Peak memory: {peak / 1024 / 1024:.2f} MB")
        tracemalloc.stop()
    
        return result
    ```
    
    ### Connection Issues
    
    ```python
    import socket
    import urllib.request
    
    def handler(event, context):
        # Test DNS resolution
        try:
            ip = socket.gethostbyname('example.com')
            print(f"DNS resolved: example.com -> {ip}")
        except socket.gaierror as e:
            print(f"DNS failed: {e}")
    
        # Test HTTP connectivity
        try:
            response = urllib.request.urlopen('https://example.com', timeout=5)
            print(f"HTTP status: {response.status}")
        except Exception as e:
            print(f"HTTP failed: {e}")
    
        return {"statusCode": 200}
    ```
    
    ## Structured Logging
    
    ### AWS Lambda Powertools
    
    ```python
    from aws_lambda_powertools import Logger
    from aws_lambda_powertools.logging import correlation_paths
    
    logger = Logger(service="my-service")
    
    @logger.inject_lambda_context(correlation_id_path=correlation_paths.API_GATEWAY_REST)
    def handler(event, context):
        logger.info("Processing request", extra={
            "user_id": event.get("user_id"),
            "action": "process"
        })
    
        try:
            result = process(event)
            logger.info("Success", extra={"result": result})
            return {"statusCode": 200, "body": json.dumps(result)}
        except Exception as e:
            logger.exception("Failed to process")
            return {"statusCode": 500}
    ```
    
    ### JSON Logging
    
    ```python
    import json
    import logging
    
    class JsonFormatter(logging.Formatter):
        def format(self, record):
            log_data = {
                "timestamp": self.formatTime(record),
                "level": record.levelname,
                "message": record.getMessage(),
                "function": record.funcName,
            }
            if hasattr(record, 'request_id'):
                log_data['request_id'] = record.request_id
            if record.exc_info:
                log_data['exception'] = self.formatException(record.exc_info)
            return json.dumps(log_data)
    
    logger = logging.getLogger()
    handler = logging.StreamHandler()
    handler.setFormatter(JsonFormatter())
    logger.addHandler(handler)
    logger.setLevel(logging.INFO)
    ```
    
    ## Debugging Event Sources
    
    ### SQS Events
    
    ```python
    def handler(event, context):
        for record in event['Records']:
            message_id = record['messageId']
            body = record['body']
    
            print(f"Processing message {message_id}")
            print(f"Body: {body}")
            print(f"Attributes: {record.get('messageAttributes', {})}")
    
            try:
                process_message(body)
            except Exception as e:
                print(f"Failed to process {message_id}: {e}")
                raise  # Message goes to DLQ
    ```
    
    ### API Gateway Events
    
    ```python
    def handler(event, context):
        print(f"HTTP Method: {event['httpMethod']}")
        print(f"Path: {event['path']}")
        print(f"Headers: {json.dumps(event.get('headers', {}))}")
        print(f"Query: {json.dumps(event.get('queryStringParameters', {}))}")
        print(f"Body: {event.get('body', '')}")
    
        return {
            "statusCode": 200,
            "body": json.dumps({"message": "Debug info logged"})
        }
    ```
    
    ## Error Handling
    
    ```python
    import json
    from aws_lambda_powertools import Logger
    
    logger = Logger()
    
    class ProcessingError(Exception):
        """Custom application error"""
        pass
    
    def handler(event, context):
        try:
            result = process(event)
            return {
                "statusCode": 200,
                "body": json.dumps(result)
            }
        except ProcessingError as e:
            logger.warning(f"Processing error: {e}")
            return {
                "statusCode": 400,
                "body": json.dumps({"error": str(e)})
            }
        except Exception as e:
            logger.exception("Unexpected error")
            return {
                "statusCode": 500,
                "body": json.dumps({"error": "Internal server error"})
            }
    ```
    
  • deployment.md 7.1 KB
    # Lambda Deployment Patterns
    
    Strategies and patterns for deploying Lambda functions.
    
    ## Deployment Methods
    
    ### Direct Zip Upload
    
    Best for small functions (< 50 MB):
    
    ```bash
    # Package and deploy
    zip -r function.zip . -x "*.git*"
    
    aws lambda update-function-code \
      --function-name MyFunction \
      --zip-file fileb://function.zip
    ```
    
    ### S3 Deployment
    
    Required for packages > 50 MB (up to 250 MB unzipped):
    
    ```bash
    # Upload to S3
    aws s3 cp function.zip s3://my-deployment-bucket/function.zip
    
    # Deploy from S3
    aws lambda update-function-code \
      --function-name MyFunction \
      --s3-bucket my-deployment-bucket \
      --s3-key function.zip
    ```
    
    ### Container Image Deployment
    
    For packages up to 10 GB:
    
    ```dockerfile
    FROM public.ecr.aws/lambda/python:3.12
    
    COPY requirements.txt .
    RUN pip install -r requirements.txt
    
    COPY app.py .
    
    CMD ["app.handler"]
    ```
    
    ```bash
    # Build and push
    docker build -t my-lambda .
    aws ecr get-login-password | docker login --username AWS --password-stdin 123456789012.dkr.ecr.us-east-1.amazonaws.com
    docker tag my-lambda:latest 123456789012.dkr.ecr.us-east-1.amazonaws.com/my-lambda:latest
    docker push 123456789012.dkr.ecr.us-east-1.amazonaws.com/my-lambda:latest
    
    # Deploy
    aws lambda update-function-code \
      --function-name MyFunction \
      --image-uri 123456789012.dkr.ecr.us-east-1.amazonaws.com/my-lambda:latest
    ```
    
    ## AWS SAM Deployment
    
    ### Template Example
    
    ```yaml
    # template.yaml
    AWSTemplateFormatVersion: '2010-09-09'
    Transform: AWS::Serverless-2016-10-31
    
    Globals:
      Function:
        Runtime: python3.12
        Timeout: 30
        MemorySize: 256
    
    Resources:
      MyFunction:
        Type: AWS::Serverless::Function
        Properties:
          FunctionName: MyFunction
          Handler: app.handler
          CodeUri: ./src
          Environment:
            Variables:
              TABLE_NAME: !Ref MyTable
          Events:
            Api:
              Type: Api
              Properties:
                Path: /items
                Method: GET
          Policies:
            - DynamoDBReadPolicy:
                TableName: !Ref MyTable
    
      MyTable:
        Type: AWS::Serverless::SimpleTable
    ```
    
    ### SAM Commands
    
    ```bash
    # Build
    sam build
    
    # Local testing
    sam local invoke MyFunction --event event.json
    sam local start-api
    
    # Deploy
    sam deploy --guided  # First time
    sam deploy           # Subsequent deploys
    
    # View logs
    sam logs -n MyFunction --tail
    ```
    
    ## Versioning and Aliases
    
    ### Publish Version
    
    ```bash
    # Publish immutable version
    aws lambda publish-version \
      --function-name MyFunction \
      --description "v1.0.0 - Initial release"
    ```
    
    ### Create Alias
    
    ```bash
    # Create PROD alias pointing to version 1
    aws lambda create-alias \
      --function-name MyFunction \
      --name PROD \
      --function-version 1
    
    # Create DEV alias pointing to $LATEST
    aws lambda create-alias \
      --function-name MyFunction \
      --name DEV \
      --function-version '$LATEST'
    ```
    
    ### Weighted Alias (Canary Deployment)
    
    ```bash
    # Route 90% to v1, 10% to v2
    aws lambda update-alias \
      --function-name MyFunction \
      --name PROD \
      --function-version 2 \
      --routing-config AdditionalVersionWeights={1=0.9}
    ```
    
    ### Blue/Green with Aliases
    
    ```bash
    # Current state: PROD -> v1
    
    # Deploy new version
    aws lambda update-function-code \
      --function-name MyFunction \
      --zip-file fileb://function.zip
    
    aws lambda publish-version \
      --function-name MyFunction \
      --description "v2.0.0"
    
    # Canary: 10% to v2
    aws lambda update-alias \
      --function-name MyFunction \
      --name PROD \
      --function-version 2 \
      --routing-config AdditionalVersionWeights={1=0.9}
    
    # Full rollout
    aws lambda update-alias \
      --function-name MyFunction \
      --name PROD \
      --function-version 2 \
      --routing-config AdditionalVersionWeights={}
    
    # Rollback if needed
    aws lambda update-alias \
      --function-name MyFunction \
      --name PROD \
      --function-version 1
    ```
    
    ## Layers
    
    ### Create a Layer
    
    Python dependencies:
    
    ```bash
    # Structure: python/lib/python3.12/site-packages/
    mkdir -p python
    pip install -t python/ requests boto3
    
    zip -r layer.zip python/
    
    aws lambda publish-layer-version \
      --layer-name my-python-deps \
      --compatible-runtimes python3.12 \
      --compatible-architectures x86_64 arm64 \
      --zip-file fileb://layer.zip
    ```
    
    ### Use AWS-Provided Layers
    
    ```bash
    # AWS Parameters and Secrets Layer
    aws lambda update-function-configuration \
      --function-name MyFunction \
      --layers arn:aws:lambda:us-east-1:177933569100:layer:AWS-Parameters-and-Secrets-Lambda-Extension:11
    ```
    
    ### Layer Best Practices
    
    - Keep layers under 50 MB
    - Version layers properly
    - Test compatibility with function runtime
    - Use separate layers for different purposes
    
    ## CI/CD Integration
    
    ### GitHub Actions
    
    ```yaml
    name: Deploy Lambda
    
    on:
      push:
        branches: [main]
    
    jobs:
      deploy:
        runs-on: ubuntu-latest
        permissions:
          id-token: write
          contents: read
    
        steps:
          - uses: actions/checkout@v4
    
          - uses: aws-actions/configure-aws-credentials@v4
            with:
              role-to-assume: arn:aws:iam::123456789012:role/github-actions-role
              aws-region: us-east-1
    
          - name: Deploy
            run: |
              zip -r function.zip .
              aws lambda update-function-code \
                --function-name MyFunction \
                --zip-file fileb://function.zip
    
              aws lambda publish-version \
                --function-name MyFunction \
                --description "${{ github.sha }}"
    ```
    
    ### SAM Pipeline
    
    ```bash
    # Initialize pipeline
    sam pipeline init --bootstrap
    
    # Creates:
    # - IAM roles for CI/CD
    # - S3 bucket for artifacts
    # - CloudFormation for infrastructure
    # - Pipeline configuration file
    ```
    
    ## Environment Management
    
    ### Environment Variables
    
    ```bash
    # Set environment variables
    aws lambda update-function-configuration \
      --function-name MyFunction \
      --environment "Variables={
        STAGE=production,
        DB_HOST=prod-db.example.com,
        LOG_LEVEL=INFO
      }"
    ```
    
    ### KMS Encryption
    
    ```bash
    aws lambda update-function-configuration \
      --function-name MyFunction \
      --kms-key-arn arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012 \
      --environment "Variables={
        DB_PASSWORD=encrypted-value
      }"
    ```
    
    ### Using Secrets Manager
    
    ```python
    import boto3
    import json
    
    secrets = boto3.client('secretsmanager')
    
    # Cache secret outside handler for reuse
    _secret = None
    
    def get_secret():
        global _secret
        if _secret is None:
            response = secrets.get_secret_value(SecretId='my-secret')
            _secret = json.loads(response['SecretString'])
        return _secret
    
    def handler(event, context):
        secret = get_secret()
        db_password = secret['password']
        # Use secret...
    ```
    
    ## Package Size Optimization
    
    ### Reduce Package Size
    
    ```bash
    # Remove unnecessary files
    zip -r function.zip . \
      -x "*.git*" \
      -x "*__pycache__*" \
      -x "*.pyc" \
      -x "tests/*" \
      -x "*.md" \
      -x "*.txt"
    
    # Use zip with compression
    zip -9 -r function.zip .
    ```
    
    ### Lambda Powertools (Recommended)
    
    ```python
    # Use AWS Lambda Powertools for structured logging, tracing, etc.
    from aws_lambda_powertools import Logger, Tracer, Metrics
    
    logger = Logger()
    tracer = Tracer()
    metrics = Metrics()
    
    @logger.inject_lambda_context
    @tracer.capture_lambda_handler
    @metrics.log_metrics
    def handler(event, context):
        logger.info("Processing request", extra={"event": event})
        return {"statusCode": 200}
    ```
    
  • SKILL.md 8.4 KB
    ---
    name: lambda
    description: AWS Lambda serverless functions for event-driven compute. Use when creating functions, configuring triggers, debugging invocations, optimizing cold starts, setting up event source mappings, or managing layers.
    last_updated: "2026-01-07"
    doc_source: https://docs.aws.amazon.com/lambda/latest/dg/
    ---
    
    # AWS Lambda
    
    AWS Lambda runs code without provisioning servers. You pay only for compute time consumed. Lambda automatically scales from a few requests per day to thousands per second.
    
    ## Table of Contents
    
    - [Core Concepts](#core-concepts)
    - [Common Patterns](#common-patterns)
    - [CLI Reference](#cli-reference)
    - [Best Practices](#best-practices)
    - [Troubleshooting](#troubleshooting)
    - [References](#references)
    
    ## Core Concepts
    
    ### Function
    
    Your code packaged with configuration. Includes runtime, handler, memory, timeout, and IAM role.
    
    ### Invocation Types
    
    | Type | Description | Use Case |
    |------|-------------|----------|
    | **Synchronous** | Caller waits for response | API Gateway, direct invoke |
    | **Asynchronous** | Fire and forget | S3, SNS, EventBridge |
    | **Poll-based** | Lambda polls source | SQS, Kinesis, DynamoDB Streams |
    
    ### Execution Environment
    
    Lambda creates execution environments to run your function. Components:
    - **Cold start**: New environment initialization
    - **Warm start**: Reusing existing environment
    - **Handler**: Entry point function
    - **Context**: Runtime information
    
    ### Layers
    
    Reusable packages of libraries, dependencies, or custom runtimes (up to 5 per function).
    
    ## Common Patterns
    
    ### Create a Python Function
    
    **AWS CLI:**
    
    ```bash
    # Create deployment package
    zip function.zip lambda_function.py
    
    # Create function
    aws lambda create-function \
      --function-name MyFunction \
      --runtime python3.12 \
      --role arn:aws:iam::123456789012:role/lambda-role \
      --handler lambda_function.handler \
      --zip-file fileb://function.zip \
      --timeout 30 \
      --memory-size 256
    
    # Update function code
    aws lambda update-function-code \
      --function-name MyFunction \
      --zip-file fileb://function.zip
    ```
    
    **boto3:**
    
    ```python
    import boto3
    import zipfile
    import io
    
    lambda_client = boto3.client('lambda')
    
    # Create zip in memory
    zip_buffer = io.BytesIO()
    with zipfile.ZipFile(zip_buffer, 'w') as zf:
        zf.writestr('lambda_function.py', '''
    def handler(event, context):
        return {"statusCode": 200, "body": "Hello"}
    ''')
    zip_buffer.seek(0)
    
    # Create function
    lambda_client.create_function(
        FunctionName='MyFunction',
        Runtime='python3.12',
        Role='arn:aws:iam::123456789012:role/lambda-role',
        Handler='lambda_function.handler',
        Code={'ZipFile': zip_buffer.read()},
        Timeout=30,
        MemorySize=256
    )
    ```
    
    ### Add S3 Trigger
    
    ```bash
    # Add permission for S3 to invoke Lambda
    aws lambda add-permission \
      --function-name MyFunction \
      --statement-id s3-trigger \
      --action lambda:InvokeFunction \
      --principal s3.amazonaws.com \
      --source-arn arn:aws:s3:::my-bucket \
      --source-account 123456789012
    
    # Configure S3 notification (see S3 skill)
    ```
    
    ### Add SQS Event Source
    
    ```bash
    aws lambda create-event-source-mapping \
      --function-name MyFunction \
      --event-source-arn arn:aws:sqs:us-east-1:123456789012:my-queue \
      --batch-size 10 \
      --maximum-batching-window-in-seconds 5
    ```
    
    ### Environment Variables
    
    ```bash
    aws lambda update-function-configuration \
      --function-name MyFunction \
      --environment "Variables={DB_HOST=mydb.cluster-xyz.us-east-1.rds.amazonaws.com,LOG_LEVEL=INFO}"
    ```
    
    ### Create and Attach Layer
    
    ```bash
    # Create layer
    zip -r layer.zip python/
    
    aws lambda publish-layer-version \
      --layer-name my-dependencies \
      --compatible-runtimes python3.12 \
      --zip-file fileb://layer.zip
    
    # Attach to function
    aws lambda update-function-configuration \
      --function-name MyFunction \
      --layers arn:aws:lambda:us-east-1:123456789012:layer:my-dependencies:1
    ```
    
    ### Invoke Function
    
    ```bash
    # Synchronous invoke
    aws lambda invoke \
      --function-name MyFunction \
      --payload '{"key": "value"}' \
      response.json
    
    # Asynchronous invoke
    aws lambda invoke \
      --function-name MyFunction \
      --invocation-type Event \
      --payload '{"key": "value"}' \
      response.json
    ```
    
    ## CLI Reference
    
    ### Function Management
    
    | Command | Description |
    |---------|-------------|
    | `aws lambda create-function` | Create new function |
    | `aws lambda update-function-code` | Update function code |
    | `aws lambda update-function-configuration` | Update settings |
    | `aws lambda delete-function` | Delete function |
    | `aws lambda list-functions` | List all functions |
    | `aws lambda get-function` | Get function details |
    
    ### Invocation
    
    | Command | Description |
    |---------|-------------|
    | `aws lambda invoke` | Invoke function |
    | `aws lambda invoke-async` | Async invoke (deprecated) |
    
    ### Event Sources
    
    | Command | Description |
    |---------|-------------|
    | `aws lambda create-event-source-mapping` | Add event source |
    | `aws lambda list-event-source-mappings` | List mappings |
    | `aws lambda update-event-source-mapping` | Update mapping |
    | `aws lambda delete-event-source-mapping` | Remove mapping |
    
    ### Permissions
    
    | Command | Description |
    |---------|-------------|
    | `aws lambda add-permission` | Add resource-based policy |
    | `aws lambda remove-permission` | Remove permission |
    | `aws lambda get-policy` | View resource policy |
    
    ## Best Practices
    
    ### Performance
    
    - **Right-size memory**: More memory = more CPU = faster execution
    - **Minimize cold starts**: Keep functions warm, use Provisioned Concurrency
    - **Optimize package size**: Smaller packages deploy faster
    - **Use layers** for shared dependencies
    - **Initialize outside handler**: Reuse connections across invocations
    
    ```python
    # GOOD: Initialize outside handler
    import boto3
    dynamodb = boto3.resource('dynamodb')
    table = dynamodb.Table('MyTable')
    
    def handler(event, context):
        # Reuses existing connection
        return table.get_item(Key={'id': event['id']})
    ```
    
    ### Security
    
    - **Least privilege IAM roles** — only grant needed permissions
    - **Use Secrets Manager** for sensitive data
    - **Enable VPC** only if needed (adds latency)
    - **Encrypt environment variables** with KMS
    
    ### Cost Optimization
    
    - **Set appropriate timeout** — don't use max 15 minutes unnecessarily
    - **Use ARM architecture** (Graviton2) for 34% better price/performance
    - **Batch process** where possible
    - **Use Reserved Concurrency** to limit costs
    
    ### Reliability
    
    - **Configure DLQ** for async invocations
    - **Handle retries** — async events retry twice
    - **Make handlers idempotent**
    - **Use structured logging**
    
    ## Troubleshooting
    
    ### Timeout Errors
    
    **Symptom:** `Task timed out after X seconds`
    
    **Causes:**
    - Function takes longer than timeout
    - Network call to unreachable resource
    - VPC configuration issues
    
    **Debug:**
    
    ```bash
    # Check function configuration
    aws lambda get-function-configuration \
      --function-name MyFunction \
      --query "Timeout"
    
    # Increase timeout
    aws lambda update-function-configuration \
      --function-name MyFunction \
      --timeout 60
    ```
    
    ### Out of Memory
    
    **Symptom:** Function crashes with memory error
    
    **Fix:**
    
    ```bash
    aws lambda update-function-configuration \
      --function-name MyFunction \
      --memory-size 512
    ```
    
    ### Cold Start Latency
    
    **Causes:**
    - Large deployment package
    - VPC configuration
    - Many dependencies to load
    
    **Solutions:**
    - Use Provisioned Concurrency
    - Reduce package size
    - Use layers for dependencies
    - Consider Graviton2 (ARM)
    
    ```bash
    # Enable Provisioned Concurrency
    aws lambda put-provisioned-concurrency-config \
      --function-name MyFunction \
      --qualifier LIVE \
      --provisioned-concurrent-executions 5
    ```
    
    ### Permission Denied
    
    **Symptom:** `AccessDeniedException`
    
    **Debug:**
    
    ```bash
    # Check execution role
    aws lambda get-function-configuration \
      --function-name MyFunction \
      --query "Role"
    
    # Check role policies
    aws iam list-attached-role-policies \
      --role-name lambda-role
    ```
    
    ### VPC Connectivity Issues
    
    **Symptom:** Cannot reach internet or AWS services
    
    **Causes:**
    - No NAT Gateway for internet access
    - Missing VPC endpoint for AWS services
    - Security group blocking outbound
    
    **Solutions:**
    - Add NAT Gateway for internet
    - Add VPC endpoints for AWS services
    - Check security group rules
    
    ## References
    
    - [Lambda Developer Guide](https://docs.aws.amazon.com/lambda/latest/dg/)
    - [Lambda API Reference](https://docs.aws.amazon.com/lambda/latest/api/)
    - [Lambda CLI Reference](https://docs.aws.amazon.com/cli/latest/reference/lambda/)
    - [boto3 Lambda](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/lambda.html)
    

Comments (0)

Sign in to join the conversation.

No comments yet.

Reviews (0)

No reviews yet.

Related