lambda

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

AWS 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

调用类型

TypeDescriptionUse Case
SynchronousCaller waits for responseAPI Gateway, direct invoke
AsynchronousFire and forgetS3, SNS, EventBridge
Poll-basedLambda polls sourceSQS, 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
undefined
AWS CLI:
bash
undefined

Create 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
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

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')
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

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 )
undefined
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 )
undefined

Add S3 Trigger

添加S3触发器

bash
undefined
bash
undefined

Add 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
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)

Configure S3 notification (see S3 skill)

undefined
undefined

Add 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 5
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}"
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
undefined
bash
undefined

Create 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
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

Attach to function

aws lambda update-function-configuration
--function-name MyFunction
--layers arn:aws:lambda:us-east-1:123456789012:layer:my-dependencies:1
undefined
aws lambda update-function-configuration
--function-name MyFunction
--layers arn:aws:lambda:us-east-1:123456789012:layer:my-dependencies:1
undefined

Invoke Function

调用函数

bash
undefined
bash
undefined

Synchronous invoke

Synchronous invoke

aws lambda invoke
--function-name MyFunction
--payload '{"key": "value"}'
response.json
aws lambda invoke
--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
undefined
aws lambda invoke
--function-name MyFunction
--invocation-type Event
--payload '{"key": "value"}'
response.json
undefined

CLI Reference

CLI 参考

Function Management

函数管理

CommandDescription
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
命令描述
aws lambda create-function
创建新函数
aws lambda update-function-code
更新函数代码
aws lambda update-function-configuration
更新设置
aws lambda delete-function
删除函数
aws lambda list-functions
列出所有函数
aws lambda get-function
获取函数详情

Invocation

调用

CommandDescription
aws lambda invoke
Invoke function
aws lambda invoke-async
Async invoke (deprecated)
命令描述
aws lambda invoke
调用函数
aws lambda invoke-async
异步调用(已弃用)

Event Sources

事件源

CommandDescription
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
命令描述
aws lambda create-event-source-mapping
添加事件源
aws lambda list-event-source-mappings
列出事件源映射
aws lambda update-event-source-mapping
更新事件源映射
aws lambda delete-event-source-mapping
删除事件源映射

Permissions

权限

CommandDescription
aws lambda add-permission
Add resource-based policy
aws lambda remove-permission
Remove permission
aws lambda get-policy
View resource policy
命令描述
aws lambda add-permission
添加基于资源的策略
aws lambda remove-permission
移除权限
aws lambda get-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
undefined

GOOD: 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']})
undefined
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']})
undefined

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
  • 最小权限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 seconds
Causes:
  • Function takes longer than timeout
  • Network call to unreachable resource
  • VPC configuration issues
Debug:
bash
undefined
症状:
Task timed out after X seconds
原因:
  • 函数执行时间超过超时限制
  • 网络调用到不可达的资源
  • VPC配置问题
调试:
bash
undefined

Check function configuration

Check function configuration

aws lambda get-function-configuration
--function-name MyFunction
--query "Timeout"
aws lambda get-function-configuration
--function-name MyFunction
--query "Timeout"

Increase timeout

Increase timeout

aws lambda update-function-configuration
--function-name MyFunction
--timeout 60
undefined
aws lambda update-function-configuration
--function-name MyFunction
--timeout 60
undefined

Out 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 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
undefined
原因:
  • 部署包过大
  • VPC配置
  • 需要加载大量依赖
解决方案:
  • 使用预置并发
  • 减小包大小
  • 使用层管理依赖
  • 考虑使用Graviton2(ARM)
bash
undefined

Enable Provisioned Concurrency

Enable Provisioned Concurrency

aws lambda put-provisioned-concurrency-config
--function-name MyFunction
--qualifier LIVE
--provisioned-concurrent-executions 5
undefined
aws lambda put-provisioned-concurrency-config
--function-name MyFunction
--qualifier LIVE
--provisioned-concurrent-executions 5
undefined

Permission Denied

权限拒绝

Symptom:
AccessDeniedException
Debug:
bash
undefined
症状:
AccessDeniedException
调试:
bash
undefined

Check execution role

Check execution role

aws lambda get-function-configuration
--function-name MyFunction
--query "Role"
aws lambda get-function-configuration
--function-name MyFunction
--query "Role"

Check role policies

Check role policies

aws iam list-attached-role-policies
--role-name lambda-role
undefined
aws iam list-attached-role-policies
--role-name lambda-role
undefined

VPC 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端点
  • 检查安全组规则

References

参考资料