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.
// Create a queue the state machine will send messages toconst queue = new sst.aws.Queue("MyQueue");
// Define all the states of the state machineconst 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 machineconst stepFunction = new sst.aws.StepFunctions("MyStateMachine", { definition: sendMessage.next(success),});
// Create a function that will receive messages from the queuequeue.subscribe({ handler: "index.handler", // Linking the state machine to grant permissions to call `SendTaskSuccess` link: [stepFunction],});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.