Sub topic 7
Request-response, .sync, and callback patterns
This chapter assumes you can read a Task state in Amazon States Language (ASL), you know what the Resource ARN and Parameters fields do, and you have used a Lambda function and an SQS queue. Every Task state that calls an AWS service uses one of three integration patterns. The pattern decides when the state finishes, so it decides how your workflow behaves when the work behind the call takes seconds, minutes, or days.
The three patterns
The pattern is chosen by the end of the Resource string. No other field changes.
| Pattern | Resource suffix | Task state finishes when | Typical use |
|---|---|---|---|
| Request-response | none | The service returns its HTTP response to the API call | Invoke a Lambda function, put a DynamoDB item, publish to SNS |
| Run a job | `.sync` | The job started by the call reaches a terminal state | Glue job, Batch job, ECS task, Athena query, child state machine |
| Wait for callback | `.waitForTaskToken` | Something calls `SendTaskSuccess` or `SendTaskFailure` with the task token | Human approval, third-party system, legacy queue consumer |
Not every service supports every pattern. The integration table in the Step Functions documentation lists which patterns each API action supports. Request-response is available for all optimized integrations and for the AWS SDK integrations. .sync is available only for specific actions. .waitForTaskToken is available for most optimized integrations and many SDK integrations.
Request-response
Request-response is the default. Step Functions calls the API, receives the response, and moves on. The state's output is that response, shaped by ResultSelector, ResultPath, and OutputPath as usual.
The common mistake is assuming "success" means "the work is done". It only means "the API accepted the request". Consider starting an Athena query with the plain resource:
{
"StartQuery": {
"Type": "Task",
"Resource": "arn:aws:states:::athena:startQueryExecution",
"Parameters": {
"QueryString": "SELECT 1",
"WorkGroup": "primary"
},
"Next": "UseResults"
}
}This state succeeds as soon as Athena returns a QueryExecutionId. The query is probably still running when UseResults starts. The same applies to states:startExecution without a suffix: the parent continues while the child runs, and the parent never learns whether the child failed.
Lambda invoke is request-response, but it is synchronous, so the state finishes when the function returns. For Lambda, "request-response" and "the work is done" coincide, up to the function's own limit of 15 minutes.
Run a job with .sync
Adding .sync tells Step Functions to start the job and then keep the Task state open until the job finishes. You write no polling logic. Step Functions watches the job itself, using EventBridge events or polling depending on the service.
This example runs an AWS Glue job and waits for it:
{
"StartAt": "RunEtlJob",
"States": {
"RunEtlJob": {
"Type": "Task",
"Resource": "arn:aws:states:::glue:startJobRun.sync",
"Parameters": {
"JobName": "nightly-etl",
"Arguments": {
"--run_date.$": "$.runDate"
}
},
"ResultPath": "$.etl",
"TimeoutSeconds": 7200,
"Catch": [
{
"ErrorEquals": ["States.ALL"],
"ResultPath": "$.error",
"Next": "EtlFailed"
}
],
"Next": "EtlDone"
},
"EtlDone": {
"Type": "Succeed"
},
"EtlFailed": {
"Type": "Fail",
"Error": "EtlFailed",
"Cause": "The Glue job did not complete successfully"
}
}
}Points to notice:
- The state fails if the job ends in a failed, stopped, or timed-out status, not only if the API call is rejected. The
Catchtherefore covers the job's outcome as well as the start request. - The output is the service's description of the finished job, so
$.etlholds the final job run details rather than only the start response. TimeoutSecondsbounds the whole wait. If it expires, the state fails withStates.Timeout, and Step Functions tries to stop the running job. Treat that as best effort and confirm in the service console that nothing is still running.- The execution role needs permissions for both the start call and the calls used to watch or stop the job. For Glue that includes
glue:StartJobRun,glue:GetJobRun, andglue:BatchStopJobRun. For services that use EventBridge managed rules, such as Batch, ECS, and nested executions, it also needsevents:PutTargets,events:PutRule, andevents:DescribeRule. A missing permission often shows up as the state hanging or failing with an authorization error. Chapter 11 covers how to scope these.
A related variant is arn:aws:states:::states:startExecution.sync:2. It runs a child state machine and returns the child's output as parsed JSON. The older .sync form without :2 returns the output as an escaped string, which is rarely what you want.
When a service has no .sync
If the service you need lacks a .sync variant, build a poll loop from states you already know:
- A request-response Task starts the work and saves the job ID.
- A
Waitstate pauses for a fixed interval. - A request-response Task calls the "describe" API.
- A
Choicestate routes on the status: back to the Wait, forward to success, or to aFailstate.
This works but costs state transitions on every poll, and it fills the execution history with repeated events. Prefer .sync or a callback when one exists.
Wait for a callback with .waitForTaskToken
The callback pattern pauses the Task state until an outside process reports back. Step Functions generates a unique task token for the state and makes it available as $$.Task.Token in the context object. The double dollar sign reads from the context object rather than from the state input. You pass the token to the outside system, and that system returns it when it has a result.
{
"StartAt": "WaitForApproval",
"States": {
"WaitForApproval": {
"Type": "Task",
"Resource": "arn:aws:states:::sqs:sendMessage.waitForTaskToken",
"Parameters": {
"QueueUrl": "https://sqs.us-east-1.amazonaws.com/123456789012/approvals",
"MessageBody": {
"orderId.$": "$.orderId",
"taskToken.$": "$$.Task.Token"
}
},
"TimeoutSeconds": 86400,
"End": true
}
}
}The SQS call succeeds quickly, but the state does not finish. The execution stays paused, without consuming state transitions, until a worker reads the message and calls back:
import json
import boto3
sfn = boto3.client("stepfunctions")
def approve(task_token: str, order_id: str) -> None:
sfn.send_task_success(
taskToken=task_token,
output=json.dumps({"orderId": order_id, "approved": True}),
)
def reject(task_token: str, reason: str) -> None:
sfn.send_task_failure(
taskToken=task_token,
error="OrderRejected",
cause=reason,
)The output argument must be a JSON string, so use json.dumps. The string becomes the state's result, which then passes through ResultSelector and ResultPath. send_task_failure raises the error name you supply, so a Catch can match OrderRejected by name.
Callback with Lambda
For Lambda, use lambda:invoke.waitForTaskToken and place the token inside Payload:
{
"Type": "Task",
"Resource": "arn:aws:states:::lambda:invoke.waitForTaskToken",
"Parameters": {
"FunctionName": "arn:aws:lambda:us-east-1:123456789012:function:RequestApproval:$LATEST",
"Payload": {
"orderId.$": "$.orderId",
"taskToken.$": "$$.Task.Token"
}
},
"TimeoutSeconds": 3600,
"End": true
}The function returns after it has sent the request. Its own return value is ignored, and the state waits for the token callback. That difference from plain Lambda invocation surprises many people.
Timeouts and heartbeats
Always set TimeoutSeconds on callback tasks. Without it the default timeout is effectively unbounded, up to the one-year limit on a Standard execution, and a lost token leaves the execution stuck.
For long waits where the worker is a running process, add HeartbeatSeconds. The worker calls SendTaskHeartbeat with the token at shorter intervals than that value. If a heartbeat is missed, the state fails with States.HeartbeatTimeout. This detects a crashed worker in minutes instead of waiting for the full timeout.
Choosing a pattern
- Use request-response when the API call itself is the work, as with Lambda, DynamoDB, and SNS, or when you want to start work and not wait for it.
- Use
.syncwhen a supported service runs a job and you need the outcome before continuing. It is the least code and gives the best failure reporting. - Use
.waitForTaskTokenwhen the result comes from something Step Functions cannot watch itself: a person, a partner API, or a system outside AWS. Also use it when the service has no.syncvariant and polling would be wasteful.
Whatever you choose, pair waiting patterns with TimeoutSeconds and a Catch. Failures in the waiting patterns arrive as named errors, such as States.Timeout, States.HeartbeatTimeout, States.TaskFailed, or the custom error from SendTaskFailure.
Exercise
A state machine starts an Amazon Athena query with the resource arn:aws:states:::athena:startQueryExecution and then runs a state that reads the query results. The results step sometimes fails because the query is still running. Give two ways to fix this, and say which workflow type each one requires.
Show answer
First, change the resource to arn:aws:states:::athena:startQueryExecution.sync so the Task state stays open until the query reaches a terminal state. This requires a Standard workflow, because Express workflows do not support .sync. Second, keep the request-response call and add a polling loop: a Wait state, a request-response call to athena:getQueryExecution, and a Choice state that loops back while the status is QUEUED or RUNNING. The loop works in both workflow types, but it costs extra state transitions and clutters the execution history.
Exercise
You use lambda:invoke.waitForTaskToken and the function returns normally after sending the approval email. The execution stays on that state for 23 hours, then fails. What happened, and what two settings would make the failure appear sooner or more clearly?
Show answer
The function's return value does not complete a callback task. The state only completes when something calls SendTaskSuccess or SendTaskFailure with the task token, and nobody did, so the state ran until its timeout and failed with States.Timeout. Set a shorter TimeoutSeconds that matches how long an approval should take, and add a Catch for States.Timeout that routes to a handler such as a reminder or a Fail state. If a running worker owns the token, add HeartbeatSeconds so a crashed worker is detected with States.HeartbeatTimeout.