{"id":"lambda","name":"lambda","summary":"イベント駆動型計算のためのAWS Lambdaサーバーレス関数。関数の作成、トリガーの設定、呼び出しのデバッグ、コールドスタートの最適化、イベントソースマッピングの設定、レイヤー管理の際に利用されます。","body":"# AWS Lambda\n\nAWS 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.\n\n## Table of Contents\n\n- [Core Concepts](#core-concepts)\n- [Common Patterns](#common-patterns)\n- [CLI Reference](#cli-reference)\n- [Best Practices](#best-practices)\n- [Troubleshooting](#troubleshooting)\n- [References](#references)\n\n## Core Concepts\n\n### Function\n\nYour code packaged with configuration. Includes runtime, handler, memory, timeout, and IAM role.\n\n### Invocation Types\n\n| Type | Description | Use Case |\n|------|-------------|----------|\n| **Synchronous** | Caller waits for response | API Gateway, direct invoke |\n| **Asynchronous** | Fire and forget | S3, SNS, EventBridge |\n| **Poll-based** | Lambda polls source | SQS, Kinesis, DynamoDB Streams |\n\n### Execution Environment\n\nLambda creates execution environments to run your function. Components:\n- **Cold start**: New environment initialization\n- **Warm start**: Reusing existing environment\n- **Handler**: Entry point function\n- **Context**: Runtime information\n\n### Layers\n\nReusable packages of libraries, dependencies, or custom runtimes (up to 5 per function).\n\n## Common Patterns\n\n### Create a Python Function\n\n**AWS CLI:**\n\n```bash\n# Create deployment package\nzip function.zip lambda_function.py\n\n# Create function\naws lambda create-function \\\n  --function-name MyFunction \\\n  --runtime python3.12 \\\n  --role arn:aws:iam::123456789012:role/lambda-role \\\n  --handler lambda_function.handler \\\n  --zip-file fileb://function.zip \\\n  --timeout 30 \\\n  --memory-size 256\n\n# Update function code\naws lambda update-function-code \\\n  --function-name MyFunction \\\n  --zip-file fileb://function.zip\n```\n\n**boto3:**\n\n```python\nimport boto3\nimport zipfile\nimport io\n\nlambda_client = boto3.client('lambda')\n\n# Create zip in memory\nzip_buffer = io.BytesIO()\nwith zipfile.ZipFile(zip_buffer, 'w') as zf:\n    zf.writestr('lambda_function.py', '''\ndef handler(event, context):\n    return {\"statusCode\": 200, \"body\": \"Hello\"}\n''')\nzip_buffer.seek(0)\n\n# Create function\nlambda_client.create_function(\n    FunctionName='MyFunction',\n    Runtime='python3.12',\n    Role='arn:aws:iam::123456789012:role/lambda-role',\n    Handler='lambda_function.handler',\n    Code={'ZipFile': zip_buffer.read()},\n    Timeout=30,\n    MemorySize=256\n)\n```\n\n### Add S3 Trigger\n\n```bash\n# Add permission for S3 to invoke Lambda\naws lambda add-permission \\\n  --function-name MyFunction \\\n  --statement-id s3-trigger \\\n  --action lambda:InvokeFunction \\\n  --principal s3.amazonaws.com \\\n  --source-arn arn:aws:s3:::my-bucket \\\n  --source-account 123456789012\n\n# Configure S3 notification (see S3 skill)\n```\n\n### Add SQS Event Source\n\n```bash\naws lambda create-event-source-mapping \\\n  --function-name MyFunction \\\n  --event-source-arn arn:aws:sqs:us-east-1:123456789012:my-queue \\\n  --batch-size 10 \\\n  --maximum-batching-window-in-seconds 5\n```\n\n### Environment Variables\n\n```bash\naws lambda update-function-configuration \\\n  --function-name MyFunction \\\n  --environment \"Variables={DB_HOST=mydb.cluster-xyz.us-east-1.rds.amazonaws.com,LOG_LEVEL=INFO}\"\n```\n\n### Create and Attach Layer\n\n```bash\n# Create layer\nzip -r layer.zip python/\n\naws lambda publish-layer-version \\\n  --layer-name my-dependencies \\\n  --compatible-runtimes python3.12 \\\n  --zip-file fileb://layer.zip\n\n# Attach to function\naws lambda update-function-configuration \\\n  --function-name MyFunction \\\n  --layers arn:aws:lambda:us-east-1:123456789012:layer:my-dependencies:1\n```\n\n### Invoke Function\n\n```bash\n# Synchronous invoke\naws lambda invoke \\\n  --function-name MyFunction \\\n  --payload '{\"key\": \"value\"}' \\\n  response.json\n\n# Asynchronous invoke\naws lambda invoke \\\n  --function-name MyFunction \\\n  --invocation-type Event \\\n  --payload '{\"key\": \"value\"}' \\\n  response.json\n```\n\n## CLI Reference\n\n### Function Management\n\n| Command | Description |\n|---------|-------------|\n| `aws lambda create-function` | Create new function |\n| `aws lambda update-function-code` | Update function code |\n| `aws lambda update-function-configuration` | Update settings |\n| `aws lambda delete-function` | Delete function |\n| `aws lambda list-functions` | List all functions |\n| `aws lambda get-function` | Get function details |\n\n### Invocation\n\n| Command | Description |\n|---------|-------------|\n| `aws lambda invoke` | Invoke function |\n| `aws lambda invoke-async` | Async invoke (deprecated) |\n\n### Event Sources\n\n| Command | Description |\n|---------|-------------|\n| `aws lambda create-event-source-mapping` | Add event source |\n| `aws lambda list-event-source-mappings` | List mappings |\n| `aws lambda update-event-source-mapping` | Update mapping |\n| `aws lambda delete-event-source-mapping` | Remove mapping |\n\n### Permissions\n\n| Command | Description |\n|---------|-------------|\n| `aws lambda add-permission` | Add resource-based policy |\n| `aws lambda remove-permission` | Remove permission |\n| `aws lambda get-policy` | View resource policy |\n\n## Best Practices\n\n### Performance\n\n- **Right-size memory**: More memory = more CPU = faster execution\n- **Minimize cold starts**: Keep functions warm, use Provisioned Concurrency\n- **Optimize package size**: Smaller packages deploy faster\n- **Use layers** for shared dependencies\n- **Initialize outside handler**: Reuse connections across invocations\n\n```python\n# GOOD: Initialize outside handler\nimport boto3\ndynamodb = boto3.resource('dynamodb')\ntable = dynamodb.Table('MyTable')\n\ndef handler(event, context):\n    # Reuses existing connection\n    return table.get_item(Key={'id': event['id']})\n```\n\n### Security\n\n- **Least privilege IAM roles** — only grant needed permissions\n- **Use Secrets Manager** for sensitive data\n- **Enable VPC** only if needed (adds latency)\n- **Encrypt environment variables** with KMS\n\n### Cost Optimization\n\n- **Set appropriate timeout** — don't use max 15 minutes unnecessarily\n- **Use ARM architecture** (Graviton2) for 34% better price/performance\n- **Batch process** where possible\n- **Use Reserved Concurrency** to limit costs\n\n### Reliability\n\n- **Configure DLQ** for async invocations\n- **Handle retries** — async events retry twice\n- **Make handlers idempotent**\n- **Use structured logging**\n\n## Troubleshooting\n\n### Timeout Errors\n\n**Symptom:** `Task timed out after X seconds`\n\n**Causes:**\n- Function takes longer than timeout\n- Network call to unreachable resource\n- VPC configuration issues\n\n**Debug:**\n\n```bash\n# Check function configuration\naws lambda get-function-configuration \\\n  --function-name MyFunction \\\n  --query \"Timeout\"\n\n# Increase timeout\naws lambda update-function-configuration \\\n  --function-name MyFunction \\\n  --timeout 60\n```\n\n### Out of Memory\n\n**Symptom:** Function crashes with memory error\n\n**Fix:**\n\n```bash\naws lambda update-function-configuration \\\n  --function-name MyFunction \\\n  --memory-size 512\n```\n\n### Cold Start Latency\n\n**Causes:**\n- Large deployment package\n- VPC configuration\n- Many dependencies to load\n\n**Solutions:**\n- Use Provisioned Concurrency\n- Reduce package size\n- Use layers for dependencies\n- Consider Graviton2 (ARM)\n\n```bash\n# Enable Provisioned Concurrency\naws lambda put-provisioned-concurrency-config \\\n  --function-name MyFunction \\\n  --qualifier LIVE \\\n  --provisioned-concurrent-executions 5\n```\n\n### Permission Denied\n\n**Symptom:** `AccessDeniedException`\n\n**Debug:**\n\n```bash\n# Check execution role\naws lambda get-function-configuration \\\n  --function-name MyFunction \\\n  --query \"Role\"\n\n# Check role policies\naws iam list-attached-role-policies \\\n  --role-name lambda-role\n```\n\n### VPC Connectivity Issues\n\n**Symptom:** Cannot reach internet or AWS services\n\n**Causes:**\n- No NAT Gateway for internet access\n- Missing VPC endpoint for AWS services\n- Security group blocking outbound\n\n**Solutions:**\n- Add NAT Gateway for internet\n- Add VPC endpoints for AWS services\n- Check security group rules\n\n## References\n\n- [Lambda Developer Guide](https://docs.aws.amazon.com/lambda/latest/dg/)\n- [Lambda API Reference](https://docs.aws.amazon.com/lambda/latest/api/)\n- [Lambda CLI Reference](https://docs.aws.amazon.com/cli/latest/reference/lambda/)\n- [boto3 Lambda](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/lambda.html)","author":"@itsmostafa","ownerProfile":null,"authorContacts":null,"sourceUrl":"https://github.com/itsmostafa/aws-agent-skills/tree/main/skills/lambda","license":"MIT","category":"coding","lang":"en","tokens":1988,"stars":0,"calls30d":2,"claimed":false,"visibility":"public","origin":"crawler","version":"0.1.0","createdAt":"2026-08-22","updatedAt":"2026-08-22","files":[{"path":"debugging.md","size":8731,"sha256":"5442c5288cb0209e3e885dd3693e5e9ab8b71b4d82378b82089a08fd0130b0cb"},{"path":"deployment.md","size":7300,"sha256":"cb667787eafe54a61b41a13e39f81da21b1dfedbe60a2d5e671feffaae311686"}],"requires":{"mcp":[],"tools":[]},"safety":{"flags":[],"scannedAt":"2026-08-22","hasScripts":false,"networkEndpoints":["boto3.amazonaws.com","docs.aws.amazon.com"]}}