lambda
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAWS Lambda
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.
AWS Lambda 无需预置服务器即可运行代码。您只需为实际消耗的计算时间付费。Lambda 可自动从每天几个请求扩展到每秒数千个请求。
Table of Contents
目录
Core Concepts
核心概念
Function
函数
Your code packaged with configuration. Includes runtime, handler, memory, timeout, and IAM role.
包含配置的代码包。包括运行时、处理程序、内存、超时时间和IAM角色。
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 |
| 类型 | 描述 | 使用场景 |
|---|---|---|
| 同步调用 | 调用方等待响应 | API Gateway、直接调用 |
| 异步调用 | 触发后无需等待 | S3、SNS、EventBridge |
| 轮询式调用 | Lambda 轮询数据源 | 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
Lambda 创建执行环境来运行您的函数。组成部分:
- 冷启动:新环境初始化
- 热启动:复用现有环境
- 处理程序:入口点函数
- 上下文:运行时信息
Layers
层
Reusable packages of libraries, dependencies, or custom runtimes (up to 5 per function).
可复用的库、依赖项或自定义运行时包(每个函数最多可附加5个)。
Common Patterns
常见模式
Create a Python Function
创建Python函数
AWS CLI:
bash
undefinedAWS CLI:
bash
undefinedCreate deployment package
Create deployment package
zip function.zip lambda_function.py
zip function.zip lambda_function.py
Create function
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
--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
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
--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
Update function code
aws lambda update-function-code
--function-name MyFunction
--zip-file fileb://function.zip
--function-name MyFunction
--zip-file fileb://function.zip
**boto3:**
```python
import boto3
import zipfile
import io
lambda_client = boto3.client('lambda')aws lambda update-function-code
--function-name MyFunction
--zip-file fileb://function.zip
--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
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)
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
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
)
undefinedlambda_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
)
undefinedAdd S3 Trigger
添加S3触发器
bash
undefinedbash
undefinedAdd permission for S3 to invoke Lambda
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
--function-name MyFunction
--statement-id s3-trigger
--action lambda:InvokeFunction
--principal s3.amazonaws.com
--source-arn arn:aws:s3:::my-bucket
--source-account 123456789012
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
--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)
Configure S3 notification (see S3 skill)
undefinedundefinedAdd SQS Event Source
添加SQS事件源
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 5bash
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 5Environment 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}"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
undefinedbash
undefinedCreate 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
--layer-name my-dependencies
--compatible-runtimes python3.12
--zip-file fileb://layer.zip
zip -r layer.zip python/
aws lambda publish-layer-version
--layer-name my-dependencies
--compatible-runtimes python3.12
--zip-file fileb://layer.zip
--layer-name my-dependencies
--compatible-runtimes python3.12
--zip-file fileb://layer.zip
Attach to function
Attach to function
aws lambda update-function-configuration
--function-name MyFunction
--layers arn:aws:lambda:us-east-1:123456789012:layer:my-dependencies:1
--function-name MyFunction
--layers arn:aws:lambda:us-east-1:123456789012:layer:my-dependencies:1
undefinedaws lambda update-function-configuration
--function-name MyFunction
--layers arn:aws:lambda:us-east-1:123456789012:layer:my-dependencies:1
--function-name MyFunction
--layers arn:aws:lambda:us-east-1:123456789012:layer:my-dependencies:1
undefinedInvoke Function
调用函数
bash
undefinedbash
undefinedSynchronous invoke
Synchronous invoke
aws lambda invoke
--function-name MyFunction
--payload '{"key": "value"}'
response.json
--function-name MyFunction
--payload '{"key": "value"}'
response.json
aws lambda invoke
--function-name MyFunction
--payload '{"key": "value"}'
response.json
--function-name MyFunction
--payload '{"key": "value"}'
response.json
Asynchronous invoke
Asynchronous invoke
aws lambda invoke
--function-name MyFunction
--invocation-type Event
--payload '{"key": "value"}'
response.json
--function-name MyFunction
--invocation-type Event
--payload '{"key": "value"}'
response.json
undefinedaws lambda invoke
--function-name MyFunction
--invocation-type Event
--payload '{"key": "value"}'
response.json
--function-name MyFunction
--invocation-type Event
--payload '{"key": "value"}'
response.json
undefinedCLI Reference
CLI 参考
Function Management
函数管理
| Command | Description |
|---|---|
| Create new function |
| Update function code |
| Update settings |
| Delete function |
| List all functions |
| Get function details |
| 命令 | 描述 |
|---|---|
| 创建新函数 |
| 更新函数代码 |
| 更新设置 |
| 删除函数 |
| 列出所有函数 |
| 获取函数详情 |
Invocation
调用
| Command | Description |
|---|---|
| Invoke function |
| Async invoke (deprecated) |
| 命令 | 描述 |
|---|---|
| 调用函数 |
| 异步调用(已弃用) |
Event Sources
事件源
| Command | Description |
|---|---|
| Add event source |
| List mappings |
| Update mapping |
| Remove mapping |
| 命令 | 描述 |
|---|---|
| 添加事件源 |
| 列出事件源映射 |
| 更新事件源映射 |
| 删除事件源映射 |
Permissions
权限
| Command | Description |
|---|---|
| Add resource-based policy |
| Remove permission |
| 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
undefined- 合理配置内存:内存越多,CPU越强,执行速度越快
- 减少冷启动:保持函数预热,使用预置并发
- 优化包大小:更小的包部署速度更快
- 使用层管理共享依赖
- 在处理程序外初始化:跨调用复用连接
python
undefinedGOOD: Initialize outside handler
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']})
undefinedimport boto3
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('MyTable')
def handler(event, context):
# Reuses existing connection
return table.get_item(Key={'id': event['id']})
undefinedSecurity
安全
- 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
- 最小权限IAM角色 — 仅授予必要的权限
- 使用Secrets Manager存储敏感数据
- 仅在需要时启用VPC(会增加延迟)
- 使用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
- 设置合适的超时时间 — 不要不必要地使用最长15分钟的超时
- 使用ARM架构(Graviton2)可提升34%的性价比
- 尽可能批量处理
- 使用预留并发限制成本
Reliability
可靠性
- Configure DLQ for async invocations
- Handle retries — async events retry twice
- Make handlers idempotent
- Use structured logging
- 为异步调用配置死信队列(DLQ)
- 处理重试 — 异步事件会重试两次
- 确保处理程序幂等
- 使用结构化日志
Troubleshooting
故障排除
Timeout Errors
超时错误
Symptom:
Task timed out after X secondsCauses:
- Function takes longer than timeout
- Network call to unreachable resource
- VPC configuration issues
Debug:
bash
undefined症状:
Task timed out after X seconds原因:
- 函数执行时间超过超时限制
- 网络调用到不可达的资源
- VPC配置问题
调试:
bash
undefinedCheck function configuration
Check function configuration
aws lambda get-function-configuration
--function-name MyFunction
--query "Timeout"
--function-name MyFunction
--query "Timeout"
aws lambda get-function-configuration
--function-name MyFunction
--query "Timeout"
--function-name MyFunction
--query "Timeout"
Increase timeout
Increase timeout
aws lambda update-function-configuration
--function-name MyFunction
--timeout 60
--function-name MyFunction
--timeout 60
undefinedaws lambda update-function-configuration
--function-name MyFunction
--timeout 60
--function-name MyFunction
--timeout 60
undefinedOut of Memory
内存不足
Symptom: Function crashes with memory error
Fix:
bash
aws lambda update-function-configuration \
--function-name MyFunction \
--memory-size 512症状: 函数因内存错误崩溃
修复:
bash
aws lambda update-function-configuration \
--function-name MyFunction \
--memory-size 512Cold 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
undefined原因:
- 部署包过大
- VPC配置
- 需要加载大量依赖
解决方案:
- 使用预置并发
- 减小包大小
- 使用层管理依赖
- 考虑使用Graviton2(ARM)
bash
undefinedEnable Provisioned Concurrency
Enable Provisioned Concurrency
aws lambda put-provisioned-concurrency-config
--function-name MyFunction
--qualifier LIVE
--provisioned-concurrent-executions 5
--function-name MyFunction
--qualifier LIVE
--provisioned-concurrent-executions 5
undefinedaws lambda put-provisioned-concurrency-config
--function-name MyFunction
--qualifier LIVE
--provisioned-concurrent-executions 5
--function-name MyFunction
--qualifier LIVE
--provisioned-concurrent-executions 5
undefinedPermission Denied
权限拒绝
Symptom:
AccessDeniedExceptionDebug:
bash
undefined症状:
AccessDeniedException调试:
bash
undefinedCheck execution role
Check execution role
aws lambda get-function-configuration
--function-name MyFunction
--query "Role"
--function-name MyFunction
--query "Role"
aws lambda get-function-configuration
--function-name MyFunction
--query "Role"
--function-name MyFunction
--query "Role"
Check role policies
Check role policies
aws iam list-attached-role-policies
--role-name lambda-role
--role-name lambda-role
undefinedaws iam list-attached-role-policies
--role-name lambda-role
--role-name lambda-role
undefinedVPC Connectivity Issues
VPC连接问题
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
症状: 无法访问互联网或AWS服务
原因:
- 没有用于互联网访问的NAT网关
- 缺少AWS服务的VPC端点
- 安全组阻止出站流量
解决方案:
- 添加NAT网关以访问互联网
- 为AWS服务添加VPC端点
- 检查安全组规则