Durable Workflows Guide

This guide explains how a durable workflow runs and how to write, start, test and operate one. The resource page has the configuration options and limits.

How a run works

A workflow is a function that receives the run's input and a context. You do the work inside context.step calls, and you pause with context.wait or context.waitForCallback.

  • A step runs, and AWS saves its result. This saved result is a checkpoint.
  • A wait ends the invocation. Lambda stops the function. Nothing runs and nothing is billed while the run waits.
  • When the run continues, Lambda calls the function again from the top. This is a replay. Each step that already finished returns its saved result at once, without running its code. The first step that has not finished runs for real.

The same happens after a crash, a timeout of one invocation or a failed attempt that is retried. So a run never repeats a finished step, and it continues where it stopped.

export const onboarding = async (event: { userId: string }, context: DurableContext) => {
  const user = await context.step('load-user', async () => getUser(event.userId)); // replay: saved result
  await context.step('send-welcome', async () => sendWelcome(user)); // replay: saved result
  await context.wait('wait-a-day', { days: 1 }); // the first invocation ends here
  await context.step('send-tips', async () => sendTips(user)); // runs in the second invocation
};

Writing safe steps

Keep code outside steps deterministic

The code outside the steps runs again on every replay. On each replay it must call the same steps in the same order. The SDK matches each call to the saved operation at the same position, so a different order breaks the run.

Anything that can give a different answer the second time belongs inside a step:

  • the current time (Date.now(), new Date())
  • random values and generated IDs (Math.random(), crypto.randomUUID())
  • reads from a database or an API
// Wrong: a replay gets a new date and a new ID.
const invoiceId = crypto.randomUUID();

// Right: the step saves the ID, and replays get the same one.
const invoiceId = await context.step('new-invoice-id', async () => crypto.randomUUID());

Return values from steps instead of changing variables declared outside them. A step that finished does not run on replay, so a change it made to an outside variable is lost.

Environment variables are safe outside steps: a run keeps the environment of the deploy that started it.

Make outside writes safe to repeat

A finished step never runs again. A step can still run more than once:

  • An attempt fails and the step is retried.
  • The invocation crashes or times out after the step did its work and before AWS saved the result.

So Stacktape and AWS do not promise that a step runs exactly once. Give every write to another system a key that makes a repeat harmless:

  • Pass an idempotency key to APIs that accept one, such as Stripe and most email providers. For a welcome email, welcome- plus the user ID works.
  • Use the run's input or a value saved by an earlier step in the key, never a value created inside the same step.
  • For your own database, write with a unique key or an upsert, so a second write changes nothing.

For a step that must not run twice even at the cost of not running, use semantics: StepSemantics.AtMostOnce together with retryStrategy: () => ({ shouldRetry: false }).

Check the code with ESLint

AWS's ESLint plugin reports code that breaks replay: time and random values outside a step, a step that changes an outside variable, and durable operations inside a step.

npm install --save-dev eslint @aws/durable-execution-sdk-js-eslint-plugin @typescript-eslint/parser
// eslint.config.js
import durableExecution from '@aws/durable-execution-sdk-js-eslint-plugin';
import typescriptParser from '@typescript-eslint/parser';

export default [
  { files: ['**/*.ts'], languageOptions: { parser: typescriptParser } },
  { ...durableExecution.configs['flat/recommended'], files: ['src/workflows/**/*.ts'] }
];

Write the workflow as an arrow function, as in the examples here. The plugin does not find the context in a function declaration.

Starting runs

From your code

Add the workflow to connectTo of the resource that starts runs. Stacktape gives that resource the workflow's alias ARN in STP_<NAME>_ARN (for onboarding: STP_ONBOARDING_ARN) and the permissions to start runs, read them and answer callbacks.

Then start a run with @stacktape/workflows:

import { start } from '@stacktape/workflows';
import type { onboarding } from './workflows/onboarding';

const runId = await start<typeof onboarding>('onboarding', { userId }, { id: `onboarding-${userId}` });
  • Pass the type of the workflow function, not of the wrapped handler. withDurableExecution drops the input type, so start<typeof handler> is refused with a type error.
  • The run ID is optional. Without it, start uses a random one.
  • The same ID with the same input returns the existing run and starts nothing new. Use an ID made from the input, such as onboarding-${userId}, when the same work must not run twice.
  • The same ID with a different input throws.
  • A finished run keeps its ID until its history retention ends (historyRetentionDays). To run the same work again, use another ID.

start returns once AWS has accepted the run. It does not wait for the run to finish. Read a run later with getRun('onboarding', runId). It returns the run's input, result and error, so check who asks before an API returns it.

From Python

Python code starts runs with boto3. Use a boto3 version that knows DurableExecutionName; the one in the Lambda runtime can be older, so add boto3 to your requirements.

import json
import os

import boto3

lambda_client = boto3.client("lambda")


def start_onboarding(user_id: str) -> str:
    response = lambda_client.invoke(
        FunctionName=os.environ["STP_ONBOARDING_ARN"],
        InvocationType="Event",
        DurableExecutionName=f"onboarding-{user_id}",
        Payload=json.dumps({"userId": user_id}),
    )
    return response["DurableExecutionArn"]


def approve(callback_id: str, approved_by: str) -> None:
    lambda_client.send_durable_execution_callback_success(
        CallbackId=callback_id,
        Result=json.dumps({"approvedBy": approved_by}),
    )

AWS accepts an existing DurableExecutionName without an error and starts nothing. To detect a second start with a different input, read the run with get_durable_execution(DurableExecutionArn=..., IncludeExecutionData=True) and compare InputPayload. @stacktape/workflows does this for you in Node.js.

From schedules, events and queues

Add an event to the workflow, as for a Lambda function. Schedules, event bus, SNS, S3, CloudWatch Logs and CloudWatch alarm events start runs in the background, and the event is the run's input.

Queue and stream events (sqs, kinesis-stream, dynamo-db-stream, kafka-topic) are different. AWS caps a run started from them at 30 minutes, so they need runTimeout of 1,800 seconds or less, and Stacktape refuses the config otherwise. These runs cannot be given an ID. For longer runs, read the queue in a Lambda function and call start with an ID from the message.

From the CLI and the Console

  • stacktape workflow start starts a run with a JSON input. --wait waits up to 15 minutes and prints the result.
  • The Stacktape Console has Start run on the workflow's Runs tab.

Approvals

context.waitForCallback pauses the run until someone answers. Its second argument receives a callback ID; send that ID to whoever decides, in an email, a Slack message or a row in your admin tool.

const approval = await context.waitForCallback<{ approvedBy: string }>(
  'manager-approval',
  async (callbackId) => notifyApprovers({ userId: event.userId, callbackId }),
  { timeout: { days: 7 }, serdes: defaultSerdes }
);
  • The answer arrives as a string. serdes: defaultSerdes (from @aws/durable-execution-sdk-js) parses it as JSON. Without it, call JSON.parse yourself.
  • timeout ends the wait with an error when nobody answers in time. Without it, the run waits until its runTimeout.
  • A rejection or a timeout makes waitForCallback throw. Catch the error to take another path, or let the run fail.
  • The callback ID works like a password for this one decision. Do not log it in places many people can read.

Answer a callback in one of three ways:

WhereApproveReject
Your appapprove(callbackId, { approvedBy })reject(callbackId, 'reason')
The CLIstacktape workflow approvestacktape workflow reject
The Stacktape ConsoleApprove on the run's pageReject on the run's page

The CLI and the Console find the callback ID of a waiting step themselves. Answering a callback twice fails. In the Console, Needs approval on the Runs tab shows the runs that wait for an answer.

Failures and retries

Retries

A step that throws is retried. With the default strategy, a step that always fails is tried 6 times over about a minute, and then the run fails. Set the retries of a step in code:

import { createRetryStrategy } from '@aws/durable-execution-sdk-js';

await context.step('charge-card', async () => chargeCard(order), {
  retryStrategy: createRetryStrategy({ maxAttempts: 3, initialDelay: { seconds: 10 } })
});

// Never retry this step.
await context.step('send-sms', async () => sendSms(user), { retryStrategy: () => ({ shouldRetry: false }) });

There is no retries option in the Stacktape config. Each retry counts as one more operation in AWS's price.

When a run fails

A failed or timed-out run raises an incident in the Stacktape Console through the workflow's built-in alarms. Find the step that failed with stacktape workflow show or on the run's page in the Console: each attempt has its error and the logs of its invocation.

A failed run cannot continue. AWS does not retry it from the failed step. To recover:

  • Run it again. stacktape workflow rerun or Run again in the Console starts a new run with the same input, on the code deployed now. It starts from the first step. Finished steps of the old run are not reused, so outside writes must be safe to repeat. The new run's ID comes from the old run, the same in the CLI and the Console, so running the same run again finds the rerun that already started.
  • Run all failed runs again. stacktape workflow rerun <workflow> --since 24h or Rerun failed runs in the Console, for example after you deploy a fix. Both take the runs that failed in that period, also ones that started long before it, and failed runs only. A timed-out run usually needs a config change first, so run those again one by one.
  • Stop a run. stacktape workflow stop or Stop in the Console. The step in progress finishes, and no further step starts.

Pause and resume

A retry strategy can pause the run instead of failing it, for example while a missing parameter or an outside outage is fixed. Return pause: true with shouldRetry: true. AWS marks this option as experimental.

A paused run waits until you resume it with stacktape workflow resume or Resume in the Console. It continues with the next attempt of the step that paused, on its original code and configuration. So resume helps after a fix outside your code. After a code fix, run the run again instead. While a run is paused, its runTimeout does not count. A run started outside Stacktape on $LATEST can't be resumed, because it would continue on whatever code is deployed by then; stop it or run it again.

Deploys

Runs keep their code and environment

Each deploy publishes a new version of the workflow and moves its stp-live alias to it. Every run stays on the version that started it, with the environment variables of that deploy. A run that waits for a week wakes up with the code and configuration it started with. Runs started after the deploy use the new code.

This has two consequences:

  • You can change the steps of a workflow freely. A run in progress never replays against new code.
  • A fix does not reach runs in progress. Stop them and run them again, or let them finish.

Fast deploys of a workflow publish a version and move the alias too. stacktape dev deploys workflows to the AWS dev stage, but it does not run them locally or rebuild them when their code changes. Restart dev mode or deploy to publish new workflow code.

Deleting a workflow

Deleting a workflow, by removing it from the config or by deleting the stack, does not stop its runs at once. Lambda keeps the function while runs wait, and each run fails the next time it continues. Stacktape counts the runs in progress and asks before it deletes. Stop the runs first if they should end cleanly.

Testing locally

AWS's testing library runs a workflow in your test process against a local checkpoint server. skipTime: true skips waits and retry delays, so a test of a workflow that waits a day takes milliseconds.

npm install --save-dev @aws/durable-execution-sdk-js-testing vitest
// src/workflows/onboarding.test.ts
import { LocalDurableTestRunner, WaitingOperationStatus } from '@aws/durable-execution-sdk-js-testing';
import { afterAll, beforeAll, expect, it } from 'vitest';
import { handler } from './onboarding';

beforeAll(() => LocalDurableTestRunner.setupTestEnvironment({ skipTime: true }));
afterAll(() => LocalDurableTestRunner.teardownTestEnvironment());

it('onboards a user after approval', async () => {
  const runner = new LocalDurableTestRunner({ handlerFunction: handler });

  // Start without await: the run stops at the approval until the test answers.
  const running = runner.run({ payload: { userId: 'u_1' } });
  const approval = runner.getOperation('manager-approval');
  await approval.waitForData(WaitingOperationStatus.SUBMITTED);
  await approval.sendCallbackSuccess(JSON.stringify({ approvedBy: 'ana' }));

  const execution = await running;
  expect(execution.getStatus()).toBe('SUCCEEDED');
  expect(execution.getResult()).toEqual({ approvedBy: 'ana' });
});
  • runner.getOperation(name) returns one operation: getStepDetails() has its result, error and attempt; getWaitDetails() has the wait.
  • sendCallbackFailure tests a rejection.
  • Steps run in the test process, so your test framework's module mocks work inside them.
  • skipTime installs fake timers. Do not combine it with vi.useFakeTimers().

How a coding agent tests a workflow

An agent with the Stacktape MCP server or the CLI can check a workflow end to end:

  1. Test locally. Run the LocalDurableTestRunner tests with skipTime. They cover the order of steps, waits and approvals without AWS.
  2. Deploy to a dev stage. stacktape deploy --stage dev --region eu-west-1. Later code changes take the fast path.
  3. Start a run and wait for it. stacktape workflow start onboarding --stage dev --region eu-west-1 --payload '{"userId":"u_test"}' --wait --agent. The command fails when the run fails. For a workflow with a long wait or an approval, start without --wait, then answer with stacktape workflow approve.
  4. Read the failing step. stacktape workflow show onboarding <run-id> --stage dev --region eu-west-1 --agent prints JSON with each step's status, attempts and errors, and the Lambda requestId of each invocation. stacktape logs onboarding --stage dev --region eu-west-1 --filter '"<requestId>"' prints the logs of that invocation.
  5. Fix, deploy and run again. stacktape workflow rerun onboarding <run-id> --stage dev --region eu-west-1 starts the same input on the new code.

Through MCP, workflow runs and workflow show run without confirmation. workflow start, stop, resume, rerun, approve and reject change runs, so the agent needs your go-ahead first.

Durable workflow or state machine

See State machine or durable workflow.

Data and the Stacktape Console

The workflow, its runs and their data live in your AWS account. Stacktape does not copy them.

  • Read in your browser. The Console's Runs tab reads runs straight from Lambda and CloudWatch Logs in your account, with credentials limited to that workflow: the list of runs, statuses, inputs, results, step results, errors, approval answers and logs. These never pass through Stacktape's servers.
  • Passed through, not stored. Actions go through the Stacktape API, which calls Lambda in your account. The API sends these values on to Lambda and does not store or log them:
    • Start: the input you enter.
    • Run again and Rerun failed runs: the API reads each original run's input from Lambda and sends it back.
    • Approve: the callback ID and the result you enter.
    • Reject: the callback ID and the reason you enter.
    • Stop and Resume send only the run.
  • Stored in the audit log. Each action records the AWS account, region, stage, workflow, run ID, the step name of an answered approval and the outcome. Never inputs, results or callback IDs.
  • Error tracking. Error messages from the workflow's logs are tracked like those of a Lambda function. Run inputs and outputs stay in your account.

Starting, stopping and answering runs in the Console needs permission to manage resources. On a production stage, the Console asks you to confirm each action. The CLI reads and changes runs in AWS directly with your credentials, and run data does not go to Stacktape.