Sub topic 3
Doing work with Task states
This chapter assumes you can read and write Amazon States Language (ASL) at the level of the previous chapter: a StartAt, a States map, and Next or End on every state. You should also have written a simple Lambda function and know what an IAM role is.
What a Task state does
A Task state is the only state type that does work. Pass, Choice, Wait, Succeed, and Fail only move data or decide where to go next. A Task calls something outside the state machine, waits for the outcome, and then passes the result to the next state.
A Task state can call:
- A Lambda function or another AWS service, through a service integration.
- An activity, which is a worker you run yourself that polls Step Functions for work.
- Any of the roughly 200 AWS services that the AWS SDK integration supports.
The Resource field, an ARN, chooses the target and the behavior. The next chapters cover service integrations and integration patterns in detail. Here the focus is the shape of a Task state and the fields that control its life cycle.
Anatomy of a Task state
Only Type and Resource are required, plus Next or End to say where execution goes afterwards. Everything else is optional.
| Field | Purpose |
|---|---|
| `Resource` | ARN that selects the integration, such as `arn:aws:states:::lambda:invoke` |
| `Parameters` | The request sent to the target, built from the state input |
| `ResultSelector` | Keeps only the parts of the raw result you want |
| `ResultPath` | Where the selected result is placed in the state's input |
| `TimeoutSeconds` | Maximum time the task may run before failing with `States.Timeout` |
| `HeartbeatSeconds` | Maximum gap between heartbeats for long-running tasks |
| `Retry` | Rules for retrying specific errors |
| `Catch` | Rules for routing failures to a recovery state |
InputPath and OutputPath also apply to Task states. The data flow chapter covers the order in which all five path fields are applied.
Invoking Lambda with the optimized integration
Here is a complete Task state that validates an order:
{
"Comment": "Validate an order and route on the result",
"StartAt": "ValidateOrder",
"States": {
"ValidateOrder": {
"Type": "Task",
"Resource": "arn:aws:states:::lambda:invoke",
"Parameters": {
"FunctionName": "arn:aws:lambda:us-east-1:123456789012:function:ValidateOrder:$LATEST",
"Payload.$": "$"
},
"ResultSelector": {
"validation.$": "$.Payload"
},
"ResultPath": "$.result",
"Retry": [
{
"ErrorEquals": ["Lambda.ServiceException", "Lambda.AWSLambdaException", "Lambda.SdkClientException", "Lambda.TooManyRequestsException"],
"IntervalSeconds": 2,
"MaxAttempts": 3,
"BackoffRate": 2.0
}
],
"Catch": [
{
"ErrorEquals": ["States.ALL"],
"ResultPath": "$.error",
"Next": "OrderFailed"
}
],
"Next": "IsValid"
},
"IsValid": {
"Type": "Choice",
"Choices": [
{
"Variable": "$.result.validation.valid",
"BooleanEquals": true,
"Next": "OrderAccepted"
}
],
"Default": "OrderFailed"
},
"OrderAccepted": {
"Type": "Succeed"
},
"OrderFailed": {
"Type": "Fail",
"Error": "OrderRejected",
"Cause": "Order failed validation or processing"
}
}
}The Lambda function it calls can be this small:
def handler(event, context):
items = event.get("items", [])
valid = bool(event.get("orderId")) and len(items) > 0
return {"valid": valid, "itemCount": len(items)}How the state is processed
Parameters builds the request. A key that ends in .$ is a path expression that Step Functions resolves against the state input. Here "Payload.$": "$" sends the whole state input to the function as its event. A key without .$ is a literal value, so FunctionName is passed as written.
The optimized Lambda integration does not return only your function's return value. It returns an envelope:
{
"ExecutedVersion": "$LATEST",
"Payload": { "valid": true, "itemCount": 2 },
"SdkHttpMetadata": { "HttpStatusCode": 200 },
"SdkResponseMetadata": { "RequestId": "example-request-id" },
"StatusCode": 200
}The metadata is rarely useful downstream, and it counts against the 256 KiB limit on state data. ResultSelector trims the envelope to {"validation": {...}}. ResultPath: "$.result" then merges that object into the original input under result, so later states still see orderId and items.
Without ResultPath, the default is $, which replaces the entire input with the task result. Beginners often hit this: a later state cannot find a field because the Task overwrote it.
The life cycle of one task execution
Retry is evaluated before Catch. If the retries are exhausted, the same error is then checked against Catch. If no Catch matches either, the execution fails.
Timeouts and heartbeats
TimeoutSeconds caps how long a task may run. When it expires, the task fails with the error States.Timeout, and you can retry or catch that error like any other. Without a value, the task has no practical timeout, so a hung downstream call can keep an execution waiting until the workflow's own limit. Standard workflows can run for up to a year, so set an explicit timeout on every Task that waits on something outside your control.
HeartbeatSeconds is for tasks that report progress, such as activities and callback tasks. The worker must call SendTaskHeartbeat at least once per interval. If a heartbeat is missed, the task fails with States.Timeout. Set the heartbeat interval smaller than TimeoutSeconds, so a dead worker is detected long before the overall limit.
{
"Type": "Task",
"Resource": "arn:aws:states:us-east-1:123456789012:activity:ProcessVideo",
"TimeoutSeconds": 3600,
"HeartbeatSeconds": 60,
"End": true
}Choosing a resource type
Three families of Resource ARNs cover most Task states:
- Optimized integrations, such as
arn:aws:states:::lambda:invokeorarn:aws:states:::sqs:sendMessage. Step Functions designed their request and response shapes. They support the.syncand.waitForTaskTokensuffixes where the service allows it. - AWS SDK integrations, such as
arn:aws:states:::aws-sdk:dynamodb:getItem. They map directly to the SDK API, so parameter names follow the service's own API, with the first letter capitalized, such asTableName. - Activities, whose ARN has the form
arn:aws:states:region:account:activity:name. Your worker polls withGetActivityTaskand returns the result withSendTaskSuccessorSendTaskFailure.
You may see a bare Lambda function ARN as the Resource in older definitions. It still works, but the lambda:invoke form is preferred because it supports Parameters for passing a payload and exposes the Lambda service errors for retries.
Errors a Task can raise
A Task can fail in these ways:
- Service errors. For Lambda, these include
Lambda.ServiceException,Lambda.AWSLambdaException,Lambda.SdkClientException, andLambda.TooManyRequestsException. These are usually transient, so they are the right candidates forRetry. - Function errors. An unhandled exception in your function fails the task, and the error name comes from the function's error type. Business errors you raise on purpose belong here, because you can name them and match them in
Catch. - Step Functions errors.
States.Timeout,States.TaskFailed,States.Permissionsfor a missing IAM permission, andStates.ALL, which matches every error exceptStates.DataLimitExceededandStates.Runtime.
Starting and checking an execution
Start an asynchronous execution from the CLI:
aws stepfunctions start-execution \
--state-machine-arn arn:aws:states:us-east-1:123456789012:stateMachine:OrderWorkflow \
--input '{"orderId": "1001"}'The command returns right away with an executionArn and a startDate. It does not wait for the workflow to finish. Pass the ARN to aws stepfunctions describe-execution to see the status and output, or to get-execution-history to see each task's input and result.
Common mistakes
- Forgetting
.$on a key, so Step Functions sends the literal string"$"instead of the state input. - Leaving out
ResultPathand losing the original input. - Setting no
TimeoutSecondson tasks that call slow or unreliable services. - Retrying on
States.ALLfor a function that is not idempotent, which can repeat side effects such as charging a card twice. - Granting the execution role too little. The role needs
lambda:InvokeFunctionon the function ARN, or the task fails withStates.Permissions.
Exercise
A Task state invokes a Lambda function with lambda:invoke. It has no ResultSelector and no ResultPath. The state input is {"orderId": "1001"}, and the function returns {"valid": true}. A Choice state afterwards tests $.orderId. What does it find, and what change keeps both the original fields and a trimmed function result?
Show answer
It finds nothing, and the Choice state fails with States.Runtime because the path does not exist. The default ResultPath is $, so the whole Lambda envelope (Payload, StatusCode, ExecutedVersion, and the metadata) replaces the input. Adding "ResultSelector": {"validation.$": "$.Payload"} and "ResultPath": "$.result" keeps orderId and puts {"valid": true} at $.result.validation.
Exercise
Why should you set both TimeoutSeconds and HeartbeatSeconds on an activity task, and how should the two values relate?
Show answer
TimeoutSeconds bounds the total run time. HeartbeatSeconds detects a dead worker early, because a missed heartbeat fails the task with States.Timeout. The heartbeat interval should be much smaller than the timeout, so a crashed worker is noticed in seconds or minutes instead of after the full timeout.