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.

Timeline: 20-minute execution, three 5-minute attempts with pauses, 4-minute worker, heartbeats every 20 seconds

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 })<...
Source:https://dev.to/sascha-ms/step-functions-timeout-getting-heartbeats-right-n86