step-functions
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAWS Step Functions
AWS Step Functions
AWS Step Functions is a serverless orchestration service that lets you build and run workflows using state machines. Coordinate multiple AWS services into business-critical applications.
AWS Step Functions是一款无服务器编排服务,可让您借助状态机构建并运行工作流。将多个AWS服务协调到关键业务应用中。
Table of Contents
目录
Core Concepts
核心概念
Workflow Types
工作流类型
| Type | Description | Pricing |
|---|---|---|
| Standard | Long-running, durable, exactly-once | Per state transition |
| Express | High-volume, short-duration | Per execution (time + memory) |
| 类型 | 描述 | 定价 |
|---|---|---|
| 标准型 | 长期运行、持久化、精确一次执行 | 按状态转换次数计费 |
| 快速型 | 高吞吐量、短时长 | 按执行(时间+内存)计费 |
State Types
状态类型
| State | Description |
|---|---|
| Task | Execute work (Lambda, API call) |
| Choice | Conditional branching |
| Parallel | Execute branches concurrently |
| Map | Iterate over array |
| Wait | Delay execution |
| Pass | Pass input to output |
| Succeed | End successfully |
| Fail | End with failure |
| 状态 | 描述 |
|---|---|
| Task | 执行工作(Lambda、API调用) |
| Choice | 条件分支 |
| Parallel | 并发执行分支任务 |
| Map | 遍历数组 |
| Wait | 延迟执行 |
| Pass | 将输入传递到输出 |
| Succeed | 成功结束 |
| Fail | 失败结束 |
Amazon States Language (ASL)
Amazon状态语言(ASL)
JSON-based language for defining state machines.
基于JSON的状态机定义语言。
Common Patterns
常见模式
Simple Lambda Workflow
简单Lambda工作流
json
{
"Comment": "Process order workflow",
"StartAt": "ValidateOrder",
"States": {
"ValidateOrder": {
"Type": "Task",
"Resource": "arn:aws:lambda:us-east-1:123456789012:function:ValidateOrder",
"Next": "ProcessPayment"
},
"ProcessPayment": {
"Type": "Task",
"Resource": "arn:aws:lambda:us-east-1:123456789012:function:ProcessPayment",
"Next": "FulfillOrder"
},
"FulfillOrder": {
"Type": "Task",
"Resource": "arn:aws:lambda:us-east-1:123456789012:function:FulfillOrder",
"End": true
}
}
}json
{
"Comment": "Process order workflow",
"StartAt": "ValidateOrder",
"States": {
"ValidateOrder": {
"Type": "Task",
"Resource": "arn:aws:lambda:us-east-1:123456789012:function:ValidateOrder",
"Next": "ProcessPayment"
},
"ProcessPayment": {
"Type": "Task",
"Resource": "arn:aws:lambda:us-east-1:123456789012:function:ProcessPayment",
"Next": "FulfillOrder"
},
"FulfillOrder": {
"Type": "Task",
"Resource": "arn:aws:lambda:us-east-1:123456789012:function:FulfillOrder",
"End": true
}
}
}Create State Machine
创建状态机
AWS CLI:
bash
aws stepfunctions create-state-machine \
--name OrderWorkflow \
--definition file://workflow.json \
--role-arn arn:aws:iam::123456789012:role/StepFunctionsRole \
--type STANDARDboto3:
python
import boto3
import json
sfn = boto3.client('stepfunctions')
definition = {
"Comment": "Order workflow",
"StartAt": "ProcessOrder",
"States": {
"ProcessOrder": {
"Type": "Task",
"Resource": "arn:aws:lambda:...",
"End": True
}
}
}
response = sfn.create_state_machine(
name='OrderWorkflow',
definition=json.dumps(definition),
roleArn='arn:aws:iam::123456789012:role/StepFunctionsRole',
type='STANDARD'
)AWS CLI:
bash
aws stepfunctions create-state-machine \
--name OrderWorkflow \
--definition file://workflow.json \
--role-arn arn:aws:iam::123456789012:role/StepFunctionsRole \
--type STANDARDboto3:
python
import boto3
import json
sfn = boto3.client('stepfunctions')
definition = {
"Comment": "Order workflow",
"StartAt": "ProcessOrder",
"States": {
"ProcessOrder": {
"Type": "Task",
"Resource": "arn:aws:lambda:...",
"End": True
}
}
}
response = sfn.create_state_machine(
name='OrderWorkflow',
definition=json.dumps(definition),
roleArn='arn:aws:iam::123456789012:role/StepFunctionsRole',
type='STANDARD'
)Start Execution
启动执行
python
import boto3
import json
sfn = boto3.client('stepfunctions')
response = sfn.start_execution(
stateMachineArn='arn:aws:states:us-east-1:123456789012:stateMachine:OrderWorkflow',
name='order-12345',
input=json.dumps({
'order_id': '12345',
'customer_id': 'cust-789',
'items': [{'product_id': 'prod-1', 'quantity': 2}]
})
)
execution_arn = response['executionArn']python
import boto3
import json
sfn = boto3.client('stepfunctions')
response = sfn.start_execution(
stateMachineArn='arn:aws:states:us-east-1:123456789012:stateMachine:OrderWorkflow',
name='order-12345',
input=json.dumps({
'order_id': '12345',
'customer_id': 'cust-789',
'items': [{'product_id': 'prod-1', 'quantity': 2}]
})
)
execution_arn = response['executionArn']Choice State (Conditional Logic)
选择状态(条件逻辑)
json
{
"StartAt": "CheckOrderValue",
"States": {
"CheckOrderValue": {
"Type": "Choice",
"Choices": [
{
"Variable": "$.total",
"NumericGreaterThan": 1000,
"Next": "HighValueOrder"
},
{
"Variable": "$.priority",
"StringEquals": "rush",
"Next": "RushOrder"
}
],
"Default": "StandardOrder"
},
"HighValueOrder": {
"Type": "Task",
"Resource": "arn:aws:lambda:...:function:ProcessHighValue",
"End": true
},
"RushOrder": {
"Type": "Task",
"Resource": "arn:aws:lambda:...:function:ProcessRush",
"End": true
},
"StandardOrder": {
"Type": "Task",
"Resource": "arn:aws:lambda:...:function:ProcessStandard",
"End": true
}
}
}json
{
"StartAt": "CheckOrderValue",
"States": {
"CheckOrderValue": {
"Type": "Choice",
"Choices": [
{
"Variable": "$.total",
"NumericGreaterThan": 1000,
"Next": "HighValueOrder"
},
{
"Variable": "$.priority",
"StringEquals": "rush",
"Next": "RushOrder"
}
],
"Default": "StandardOrder"
},
"HighValueOrder": {
"Type": "Task",
"Resource": "arn:aws:lambda:...:function:ProcessHighValue",
"End": true
},
"RushOrder": {
"Type": "Task",
"Resource": "arn:aws:lambda:...:function:ProcessRush",
"End": true
},
"StandardOrder": {
"Type": "Task",
"Resource": "arn:aws:lambda:...:function:ProcessStandard",
"End": true
}
}
}Parallel Execution
并行执行
json
{
"StartAt": "ProcessInParallel",
"States": {
"ProcessInParallel": {
"Type": "Parallel",
"Branches": [
{
"StartAt": "UpdateInventory",
"States": {
"UpdateInventory": {
"Type": "Task",
"Resource": "arn:aws:lambda:...:function:UpdateInventory",
"End": true
}
}
},
{
"StartAt": "SendNotification",
"States": {
"SendNotification": {
"Type": "Task",
"Resource": "arn:aws:lambda:...:function:SendNotification",
"End": true
}
}
},
{
"StartAt": "UpdateAnalytics",
"States": {
"UpdateAnalytics": {
"Type": "Task",
"Resource": "arn:aws:lambda:...:function:UpdateAnalytics",
"End": true
}
}
}
],
"Next": "Complete"
},
"Complete": {
"Type": "Succeed"
}
}
}json
{
"StartAt": "ProcessInParallel",
"States": {
"ProcessInParallel": {
"Type": "Parallel",
"Branches": [
{
"StartAt": "UpdateInventory",
"States": {
"UpdateInventory": {
"Type": "Task",
"Resource": "arn:aws:lambda:...:function:UpdateInventory",
"End": true
}
}
},
{
"StartAt": "SendNotification",
"States": {
"SendNotification": {
"Type": "Task",
"Resource": "arn:aws:lambda:...:function:SendNotification",
"End": true
}
}
},
{
"StartAt": "UpdateAnalytics",
"States": {
"UpdateAnalytics": {
"Type": "Task",
"Resource": "arn:aws:lambda:...:function:UpdateAnalytics",
"End": true
}
}
}
],
"Next": "Complete"
},
"Complete": {
"Type": "Succeed"
}
}
}Map State (Iteration)
Map状态(迭代)
json
{
"StartAt": "ProcessItems",
"States": {
"ProcessItems": {
"Type": "Map",
"ItemsPath": "$.items",
"MaxConcurrency": 10,
"Iterator": {
"StartAt": "ProcessItem",
"States": {
"ProcessItem": {
"Type": "Task",
"Resource": "arn:aws:lambda:...:function:ProcessItem",
"End": true
}
}
},
"ResultPath": "$.processedItems",
"End": true
}
}
}json
{
"StartAt": "ProcessItems",
"States": {
"ProcessItems": {
"Type": "Map",
"ItemsPath": "$.items",
"MaxConcurrency": 10,
"Iterator": {
"StartAt": "ProcessItem",
"States": {
"ProcessItem": {
"Type": "Task",
"Resource": "arn:aws:lambda:...:function:ProcessItem",
"End": true
}
}
},
"ResultPath": "$.processedItems",
"End": true
}
}
}Error Handling
错误处理
json
{
"StartAt": "ProcessWithRetry",
"States": {
"ProcessWithRetry": {
"Type": "Task",
"Resource": "arn:aws:lambda:...:function:Process",
"Retry": [
{
"ErrorEquals": ["Lambda.ServiceException", "Lambda.TooManyRequestsException"],
"IntervalSeconds": 2,
"MaxAttempts": 6,
"BackoffRate": 2
},
{
"ErrorEquals": ["States.Timeout"],
"IntervalSeconds": 5,
"MaxAttempts": 3,
"BackoffRate": 1.5
}
],
"Catch": [
{
"ErrorEquals": ["CustomError"],
"ResultPath": "$.error",
"Next": "HandleCustomError"
},
{
"ErrorEquals": ["States.ALL"],
"ResultPath": "$.error",
"Next": "HandleAllErrors"
}
],
"End": true
},
"HandleCustomError": {
"Type": "Task",
"Resource": "arn:aws:lambda:...:function:HandleCustom",
"End": true
},
"HandleAllErrors": {
"Type": "Fail",
"Error": "ProcessingFailed",
"Cause": "An error occurred during processing"
}
}
}json
{
"StartAt": "ProcessWithRetry",
"States": {
"ProcessWithRetry": {
"Type": "Task",
"Resource": "arn:aws:lambda:...:function:Process",
"Retry": [
{
"ErrorEquals": ["Lambda.ServiceException", "Lambda.TooManyRequestsException"],
"IntervalSeconds": 2,
"MaxAttempts": 6,
"BackoffRate": 2
},
{
"ErrorEquals": ["States.Timeout"],
"IntervalSeconds": 5,
"MaxAttempts": 3,
"BackoffRate": 1.5
}
],
"Catch": [
{
"ErrorEquals": ["CustomError"],
"ResultPath": "$.error",
"Next": "HandleCustomError"
},
{
"ErrorEquals": ["States.ALL"],
"ResultPath": "$.error",
"Next": "HandleAllErrors"
}
],
"End": true
},
"HandleCustomError": {
"Type": "Task",
"Resource": "arn:aws:lambda:...:function:HandleCustom",
"End": true
},
"HandleAllErrors": {
"Type": "Fail",
"Error": "ProcessingFailed",
"Cause": "An error occurred during processing"
}
}
}CLI Reference
CLI参考
State Machine Management
状态机管理
| Command | Description |
|---|---|
| Create state machine |
| Update definition |
| Delete state machine |
| List state machines |
| Get details |
| 命令 | 描述 |
|---|---|
| 创建状态机 |
| 更新定义 |
| 删除状态机 |
| 列出状态机 |
| 获取详情 |
Executions
执行管理
| Command | Description |
|---|---|
| Start execution |
| Stop execution |
| Get execution details |
| List executions |
| Get execution history |
| 命令 | 描述 |
|---|---|
| 启动执行 |
| 停止执行 |
| 获取执行详情 |
| 列出执行记录 |
| 获取执行历史 |
Best Practices
最佳实践
Design
设计建议
- Keep states focused — one purpose per state
- Use meaningful state names
- Implement comprehensive error handling
- Use Parallel for independent tasks
- Use Map for batch processing
- 保持状态聚焦——每个状态单一职责
- 使用有意义的状态名称
- 实现全面的错误处理
- 对独立任务使用Parallel
- 对批量处理使用Map
Performance
性能优化
- Use Express workflows for high-volume, short tasks
- Set appropriate timeouts
- Limit Map concurrency to avoid throttling
- Use SDK integrations when possible (avoid Lambda wrapper)
- 对高吞吐量、短时长任务使用快速型工作流
- 设置合理的超时时间
- 限制Map并发数以避免节流
- 尽可能使用SDK集成(避免Lambda包装器)
Reliability
可靠性保障
- Retry transient errors
- Catch and handle specific errors
- Use idempotent operations
- Enable X-Ray tracing
- 重试临时错误
- 捕获并处理特定错误
- 使用幂等操作
- 启用X-Ray追踪
Cost Optimization
成本优化
- Use Express for short workflows (< 5 minutes)
- Combine related operations to reduce transitions
- Use Wait states instead of Lambda delays
- 对短时长工作流(<5分钟)使用快速型
- 合并相关操作以减少状态转换次数
- 使用Wait状态替代Lambda延迟
Troubleshooting
故障排查
Execution Failed
执行失败
bash
undefinedbash
undefinedGet execution history
Get execution history
aws stepfunctions get-execution-history
--execution-arn arn:aws:states:us-east-1:123456789012:execution:MyWorkflow:exec-123
--query 'events[?type== || type==]'
--execution-arn arn:aws:states:us-east-1:123456789012:execution:MyWorkflow:exec-123
--query 'events[?type==
TaskFailedExecutionFailedundefinedaws stepfunctions get-execution-history
--execution-arn arn:aws:states:us-east-1:123456789012:execution:MyWorkflow:exec-123
--query 'events[?type== || type==]'
--execution-arn arn:aws:states:us-east-1:123456789012:execution:MyWorkflow:exec-123
--query 'events[?type==
TaskFailedExecutionFailedundefinedLambda Timeout
Lambda超时
Causes:
- Lambda running too long
- Task timeout too short
Fix:
json
{
"Type": "Task",
"Resource": "arn:aws:lambda:...",
"TimeoutSeconds": 300,
"HeartbeatSeconds": 60
}原因:
- Lambda运行时间过长
- 任务超时设置过短
修复方案:
json
{
"Type": "Task",
"Resource": "arn:aws:lambda:...",
"TimeoutSeconds": 300,
"HeartbeatSeconds": 60
}State Stuck
状态停滞
Check:
- Task state waiting for callback
- Wait state not yet elapsed
- Activity worker not responding
检查项:
- Task状态等待回调
- Wait状态尚未到期
- Activity Worker未响应
Invalid State Machine
无效状态机
bash
undefinedbash
undefinedValidate definition
Validate definition
aws stepfunctions validate-state-machine-definition
--definition file://workflow.json
--definition file://workflow.json
undefinedaws stepfunctions validate-state-machine-definition
--definition file://workflow.json
--definition file://workflow.json
undefined