A Step Functions timeout is one of those settings you only miss once an execution has been sitting at “Running” for three days. No error, no alarm, no log line. The workflow simply waits for an answer that never arrives, because the worker crashed at some point and nobody told it.
In the previous part of the series I covered the timeout chain from API Gateway down to the SDK call. Today I move one level up: to workflows that take minutes or hours. However, a single timeout value is no longer enough there. You need an upper limit per step, a sign of life from the worker and an overall limit for the entire execution, and all three have to fit together. As a result, by the end of this article you will have a runnable CDK project with tests for exactly that.
In short
Callback tasks with a task token, .sync jobs and activities have no default timeout in Step Functions and can hang until the maximum execution duration is reached. So set TimeoutSeconds and HeartbeatSeconds for every such task, let the worker send heartbeats regularly and include retries in the overall execution limit. The biggest pitfall: a timeout in Step Functions stops neither the running Lambda function nor the worker, both have to notice on their own that nobody is waiting anymore.
What you will learn in this article
- When Step Functions waits forever without a timeout and how to prevent it
- The difference between TimeoutSeconds and HeartbeatSeconds
- A worker that sends heartbeats and stops in time
- How to turn retries and time limits into a consistent budget
- Which error names you need to catch and which ones fall short
Why a Step Functions timeout is mandatory
The Amazon States Language, the JSON language used to describe Step Functions workflows, sets no time limits by itself. Simple request-response calls do get a default value, so a normal API call cannot hang endlessly. The longer-running patterns are a different story: according to the documentation, activities, .sync jobs and callbacks with .waitForTaskToken have no default timeout. They wait until the execution reaches its maximum. Consequently, for Standard workflows that can mean a whole year.
A callback task works like this: Step Functions creates a task token, a kind of receipt number, and sends it along with the data to another service, for example an SQS queue. The workflow pauses. Only when someone calls SendTaskSuccess or SendTaskFailure with exactly this token does it continue. So if the worker crashes first or the message gets lost, nobody calls back. The workflow keeps waiting anyway.
What a hanging execution costs
For Standard workflows it hardly costs money, since billing is based on state transitions and not on waiting time. The real cost lies elsewhere. Instead, the process the workflow represents gets stuck in an intermediate state: an order that is never confirmed, a bike that is never released again. And because nothing fails, no alarm goes off either. You only find the problem when someone complains. A timeout therefore turns this silent hang into a visible error your workflow can react to.
Which time limits exist
In a typical Serverless workflow with a worker, several limits also interact. The following table shows who enforces each one and what happens when it is exceeded.
| Limit | Where it is set | What happens when it is exceeded |
|---|---|---|
| Execution TimeoutSeconds | top level of the state machine | execution fails with States.Timeout, cannot be caught |
| Task TimeoutSeconds | in the task state | task fails with States.Timeout, Retry and Catch apply |
| HeartbeatSeconds | in the task state | task fails if no heartbeat arrived for too long |
| Lambda timeout | on the function | Lambda aborts, Step Functions sees Sandbox.Timedout or Lambda.Unknown
|
| Visibility timeout | on the SQS queue | message becomes visible again and is redelivered |
| Budget in the worker | in your own code | worker aborts in a controlled way and reports an error |
TimeoutSeconds and HeartbeatSeconds compared
TimeoutSeconds is the maximum duration of one task attempt. The clock starts as soon as the task begins and cannot be extended. Heartbeats do not change that either: the API reference for SendTaskHeartbeat makes it clear that a task’s timeout is its maximum duration, no matter how many heartbeats arrive.
HeartbeatSeconds, on the other hand, measures the gap between two signs of life. In addition, every call to SendTaskHeartbeat resets this clock. The value must be lower than TimeoutSeconds. This lets you tell two situations apart cleanly: you notice “the worker is dead” after seconds via the heartbeat, and “the work simply takes too long” after minutes via the timeout.
An image that helps me here: you take your bike to the workshop. The timeout is the promise “it will be ready by 6 pm”. The heartbeat, on the other hand, is the agreement “give me a quick call every hour”. If nobody calls, you already know at noon that something is wrong and don’t have to wait until the evening.
Which error name you need to catch
This is where things get a bit messy, and I would rather say so openly. The error handling page lists a dedicated error States.HeartbeatTimeout for missing heartbeats. The task state page and the description of the callback patterns, however, say that a missing heartbeat ends with States.Timeout. That is why I always catch both names in Catch blocks. After all, it costs one line and saves you a surprise.
Two more details are worth knowing. In Retry and Catch, States.TaskFailed acts as a wildcard for almost all errors but explicitly excludes States.Timeout. States.ALL, in contrast, does include the timeout. And when a nested state machine runs into a timeout, the parent workflow receives a States.TaskFailed.
What happens with a Lambda task
For a Lambda task, TimeoutSeconds only limits how long Step Functions waits for the response. The function itself keeps running until it finishes or its own Lambda timeout kicks in. If the task timeout is shorter than the Lambda timeout and you have configured a retry on States.Timeout, in the worst case two invocations of the same function run in parallel. My rule of thumb is therefore: the task timeout sits a few seconds above the Lambda timeout. Then the function normally reports an error itself, and the task timeout is just the safety net.
The example: battery check at a bike rental
For the code, I stick with the fictional bike rental from the previous part, since it already has the right moving parts. When an e-bike is returned, a workflow with two steps starts. First, a small Lambda function calculates the rental fee. After that, a battery diagnosis runs which, depending on the bike, takes a good minute: measure the voltage, read the charge cycles, test the capacity. A worker behind an SQS queue handles this diagnosis, while Step Functions waits for the result via a task token.
The worker reports in with a heartbeat every 20 seconds. Should it stay silent for 60 seconds, it is considered dead. When the bike is currently unreachable, the workflow tries again after a pause. If the check finally hangs or fails, the workshop gets a message via SNS, and the execution ends with a clear error instead of waiting forever.
🎬 Flow: callback task with heartbeats – this animated diagram only runs on my site: watch it on sascha-ms.de
Working out the time budget
Before I write any code, I work through the budget once from the outside in. The execution may take at most 20 minutes. Specifically, the battery check gets 5 minutes per attempt and up to two retries with pauses of 30 and 60 seconds. That makes three times five minutes plus one and a half minutes of waiting, so 16.5 minutes. Even with the Lambda task in front of it, there is still enough headroom up to 20 minutes.
Similarly, the principle applies within a single attempt. The worker Lambda has a 4-minute timeout, which is less than the task’s 5 minutes. In code, it also only allows itself its remaining time minus 10 seconds. That leaves time to still send SendTaskFailure when aborting, instead of simply being killed. Following the AWS recommendation, the queue’s visibility timeout is six times the Lambda timeout, so 24 minutes.
The budget from the outside in: every layer stays below the limit of its caller.
Step by step: implementing a Step Functions timeout with CDK
This time it is AWS CDK’s turn, the previous part used the Serverless Framework. You will also find all files in the example repository at the end.
Prerequisites
- Node.js 22 or newer and npm
- An AWS account and configured credentials for the AWS CLI (only for deployment)
- AWS CDK v2, prepared once in the target account with
npx cdk bootstrap - Basic knowledge of Lambda and SQS, I explain Step Functions along the way
Step 1: Create the project
mkdir step-functions-timeouts && cd step-functions-timeouts
npm init -y
npm install aws-cdk-lib constructs @aws-sdk/client-sfn
npm install -D typescript tsx vitest esbuild aws-cdk @types/node @types/aws-lambda
mkdir bin lib src test
Then replace the package.json with this version that includes scripts for build, tests and synth:
{
"name": "step-functions-timeouts",
"version": "1.0.0",
"private": true,
"type": "module",
"scripts": {
"build": "tsc --noEmit",
"test": "vitest run",
"synth": "cdk synth",
"deploy": "cdk deploy"
},
"dependencies": {
"@aws-sdk/client-sfn": "^3.1168.0",
"aws-cdk-lib": "^2.277.0",
"constructs": "^10.8.1"
},
"devDependencies": {
"@types/aws-lambda": "^8.10.164",
"@types/node": "^24.19.2",
"aws-cdk": "^2.1148.1",
"esbuild": "^0.25.12",
"tsx": "^4.23.15",
"typescript": "5.9",
"vitest": "^5.1.0"
}
}
The tsconfig.json is deliberately plain and strict:
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"types": ["node"]
},
"include": ["bin", "lib", "src", "test"]
}
Finally, the cdk.json only states how CDK starts the app. tsx runs TypeScript directly, so no separate build step is needed:
{
"app": "npx tsx bin/app.ts"
}
Step 2: Calculate the fee
The first Lambda function is deliberately small, so it stays easy to follow. Later it shows how the task timeout and the Lambda timeout relate to each other.
// src/calculate-fee.ts
export interface ReturnInput {
rentalId: string;
bikeId: string;
minutes: number;
}
export interface Fee {
amountCents: number;
currency: 'EUR';
}
const UNLOCK_CENTS = 100;
const PER_MINUTE_CENTS = 25;
export const handler = async (input: ReturnInput): Promise<Fee> => {
if (!Number.isInteger(input.minutes) || input.minutes < 0) {
throw new Error(`Invalid rental duration: ${input.minutes}`);
}
return { amountCents: UNLOCK_CENTS + input.minutes * PER_MINUTE_CENTS, currency: 'EUR' };
};
Step 3: The heartbeat helper
The core of the worker is a function that runs any piece of work and sends heartbeats in the background meanwhile. Two decisions are built into it. The first heartbeat goes out immediately, before the work starts. If the task has already expired, for example because the SQS message was redelivered after a crash, Step Functions responds with TaskTimedOut, and the worker doesn’t even get started. On top of that, the helper aborts the running work via an AbortSignal as soon as Step Functions no longer knows the task.
// src/heartbeat.ts
import { SendTaskHeartbeatCommand, type SFNClient } from '@aws-sdk/client-sfn';
/** Errors that mean: Step Functions is no longer waiting for this task. */
const TASK_GONE_ERRORS = new Set(['TaskTimedOut', 'TaskDoesNotExist', 'InvalidToken']);
export class TaskGoneError extends Error {
constructor(reason: string) {
super(`Step Functions is no longer waiting for this task (${reason})`);
this.name = 'TaskGoneError';
}
}
export function isTaskGone(err: unknown): boolean {
return err instanceof Error && TASK_GONE_ERRORS.has(err.name);
}
export interface HeartbeatOptions {
taskToken: string;
intervalMs: number;
client: Pick<SFNClient, 'send'>;
}
/**
* Runs `work` and sends heartbeats at a regular interval meanwhile.
* The first heartbeat goes out immediately: if the task has already expired,
* we don't even start working.
*/
export async function runWithHeartbeat<T>(
work: (signal: AbortSignal) => Promise<T>,
{ taskToken, intervalMs, client }: HeartbeatOptions,
): Promise<T> {
const controller = new AbortController();
const beat = async (): Promise<void> => {
try {
await client.send(new SendTaskHeartbeatCommand({ taskToken }));
} catch (err) {
if (isTaskGone(err)) {
controller.abort(new TaskGoneError((err as Error).name));
return;
}
// Network hiccup: simply try again at the next interval
console.warn('Heartbeat failed, will retry at next interval', err);
}
};
await beat();
if (controller.signal.aborted) throw controller.signal.reason;
const timer = setInterval(() => void beat(), intervalMs);
try {
return await work(controller.signal);
} finally {
clearInterval(timer);
}
}
Individual network errors during a heartbeat do not cause an abort. With a 20-second interval and a 60-second window, a heartbeat may get lost now and then without the task dying.
Step 4: The simulated battery diagnosis
I simulate the actual diagnosis with three waiting periods. However, it is important that it respects the AbortSignal. With a real interface, you would then pass the signal on to fetch or the SDK call. Also, bikes with an ID starting with offline- are unreachable for testing purposes.
// src/battery-diagnosis.ts
import { setTimeout as sleep } from 'node:timers/promises';
export interface BatteryReport {
bikeId: string;
healthPercent: number;
chargeCycles: number;
verdict: 'ok' | 'replace';
}
/** The bike does not respond – a temporary error, another attempt is worthwhile. */
export class BikeOfflineError extends Error {
constructor(bikeId: string) {
super(`E-bike ${bikeId} is not reachable`);
this.name = 'BikeOfflineError';
}
}
const STEP_MS = Number(process.env.DIAGNOSIS_STEP_MS ?? '15000');
/**
* Simulated battery diagnosis in three steps (voltage, cycles, capacity test).
* In real life, this would query the battery's interface.
*/
export async function runBatteryDiagnosis(bikeId: string, signal: AbortSignal): Promise<BatteryReport> {
if (bikeId.startsWith('offline-')) throw new BikeOfflineError(bikeId);
for (const step of ['voltage', 'charge cycles', 'capacity test']) {
console.log(`Diagnosis ${bikeId}: ${step}`);
await sleep(STEP_MS, undefined, { signal });
}
const seed = [...bikeId].reduce((sum, ch) => sum + ch.charCodeAt(0), 0);
const healthPercent = 55 + (seed % 45);
return {
bikeId,
healthPercent,
chargeCycles: 120 + (seed % 600),
verdict: healthPercent < 70 ? 'replace' : 'ok',
};
}
Step 5: The worker
The worker reads the SQS message, runs the diagnosis through the heartbeat helper and reports the result to Step Functions. It translates errors into custom error names such as BatteryCheck.BikeOffline that the state machine can react to specifically. So the workflow decides about retries, not the queue. That matters here: a redelivery via SQS would only happen after 24 minutes, which is far too late.
// src/battery-check-worker.ts
import type { Context, SQSBatchResponse, SQSEvent } from 'aws-lambda';
import { SFNClient, SendTaskFailureCommand, SendTaskSuccessCommand } from '@aws-sdk/client-sfn';
import { BikeOfflineError, runBatteryDiagnosis, type BatteryReport } from './battery-diagnosis.js';
import { isTaskGone, runWithHeartbeat, TaskGoneError } from './heartbeat.js';
export interface CheckRequest {
taskToken: string;
rentalId: string;
bikeId: string;
}
export interface WorkerDeps {
client: Pick<SFNClient, 'send'>;
diagnose: (bikeId: string, signal: AbortSignal) => Promise<BatteryReport>;
heartbeatIntervalMs: number;
budgetMs: number;
}
/** Aborted promises (e.g. from timers/promises) wrap the reason in `cause`. */
function rootCause(err: unknown): unknown {
return err instanceof Error && err.name === 'AbortError' && err.cause ? err.cause : err;
}
/** Maps an error to the error name the state machine evaluates. */
function errorName(err: unknown): string {
if (err instanceof BikeOfflineError) return 'BatteryCheck.BikeOffline';
if (err instanceof Error && err.name === 'TimeoutError') return 'BatteryCheck.TooSlow';
return 'BatteryCheck.Unexpected';
}
export async function processCheck(req: CheckRequest, deps: WorkerDeps): Promise<'success' | 'failure' | 'gone'> {
const { client } = deps;
const { taskToken } = req;
try {
const report = await runWithHeartbeat(
(signal) => deps.diagnose(req.bikeId, AbortSignal.any([signal, AbortSignal.timeout(deps.budgetMs)])),
{ taskToken, intervalMs: deps.heartbeatIntervalMs, client },
);
await client.send(new SendTaskSuccessCommand({ taskToken, output: JSON.stringify(report) }));
return 'success';
} catch (caught) {
const err = rootCause(caught);
if (err instanceof TaskGoneError || isTaskGone(err)) {
// The workflow has moved on (timeout). Drop the message, report nothing.
console.warn(`Task for rental ${req.rentalId} is no longer active`);
return 'gone';
}
await client.send(
new SendTaskFailureCommand({
taskToken,
error: errorName(err),
cause: err instanceof Error ? err.message : String(err),
}),
);
return 'failure';
}
}
const sfn = new SFNClient({});
export const handler = async (event: SQSEvent, context: Context): Promise<SQSBatchResponse> => {
const batchItemFailures: SQSBatchResponse['batchItemFailures'] = [];
for (const record of event.Records) {
try {
await processCheck(JSON.parse(record.body) as CheckRequest, {
client: sfn,
diagnose: runBatteryDiagnosis,
heartbeatIntervalMs: Number(process.env.HEARTBEAT_INTERVAL_MS ?? '20000'),
// 10 seconds of headroom so SendTaskFailure still gets through
budgetMs: context.getRemainingTimeInMillis() - 10_000,
});
} catch (err) {
// Only if even SendTaskSuccess/-Failure fails: redeliver the message later
console.error('Reporting back to Step Functions failed', err);
batchItemFailures.push({ itemIdentifier: record.messageId });
}
}
return { batchItemFailures };
};
One detail about the budget: AbortSignal.any combines two reasons for aborting. Either Step Functions reports that nobody is waiting anymore, or the worker’s own time budget runs out. In the second case, a TimeoutError is behind the abort, and the worker reports BatteryCheck.TooSlow. Because aborted waits from node:timers/promises wrap the actual reason in the cause field, rootCause unwraps it first. Without this line, the worker would not recognize an expired task and would try to report it as failed with an invalid token.
Step 6: The CDK stack
Finally, all the time limits come together in the stack. For a while now, the properties in CDK have been called taskTimeout and heartbeatTimeout and expect an sfn.Timeout. In contrast, the older variants timeout and heartbeat are marked as deprecated.
// lib/bike-return-stack.ts
import { Duration, Stack, type StackProps } from 'aws-cdk-lib';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import { SqsEventSource } from 'aws-cdk-lib/aws-lambda-event-sources';
import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs';
import * as sns from 'aws-cdk-lib/aws-sns';
import * as sqs from 'aws-cdk-lib/aws-sqs';
import * as sfn from 'aws-cdk-lib/aws-stepfunctions';
import * as tasks from 'aws-cdk-lib/aws-stepfunctions-tasks';
import type { Construct } from 'constructs';
export class BikeReturnStack extends Stack {
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
// 1) Calculate the fee: short Lambda, task timeout just above the Lambda timeout
const feeFn = new NodejsFunction(this, 'CalculateFeeFn', {
entry: 'src/calculate-fee.ts',
runtime: lambda.Runtime.NODEJS_22_X,
timeout: Duration.seconds(10),
memorySize: 256,
});
const calculateFee = new tasks.LambdaInvoke(this, 'CalculateFee', {
lambdaFunction: feeFn,
payloadResponseOnly: true,
resultPath: '$.fee',
taskTimeout: sfn.Timeout.duration(Duration.seconds(15)),
retryOnServiceExceptions: true,
});
calculateFee.addRetry({
errors: ['Sandbox.Timedout', 'States.Timeout'],
maxAttempts: 1,
interval: Duration.seconds(2),
});
// 2) Check the battery: callback with task token via SQS, worker sends heartbeats
const workerFn = new NodejsFunction(this, 'BatteryCheckWorkerFn', {
entry: 'src/battery-check-worker.ts',
runtime: lambda.Runtime.NODEJS_22_X,
timeout: Duration.minutes(4),
memorySize: 256,
environment: { HEARTBEAT_INTERVAL_MS: '20000' },
});
const dlq = new sqs.Queue(this, 'BatteryCheckDlq', { retentionPeriod: Duration.days(14) });
const checkQueue = new sqs.Queue(this, 'BatteryCheckQueue', {
visibilityTimeout: Duration.minutes(24), // 6 × Lambda timeout
deadLetterQueue: { queue: dlq, maxReceiveCount: 3 },
});
workerFn.addEventSource(new SqsEventSource(checkQueue, { batchSize: 1, reportBatchItemFailures: true }));
const checkBattery = new tasks.SqsSendMessage(this, 'CheckBattery', {
queue: checkQueue,
integrationPattern: sfn.IntegrationPattern.WAIT_FOR_TASK_TOKEN,
messageBody: sfn.TaskInput.fromObject({
taskToken: sfn.JsonPath.taskToken,
rentalId: sfn.JsonPath.stringAt('$.rentalId'),
bikeId: sfn.JsonPath.stringAt('$.bikeId'),
}),
resultPath: '$.battery',
heartbeatTimeout: sfn.Timeout.duration(Duration.seconds(60)),
taskTimeout: sfn.Timeout.duration(Duration.minutes(5)),
});
checkBattery.addRetry({
errors: ['BatteryCheck.BikeOffline'],
maxAttempts: 2,
interval: Duration.seconds(30),
backoffRate: 2,
});
// 3) If the check hangs or fails: notify the workshop, then abort cleanly
const workshopTopic = new sns.Topic(this, 'WorkshopTopic');
const notifyWorkshop = new tasks.SnsPublish(this, 'NotifyWorkshop', {
topic: workshopTopic,
message: sfn.TaskInput.fromObject({
rentalId: sfn.JsonPath.stringAt('$.rentalId'),
bikeId: sfn.JsonPath.stringAt('$.bikeId'),
error: sfn.JsonPath.stringAt('$.error.Error'),
}),
resultPath: sfn.JsonPath.DISCARD,
});
const checkFailed = new sfn.Fail(this, 'CheckFailed', {
errorPath: '$.error.Error',
causePath: '$.error.Cause',
});
checkBattery.addCatch(notifyWorkshop.next(checkFailed), {
errors: [
'States.HeartbeatTimeout',
'States.Timeout',
'BatteryCheck.TooSlow',
'BatteryCheck.BikeOffline',
'BatteryCheck.Unexpected',
],
resultPath: '$.error',
});
const stateMachine = new sfn.StateMachine(this, 'BikeReturnStateMachine', {
definitionBody: sfn.DefinitionBody.fromChainable(
calculateFee.next(checkBattery).next(new sfn.Succeed(this, 'ReturnCompleted')),
),
// Upper limit for the whole execution, including all retries
timeout: Duration.minutes(20),
});
// The worker may call SendTaskSuccess, SendTaskFailure and SendTaskHeartbeat
stateMachine.grantTaskResponse(workerFn);
}
}
A few spots deserve a second look. retryOnServiceExceptions automatically adds the retries AWS recommends for temporary Lambda errors. grantTaskResponse gives the worker exactly the permissions for SendTaskSuccess, SendTaskFailure and SendTaskHeartbeat. Furthermore, the Catch block names both States.Timeout and States.HeartbeatTimeout.
What is still missing is the entry point of the app:
// bin/app.ts
import { App } from 'aws-cdk-lib';
import { BikeReturnStack } from '../lib/bike-return-stack.js';
const app = new App();
new BikeReturnStack(app, 'BikeReturnStack');
Step 7: Test the behavior
Nobody likes testing timeouts with real waiting times. Vitest can fast-forward the clock, so the heartbeat tests run in milliseconds:
// test/heartbeat.test.ts
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { runWithHeartbeat, TaskGoneError } from '../src/heartbeat.js';
function namedError(name: string): Error {
const err = new Error(name);
err.name = name;
return err;
}
describe('runWithHeartbeat', () => {
beforeEach(() => vi.useFakeTimers());
afterEach(() => vi.useRealTimers());
it('sends a heartbeat immediately and then at the interval', async () => {
const send = vi.fn().mockResolvedValue({});
const work = (signal: AbortSignal) =>
new Promise<string>((resolve) => setTimeout(() => resolve(signal.aborted ? 'aborted' : 'done'), 65_000));
const result = runWithHeartbeat(work, { taskToken: 't-1', intervalMs: 20_000, client: { send } });
await vi.advanceTimersByTimeAsync(65_000);
await expect(result).resolves.toBe('done');
expect(send).toHaveBeenCalledTimes(4); // immediately + after 20, 40 and 60 seconds
});
it('does not start at all if the task has already expired', async () => {
const send = vi.fn().mockRejectedValue(namedError('TaskTimedOut'));
const work = vi.fn();
await expect(runWithHeartbeat(work, { taskToken: 't-2', intervalMs: 20_000, client: { send } })).rejects.toBeInstanceOf(
TaskGoneError,
);
expect(work).not.toHaveBeenCalled();
});
it('aborts the work as soon as Step Functions no longer knows the task', async () => {
const send = vi.fn().mockResolvedValueOnce({}).mockRejectedValueOnce(namedError('TaskTimedOut'));
const work = (signal: AbortSignal) =>
new Promise<string>((_, reject) => signal.addEventListener('abort', () => reject(signal.reason)));
const result = runWithHeartbeat(work, { taskToken: 't-3', intervalMs: 20_000, client: { send } });
const assertion = expect(result).rejects.toThrow(/no longer waiting/);
await vi.advanceTimersByTimeAsync(20_000);
await assertion;
});
it('survives individual network errors during heartbeats', async () => {
const send = vi.fn().mockResolvedValueOnce({}).mockRejectedValueOnce(namedError('ECONNRESET')).mockResolvedValue({});
vi.spyOn(console, 'warn').mockImplementation(() => undefined);
const work = () => new Promise<string>((resolve) => setTimeout(() => resolve('done'), 45_000));
const result = runWithHeartbeat(work, { taskToken: 't-4', intervalMs: 20_000, client: { send } });
await vi.advanceTimersByTimeAsync(45_000);
await expect(result).resolves.toBe('done');
});
});
For the worker, on the other hand, a few cases with a fake client are enough. The most important one is the last: if the task has already expired, the diagnosis must not start at all.
// test/worker.test.ts
import { setTimeout as sleep } from 'node:timers/promises';
import { describe, expect, it, vi } from 'vitest';
import { BikeOfflineError } from '../src/battery-diagnosis.js';
import { processCheck, type WorkerDeps } from '../src/battery-check-worker.js';
const request = { taskToken: 't-1', rentalId: 'R-42', bikeId: 'ebike-7' };
function deps(overrides: Partial<WorkerDeps>): WorkerDeps {
return {
client: { send: vi.fn().mockResolvedValue({}) },
diagnose: vi.fn().mockResolvedValue({ bikeId: 'ebike-7', healthPercent: 88, chargeCycles: 300, verdict: 'ok' }),
heartbeatIntervalMs: 20_000,
budgetMs: 60_000,
...overrides,
};
}
function sentCommands(d: WorkerDeps): string[] {
return (d.client.send as ReturnType<typeof vi.fn>).mock.calls.map(([cmd]) => cmd.constructor.name);
}
describe('processCheck', () => {
it('reports the result with SendTaskSuccess', async () => {
const d = deps({});
await expect(processCheck(request, d)).resolves.toBe('success');
expect(sentCommands(d)).toEqual(['SendTaskHeartbeatCommand', 'SendTaskSuccessCommand']);
});
it('reports an unreachable bike as BatteryCheck.BikeOffline', async () => {
const d = deps({ diagnose: vi.fn().mockRejectedValue(new BikeOfflineError('ebike-7')) });
await expect(processCheck(request, d)).resolves.toBe('failure');
const last = (d.client.send as ReturnType<typeof vi.fn>).mock.calls.at(-1)?.[0];
expect(last.input.error).toBe('BatteryCheck.BikeOffline');
});
it('reports an exceeded time budget as BatteryCheck.TooSlow', async () => {
const d = deps({
budgetMs: 5,
// sleep() from timers/promises throws an AbortError with the reason in cause when aborted
diagnose: async (bikeId, signal) => {
await sleep(60_000, undefined, { signal });
return { bikeId, healthPercent: 90, chargeCycles: 10, verdict: 'ok' };
},
});
await expect(processCheck(request, d)).resolves.toBe('failure');
const last = (d.client.send as ReturnType<typeof vi.fn>).mock.calls.at(-1)?.[0];
expect(last.input.error).toBe('BatteryCheck.TooSlow');
});
it('reports nothing if the task has already expired', async () => {
const gone = Object.assign(new Error('expired'), { name: 'TaskTimedOut' });
const d = deps({ client: { send: vi.fn().mockRejectedValue(gone) } });
vi.spyOn(console, 'warn').mockImplementation(() => undefined);
await expect(processCheck(request, d)).resolves.toBe('gone');
expect(d.diagnose).not.toHaveBeenCalled();
});
});
Finally, the third test checks the generated state machine definition. That way you notice immediately if someone removes a timeout while tidying up:
// test/stack.test.ts
import { App } from 'aws-cdk-lib';
import { Template } from 'aws-cdk-lib/assertions';
import { describe, expect, it } from 'vitest';
import { BikeReturnStack } from '../lib/bike-return-stack.js';
function definition(): Record<string, any> {
const template = Template.fromStack(new BikeReturnStack(new App(), 'TestStack'));
const [machine] = Object.values(template.findResources('AWS::StepFunctions::StateMachine'));
const parts = machine.Properties.DefinitionString['Fn::Join'][1] as unknown[];
// Replace ARN placeholders with strings so the definition can be parsed
return JSON.parse(parts.map((p) => (typeof p === 'string' ? p : 'ref')).join(''));
}
describe('BikeReturnStack', () => {
const def = definition();
it('limits the whole execution', () => {
expect(def.TimeoutSeconds).toBe(1200);
});
it('sets timeout and heartbeat for the callback task', () => {
expect(def.States.CheckBattery.TimeoutSeconds).toBe(300);
expect(def.States.CheckBattery.HeartbeatSeconds).toBe(60);
});
it('waits slightly longer for the Lambda task than the function itself', () => {
expect(def.States.CalculateFee.TimeoutSeconds).toBe(15);
});
it('catches timeouts and routes them to the workshop', () => {
const catcher = def.States.CheckBattery.Catch[0];
expect(catcher.ErrorEquals).toContain('States.Timeout');
expect(catcher.ErrorEquals).toContain('States.HeartbeatTimeout');
expect(catcher.Next).toBe('NotifyWorkshop');
});
});
npm run build
npm test
Expected result: three test files and twelve green tests. During the stack test, esbuild bundles the two Lambda functions on the side, and the related output is normal.
Step 8: Deploy and try it out
npx cdk deploy
# Get the state machine ARN from the console or via the CLI
aws stepfunctions list-state-machines --query "stateMachines[?contains(name, 'BikeReturn')].stateMachineArn" --output text
aws stepfunctions start-execution \
--state-machine-arn <ARN> \
--input '{"rentalId":"R-1001","bikeId":"ebike-7","minutes":42}'
After about 45 seconds, the execution shows “Succeeded”, and you will find the worker’s report under battery in the output. Three variants are worth trying:
- With
"bikeId":"offline-3", the execution history shows two retries with pauses of 30 and 60 seconds, followed by the path viaNotifyWorkshoptoCheckFailed. - If you set the worker Lambda’s environment variable
HEARTBEAT_INTERVAL_MSto90000, the second heartbeat arrives too late. After 60 seconds, the task ends with a heartbeat timeout, and the workshop gets a message. - If you set
DIAGNOSIS_STEP_MSto100000, the budget in the worker kicks in. It reportsBatteryCheck.TooSlowbefore its Lambda timeout strikes.
When you are done, clean up with npx cdk destroy.
Common mistakes with timeouts in Step Functions
Callback without a timeout
The classic. A .waitForTaskToken task without TimeoutSeconds and without HeartbeatSeconds waits until the maximum execution duration. Check your existing state machines specifically for this combination. The stack test from step 7 prevents it from creeping back in.
Heartbeat interval equal to the heartbeat window
If the worker sends exactly every 60 seconds and the window is also 60 seconds, a small delay is enough for a timeout. Instead, an interval of a third of the window has proven itself. You don’t need to send much more often: SendTaskHeartbeat has its own throttling limit per account and Region.
Task timeout shorter than the Lambda timeout
Then Step Functions gives up while the function is still working. As a result, the same work runs twice if a retry follows. Therefore, always keep the task timeout slightly above the Lambda timeout.
Retries that blow the overall budget
TimeoutSeconds applies per attempt. For example, three attempts of ten minutes each do not fit into an execution with a 20-minute limit. Work through the budget once as shown above and write the calculation as a comment next to the code.
Old token after a timeout
When a callback task expires and is retried, Step Functions creates a new token. A worker still busy with the old job receives the error TaskTimedOut on its next heartbeat or on the final SendTaskSuccess. So treat it as “nobody is waiting anymore” and not as an error that needs retrying.
Only States.TaskFailed caught
If your Catch only names States.TaskFailed, it catches no timeout. The execution then fails without a cleanup step. Name timeouts explicitly or use States.ALL as the last catcher.
Cost and security
The cost of this pattern mainly comes from the worker Lambda’s run time. Standard workflows are billed by state transitions, and retries count as transitions too. A few retries hardly matter, but a retry without an upper limit does. So always set maxAttempts and, for long waits, also maxDelay.
When it comes to security, it is all about the task token. Whoever has the token and the matching IAM permission can complete the task and slip the workflow any result they like. So don’t write the token to the log, don’t pass it on to clients outside your account, and only grant grantTaskResponse to the functions that are really supposed to respond. According to the documentation, tokens only work for callers from the same AWS account anyway.
My take
I consider timeouts in Step Functions a mandatory setting, just like types on a public function. That the Amazon States Language leaves them out by default has technical reasons, but in everyday work it is a trap. A workflow without a time limit basically says: “I rely on nothing ever going wrong.” In distributed systems, that never holds true for long.
At the same time, I would not add heartbeats everywhere. For a callback that waits for a human, such as an approval like in the article on Human in the Loop with Step Functions, a heartbeat makes little sense. Instead, a generous timeout with a reminder is enough there. Heartbeats pay off, however, where a machine is working that can crash, and where you want to notice the crash quickly. And one more point where I don’t follow the documentation blindly: I only configure retries on timeouts if the step is idempotent. Otherwise, the timeout builds exactly the duplicate processing I wanted to prevent.
FAQ
What happens if I don’t set a timeout in Step Functions?
Simple request-response calls have a default timeout, so they cannot hang forever. Callbacks with a task token, .sync jobs and activities, however, wait without one until the maximum execution duration, which for Standard workflows is up to one year.
What a polling worker for activities looks like, and when it beats a callback, is covered in Step Functions activity vs. callback.
How long can a Step Functions execution run at most?
Standard workflows can run for up to one year, Express workflows for up to five minutes. Also, both limits are fixed and cannot be raised. With TimeoutSeconds at the top level, you set your own, shorter limit.
What is the difference between TimeoutSeconds and HeartbeatSeconds?
TimeoutSeconds limits the total duration of one task attempt. HeartbeatSeconds limits the gap between two signs of life from the worker and must be lower than the timeout. Heartbeats do not extend the timeout.
Does Step Functions stop my Lambda function on a timeout?
No. Step Functions only stops waiting. The function keeps running until it finishes or its own Lambda timeout kicks in. That is why the task timeout should sit slightly above the Lambda timeout.
Your next step
Open your most important state machine and look for tasks with .waitForTaskToken, .sync or activities. Does each of them have a timeout? If not, add one today and work through the overall budget including retries once. If you are still wondering whether Step Functions is the right tool for your process at all, the AWS Service Finder helps you decide.
And now I am curious: have you ever had an execution that silently waited for days? How did you find out?
Continue the series: Previous part: Lambda timeout budget: from API Gateway to SDK · Next part: Step Functions Distributed Map: Process CSV with Lambda · All parts of the series “Serverless patterns in practice”
All code from this article, ready to run: smirowstanitzok/sascha-ms-examples
Sources
- AWS Step Functions Developer Guide: Task workflow state (TimeoutSeconds, HeartbeatSeconds)
- AWS Step Functions Developer Guide: Handling errors in Step Functions workflows
- AWS Step Functions Developer Guide: Best practices
- AWS Step Functions Developer Guide: Discover service integration patterns
- AWS Step Functions API Reference: SendTaskHeartbeat
- AWS Step Functions Developer Guide: Service quotas
- AWS CDK API Reference: aws-cdk-lib.aws_stepfunctions
This post was created with AI assistance.
👉 Next step: Working with AWS CDK? Grab my printable AWS CDK cheat sheet with commands, concepts and a stack skeleton.
📬 Stay updated: New articles on serverless, AI and leading tech teams via RSS, browser push or the weekly newsletter (in German).
Originally published on sascha-ms.de. More articles on serverless, AI in everyday development and leading tech teams: sascha-ms.de/en

Top comments (0)