Skip to content
GitHub Discord

AWS Step Functions task token

Use Step Functions with task tokens to pause execution, send a message to an SQS queue, and resume after processing.

sst.config.ts
// Create a queue the state machine will send messages to
const queue = new sst.aws.Queue("MyQueue");
// Define all the states of the state machine
const sendMessage = sst.aws.StepFunctions.sqsSendMessage({
name: "SendMessage",
integration: "token",
queue,
messageBody: {
// Task token passed in the message body
MyTaskToken: "{% $states.context.Task.Token %}",
},
});
const success = sst.aws.StepFunctions.succeed({ name: "Succeed" });
// Create the state machine
const stepFunction = new sst.aws.StepFunctions("MyStateMachine", {
definition: sendMessage.next(success),
});
// Create a function that will receive messages from the queue
queue.subscribe({
handler: "index.handler",
// Linking the state machine to grant permissions to call `SendTaskSuccess`
link: [stepFunction],
});
index.ts
import { SQSEvent } from "aws-lambda";
import { SFNClient, SendTaskSuccessCommand } from "@aws-sdk/client-sfn";
const sfn = new SFNClient();
export async function handler(e: SQSEvent) {
// Parse the task token
const { body } = e.Records[0];
const { MyTaskToken } = JSON.parse(body);
// Do some work
await new Promise((resolve) => setTimeout(resolve, 1000));
// Call `SendTaskSuccess` to mark the task done
await sfn.send(
new SendTaskSuccessCommand({
taskToken: MyTaskToken,
output: JSON.stringify({ result: "foo" }),
})
);
return "ok";
}

View the full example.