State Machine

A Stacktape state machine uses AWS Step Functions to orchestrate multi-step workflows with branching, retries, parallel execution, and error handling — without writing orchestration code. Define your workflow in Amazon States Language (ASL), and Stacktape handles the underlying AWS infrastructure. Pay per state transition (~$0.025/1,000 transitions).

When to use

Stacktape state machines are the right choice when your workload involves coordinating multiple steps with dependencies between them. Use a state machine instead of chaining Lambda function calls manually whenever you need visibility into execution state, built-in retries, or branching logic.

  • Multi-step processing pipelines — order processing, ETL pipelines, or data ingestion flows where each step depends on the previous one's output.
  • Workflows with conditional branching — approval flows, content moderation pipelines, or any process that takes different paths based on intermediate results.
  • Tasks requiring automatic retries — payment processing, third-party API calls, or anything that may fail transiently and needs exponential backoff without custom retry logic.
  • Long-running orchestration — processes that span minutes, hours, or days (AWS Standard workflows can run up to one year), such as batch processing or multi-stage deployments.
  • Parallel fan-out / fan-in — splitting work across multiple Lambda functions in parallel and aggregating results.

When NOT to use

Not every coordination problem needs a state machine. For straightforward async processing, single-step operations, or simple event fan-out, lighter Stacktape resources handle the job at lower cost and complexity. State machine transitions cost ~$0.025 per 1,000, which adds up at high volume.

ScenarioBetter alternative
Simple request-response APIHTTP API Gateway with a single Lambda function
One function calling anotherDirect invocation via AWS SDK — no orchestration needed
Decoupled async processingSQS queue trigger on a Lambda function
Fan-out to multiple consumersSNS topic or EventBridge event bus
High-throughput stream processingKinesis stream with a Lambda consumer
Simple scheduled taskA Lambda function with a schedule trigger

Basic example

This example defines two Lambda functions orchestrated by a state machine. The workflow validates an order, branches on the result, and either processes the order or fails. Task states reference each function's ARN with $ResourceParam, which resolves at deploy time.

export default defineConfig(() => {
  const validateOrder = new LambdaFunction({
    packaging: new JsBundleLambdaPackaging({ entryfilePath: './src/validate-order.ts' })
  });

  const processOrder = new LambdaFunction({
    packaging: new JsBundleLambdaPackaging({ entryfilePath: './src/process-order.ts' }),
    timeout: 60
  });

  const orderWorkflow = new StateMachine({
    definition: {
      Comment: 'Order processing workflow',
      StartAt: 'ValidateOrder',
      States: {
        ValidateOrder: {
          Type: 'Task',
          Resource: $ResourceParam('validateOrder', 'arn'),
          Next: 'CheckValidity',
          Catch: [{ ErrorEquals: ['States.ALL'], Next: 'OrderFailed' }]
        },
        CheckValidity: {
          Type: 'Choice',
          Choices: [{ Variable: '$.valid', BooleanEquals: true, Next: 'ProcessOrder' }],
          Default: 'OrderFailed'
        },
        ProcessOrder: {
          Type: 'Task',
          Resource: $ResourceParam('processOrder', 'arn'),
          Retry: [
            {
              ErrorEquals: ['States.TaskFailed'],
              IntervalSeconds: 3,
              MaxAttempts: 2,
              BackoffRate: 2
            }
          ],
          End: true
        },
        OrderFailed: {
          Type: 'Fail',
          Error: 'OrderProcessingFailed',
          Cause: 'Validation or processing failed'
        }
      }
    }
  });

  return {
    resources: { validateOrder, processOrder, orderWorkflow }
  };
});

A state machine definition requires StartAt and States. StartAt names the first state to execute, and States maps state names to state objects — each with a Type field. Most non-terminal states transition with Next or finish with End: true; terminal Succeed and Fail states end execution without needing Next or End.

Task states reference a Lambda function by its name in your config: $ResourceParam('validateOrder', 'arn') resolves to the function's ARN at deploy time. You don't need to look up CloudFormation logical names.

Workflow definition

The StateMachine resource accepts a single definition property using Amazon States Language (ASL) — a JSON-based spec for defining Step Functions workflows. A definition requires StartAt (the first state to execute) and States (a map of state names to state objects). You can optionally set Comment for a human-readable description, Version for the ASL version, and TimeoutSeconds to cap the maximum execution time for the entire workflow.

State types

The Stacktape StateMachine definition models eight ASL state types: Choice, Fail, Map, Parallel, Pass, Succeed, Task, and Wait. Each state type serves a distinct role in the workflow.

State typePurposeKey properties
TaskInvokes a Lambda function or another supported ASL task targetResource, Retry, Catch, TimeoutSeconds, HeartbeatSeconds, Parameters
ChoiceBranches based on input conditionsChoices (condition rules), Default (fallback state)
ParallelRuns multiple branches concurrently, waits for all to completeBranches (each a StartAt/States workflow), Retry, Catch
MapIterates over an array, running a sub-workflow per itemItemProcessor (or the older Iterator), ItemsPath, MaxConcurrency
WaitPauses execution for a duration or until a timestampSeconds, Timestamp, SecondsPath, TimestampPath
PassPasses input to output, optionally injecting or transforming dataResult, Parameters, ResultPath
SucceedMarks successful completion — terminates the workflow—
FailTerminates execution with an errorError, Cause

Task is the most common state type — it's how the state machine invokes your Lambda functions and other AWS services. Choice is the branching mechanism (equivalent to if/else). Parallel and Map handle fan-out patterns. Succeed and Fail are terminal states that end execution without needing Next or End. See the ASL specification for full syntax details.

Stacktape checks the state types and the fields listed above. Other ASL fields, such as QueryLanguage, Arguments or Assign, are passed to AWS unchanged, and a path set to null (for example OutputPath: null) is kept.

Referencing Lambda functions

Task states use the Resource property to identify a Lambda function or another supported ASL task target. For a function in the same config, use the $ResourceParam directive with the function's resource name and its arn parameter. Stacktape resolves it to the function's ARN at deploy time.

resources:
  scoreReceipt:
    type: function
    properties:
      packaging:
        type: js-bundle
        properties:
          entryfilePath: src/score-receipt.ts
  approvalWorkflow:
    type: state-machine
    properties:
      definition:
        StartAt: ScoreReceipt
        States:
          ScoreReceipt:
            Type: Task
            Resource: $ResourceParam('scoreReceipt', 'arn')
            End: true

Use a plain string when you already have a concrete Task Resource value, such as the ARN of a function outside this config or an ASL service integration URI. An object with a CloudFormation intrinsic function, such as Fn::GetAtt, also works when you need one.

You can also set TimeoutSeconds on a Task state to limit how long the state machine waits for the task to complete, and HeartbeatSeconds to require periodic heartbeat signals from long-running tasks. The Parameters property lets you reshape the input before passing it to the task.

Workflow timeout

Set TimeoutSeconds at the top level of your definition to limit the maximum execution time for the entire workflow. This is a safeguard against runaway executions — without it, AWS Standard Step Functions workflows can run for up to one year. For any workflow that should complete within a predictable window (minutes or hours), always set a timeout.

Error handling

AWS Step Functions provides built-in error handling through Retry and Catch blocks on Task, Parallel, and Map states. This replaces the need for custom retry logic in your Lambda function code and gives you a declarative way to handle failures at the orchestration layer.

Retry accepts an array of rules, each specifying which errors to match (ErrorEquals), the initial delay (IntervalSeconds), maximum attempts (MaxAttempts), and backoff multiplier (BackoffRate). Multiple retry rules are evaluated in order — the first matching rule is used.

Catch routes to a fallback state when all retries are exhausted or for errors not covered by retry rules. Each catch rule matches error types (ErrorEquals) and redirects to a named state (Next). This lets you build graceful degradation paths — for example, notifying a support team when payment processing fails after retries.

const paymentWorkflow = new StateMachine({
  definition: {
    StartAt: 'ChargePayment',
    States: {
      ChargePayment: {
        Type: 'Task',
        Resource: $ResourceParam('chargePayment', 'arn'),
        Retry: [
          {
            ErrorEquals: ['States.TaskFailed'],
            IntervalSeconds: 5,
            MaxAttempts: 3,
            BackoffRate: 2
          }
        ],
        Catch: [
          {
            ErrorEquals: ['States.ALL'],
            Next: 'NotifySupport'
          }
        ],
        Next: 'PaymentComplete'
      },
      NotifySupport: {
        Type: 'Task',
        Resource: $ResourceParam('notifySupport', 'arn'),
        Next: 'PaymentFailed'
      },
      PaymentFailed: {
        Type: 'Fail',
        Error: 'PaymentError',
        Cause: 'Payment failed after 3 retries'
      },
      PaymentComplete: {
        Type: 'Succeed'
      }
    }
  }
});

In this example, ChargePayment retries up to 3 times on failure with exponential backoff (5s, 10s, 20s). If all retries fail, Catch redirects to NotifySupport, which alerts the support team before the workflow terminates with a Fail state. Without the retry block, any transient error would immediately fail the workflow.

Retry and Catch match error strings in ErrorEquals. Common ASL error names include States.ALL, States.TaskFailed, States.Timeout, and States.HeartbeatTimeout. You can also match custom error strings thrown by your Lambda functions. See the ASL specification for the complete list and matching rules.

Starting executions

The StateMachine resource configures only the workflow definition. To start executions from application code, pass the state machine ARN to a workload and call Step Functions with the AWS SDK. Use connectTo to scope the consuming workload's IAM role for the state machine, and the $ResourceParam directive to inject the state machine ARN as an environment variable.

const startOrder = new LambdaFunction({
  packaging: new JsBundleLambdaPackaging({ entryfilePath: './src/start-order.ts' }),
  connectTo: [orderWorkflow],
  environment: { ORDER_WORKFLOW_ARN: "$ResourceParam('orderWorkflow', 'arn')" }
});

State machines are accepted by connectTo for workload IAM role scoping — listing 'orderWorkflow' grants the consuming workload permissions for the state machine. The environment entry uses $ResourceParam('orderWorkflow', 'arn') to inject the state machine ARN at deploy time. State machines expose arn and name as referenceable parameters.

Listing a state machine in connectTo grants the consuming workload the IAM permissions required to interact with the state machine (e.g., starting and describing executions). Use $ResourceParam('orderWorkflow', 'arn') to pass the state machine ARN as an environment variable. State machines expose arn and name as referenceable parameters.

Use the ARN in your handler to start executions:

import { Hono } from 'hono';
import { handle } from 'hono/aws-lambda';
import { SFNClient, StartExecutionCommand, DescribeExecutionCommand } from '@aws-sdk/client-sfn';

const sfn = new SFNClient({});
const stateMachineArn = process.env.ORDER_WORKFLOW_ARN!;

const app = new Hono();

app.post('/orders', async (c) => {
  const input = await c.req.text() || '{}';
  const result = await sfn.send(
    new StartExecutionCommand({ stateMachineArn, input })
  );
  return c.json({ executionArn: result.executionArn }, 202);
});

app.get('/orders/status/:executionArn{.+}', async (c) => {
  const executionArn = decodeURIComponent(c.req.param('executionArn'));
  const result = await sfn.send(new DescribeExecutionCommand({ executionArn }));
  return c.json({
    status: result.status,
    output: result.output ? JSON.parse(result.output) : null
  });
});

export default handle(app);

This handler code starts a workflow execution and returns the execution ARN, with a second route for polling execution status. To expose these routes as HTTP endpoints, attach the startOrder Lambda function to an HTTP API Gateway or Application Load Balancer using an event integration. The @aws-sdk/client-sfn package provides StartExecutionCommand, DescribeExecutionCommand, StopExecutionCommand, and other Step Functions operations.

Overrides

The StateMachine resource supports overrides for modifying the generated CloudFormation resources. The StateMachineProps type exposes only the ASL definition property — CloudFormation-level settings not modeled by the type (such as logging configuration or the workflow type) must be set through overrides. Use overrides as an escape hatch only after inspecting the compiled template and confirming the logical resource path you need to modify.

For example, to switch the state machine to an Express workflow (higher throughput, lower per-transition cost, 5-minute maximum duration), override the StateMachineType property on the generated AWS::StepFunctions::StateMachine resource. First run stacktape synth to find the logical name. The example below assumes the logical name is OrderWorkflowStateMachine — verify yours against the compiled output.

const orderWorkflow = new StateMachine({
  definition: {
    StartAt: 'Process',
    States: {
      Process: { Type: 'Pass', End: true }
    }
  },
  overrides: {
    OrderWorkflowStateMachine: {
      'Properties.StateMachineType': 'EXPRESS'
    }
  }
});

The overrides object keys are CloudFormation logical names, and values use dot-notation paths into the resource properties. StateMachineType accepts STANDARD (default) or EXPRESS. See overrides for full syntax details.

Use stacktape synth to inspect the CloudFormation resources generated for the state machine before applying overrides.

Referenceable parameters

State machines expose arn and name as referenceable parameters. Use these with the $ResourceParam directive anywhere in your config, or pass them as environment variables to other resources.

The following parameters can be easily referenced using $ResourceParam directive directive.

To learn more about referencing parameters, refer to referencing parameters.

arn
  • Arn of the state machine.

  • Usage: $ResourceParam('<<resource-name>>', 'arn')
name
  • AWS (physical) name of the state machine.

  • Usage: $ResourceParam('<<resource-name>>', 'name')

API Reference

StateMachineProps
Click a property in the tree to see its description, default value, and full type.

State Machine FAQ

How do I reference Lambda functions in a state machine definition?

Put the function's ARN in the Task state's Resource field with the $ResourceParam directive: Resource: $ResourceParam('processOrder', 'arn'), where processOrder is the function's name in your config. Stacktape resolves it at deploy time, so you don't need CloudFormation logical names.

How do I pass the state machine ARN to a Lambda function?

Use connectTo to grant IAM permissions, and add an environment entry with the $ResourceParam directive to inject the ARN. For example, { name: 'MY_WORKFLOW_ARN', value: "$ResourceParam('myWorkflow', 'arn')" }. The state machine exposes arn and name as referenceable parameters.

How do I switch to an Express workflow (or change other CloudFormation settings)?

The StateMachineProps type exposes only the ASL definition — anything else, including the workflow type and logging, must be set through overrides. To switch to Express (higher throughput, lower per-transition cost, 5-minute maximum duration), override Properties.StateMachineType to EXPRESS on the generated AWS::StepFunctions::StateMachine resource. Run stacktape synth first to find its logical name, since overrides key off it.

How much do AWS Step Functions cost?

AWS Standard Step Functions charge per state transition (~$0.025/1,000 transitions), so cost scales with how many states each execution passes through. This adds up at high volume — for simple decoupled or single-step work, a Lambda function behind an SQS queue or SNS topic is cheaper. Express workflows use different (per-request + duration) pricing; see How do I switch to an Express workflow and the AWS Step Functions pricing page for current rates.

How long can a Step Functions execution run?

AWS Standard Step Functions workflows can run for up to one year, so a workflow with no timeout can keep transitioning (and billing) indefinitely. Set the top-level TimeoutSeconds property in your definition to cap the whole workflow, and TimeoutSeconds on individual Task states to bound a single step. Use HeartbeatSeconds on Task states to require periodic signals from long-running tasks.

When should I use a state machine vs an SQS queue?

Use a state machine when you need branching logic, ordered multi-step processing, built-in retries with backoff, or workflow visibility (execution history, status tracking). Use an SQS queue for simple decoupled message processing where a single Lambda consumer handles each message independently. SQS is cheaper at high throughput and simpler to set up for one-step async processing.

When should I use a state machine vs direct Lambda-to-Lambda invocation?

Direct invocation (calling one Lambda from another via the AWS SDK) works for simple two-function chains. Use a state machine when you need error handling with retries and fallbacks, conditional branching, parallel execution, or execution history. State machines also avoid the cascading timeout problem — if function A calls B calls C, A's timeout must account for the entire chain. A state machine manages each step's timeout independently.