What it actually is
AWS Step Functions runs state machines that you describe in JSON (the Amazon States Language, ASL). Each state either does work (a Task that calls an AWS API, a Lambda function, an HTTP endpoint, or a nested workflow), makes a decision (Choice), waits (Wait), fans out (Parallel, Map), or ends the run (Succeed, Fail). AWS stores the position of every running execution, retries what you told it to retry, and routes errors to the states you named in Catch. Your code never has to remember where it was.
That last sentence is the whole product. A workflow that lives inside one long Lambda function forgets everything when the function times out or the container dies. A workflow that lives in Step Functions does not, because the engine checkpoints every transition. People describe Step Functions as "orchestration" or "low-code", and both labels hide the real value: it is a durable execution engine with a visual editor attached.
It is also bigger than it was a year ago. Since September 15, 2026 Step Functions adds SDK integrations for new AWS services automatically, within weeks of their release, and AWS stopped announcing them one by one. In June 2026 it gained an agentic reasoning step backed by the Amazon Bedrock AgentCore managed harness (in preview, four Regions). On October 29, 2026 workflows became callable as tools by AI agents through AgentCore Gateway over MCP. None of that changes the core model below, which is what this article is about.
The model
Two engines, one language. When you create a state machine you pick a type, and you cannot change it later. The documentation is blunt: "The workflow type can not be updated after you create a state machine."
Standard workflows run for up to one year, give exactly-once execution of the workflow, keep a queryable execution history for 90 days after the execution closes, and support every integration pattern, including .sync (start a job and wait for it) and .waitForTaskToken (pause until something calls back). Starting an execution with the name of a currently running one returns an idempotent response instead of starting a second copy.
Express workflows run for up to five minutes and have no state transition rate limit. Asynchronous Express gives at-least-once execution: the same run can happen twice. Synchronous Express (StartSyncExecution, or called from API Gateway) gives at-most-once. Neither manages idempotency for you, neither supports .sync or .waitForTaskToken, neither supports Distributed Map or activities, and the only history you get is whatever you send to CloudWatch Logs.
Two query languages. States read and shape data with either JSONPath (the original, still the default when QueryLanguage is omitted) or JSONata. They are not interchangeable field by field: JSONPath states use InputPath, Parameters, ResultSelector, ResultPath, and OutputPath; JSONata states use Arguments, Output, and Assign, with expressions wrapped in {% %}. You can set the language at the top level and override it per state, so migration can be incremental. New work should start in JSONata.
Variables. Assign stores values that later states read as $name, without threading them through every state's input and output. A single variable can hold 256 KiB, one Assign block can write 256 KiB total, and an execution can hold 10 MiB of variables. States inside Parallel and Map get their own scope: they can read outer variables but cannot reassign them (a Catch Assign is the exception), and Distributed Map cannot read outer variables at all.
Who operates what. AWS runs the engine, the checkpointing, the retry timers, and the history store. You own the definition, the IAM role the state machine assumes, the idempotency of every task it calls, and the meaning of every error it catches. That last one is where most production incidents live, and it is what the build below is about.
When to use it, when not to
You need | Use | Not |
|---|---|---|
A multi-step business process with retries, compensation, human approval, or waits measured in hours or days | Step Functions Standard | A Lambda function with a |
High-volume, short, idempotent processing (event transformation, IoT ingestion, an API backend that chains three calls) | Step Functions Express | Standard, which bills every transition and throttles transitions |
Routing one event to many independent consumers | EventBridge or SNS | Step Functions, which orchestrates; it does not broadcast |
A work queue with backpressure | SQS | A Map state polling nothing |
Durable workflows written as ordinary code in your own service | Lambda durable functions or another code-first engine | Contorting ASL to express deep business logic |
Processing millions of S3 objects or CSV rows in parallel | Distributed Map (Standard) | Inline Map, which keeps every iteration in one execution history |
The choreography vs orchestration question also matters. If no single team owns the business process, events on a bus (see the EventBridge entry, SL#165) keep services decoupled. If one team owns the outcome and needs to answer "where is order 4471 right now and what did we already undo", a state machine answers it in one console view. The Saga pattern essay, SL#110 covers that trade-off in depth; this article is the AWS implementation.
What it costs
Standard workflows bill per state transition: $0.000025 each in US East (N. Virginia), which is $25 per million. The free tier is 4,000 transitions per month and, unlike most free tiers, it does not expire after 12 months. Every retry counts as an additional transition, and so does every state of a redriven execution.
Express workflows bill per request and per duration: $1.00 per million requests plus $0.00001667 per GB-second for the first tier of usage, with cheaper tiers above it. Memory is estimated (50 MB plus the definition size plus the execution data, scaled by Parallel and Map usage) and rounded up to 64 MB chunks; duration is rounded up to the nearest 100 ms. Calls to other services (Lambda, DynamoDB, Bedrock) are billed by those services.
The number that surprises people is the ratio. Take one million orders a month through a six-state workflow. On Standard that is 6 million transitions, minus the 4,000 free, times $0.000025: about $149.90. On Express, assuming 64 MB and 200 ms per run, it is $1.00 in requests plus 12,500 GB-seconds at $0.00001667, about $0.21, so roughly $1.21. Express is two orders of magnitude cheaper for this shape of work.
So why does the build below use Standard? Because the price buys exactly-once semantics, 90 days of queryable history, idempotent starts, and redrive. For a saga that moves money, those are the product. For a stateless transform that is safe to run twice, Express is the right answer and Standard is a tax. Two more line items to watch: Express history lives in CloudWatch Logs, and logging at level ALL with full execution data can cost more than the workflow itself; and Standard loops that poll ("check status, wait 10 seconds, check again") multiply transitions quietly. Use .sync integrations or callbacks instead of polling loops whenever the target supports them.
The limits that bite
256 KiB of payload. Input and output of every state, task, and execution is capped at 256 KiB, a hard quota. Exceeding it raises States.DataLimitExceeded, which States.ALL does not catch; you have to name it. Pass S3 keys or DynamoDB keys between states, never documents.
25,000 history events per Standard execution. A loop that runs a few thousand iterations inside one execution hits this and fails. The fix is structural: move the loop into a child workflow or a Distributed Map, which runs each iteration as its own child execution.
Transition throttling. In US East (N. Virginia), US West (Oregon), and Europe (Ireland), Standard state transitions use a token bucket of 5,000 with a refill of 5,000 per second; other Regions get 800 and 800. StartExecution for Standard is 1,300 burst and 300 per second in those three Regions, 800 and 150 elsewhere. New accounts start with reduced transition quotas that AWS raises automatically with usage, which is exactly what bites a launch-day load test. Express has no transition limit and a start bucket of 6,000 per second.
One million open executions per account per Region for Standard, then ExecutionLimitExceeded. Workflows that wait days for a human add up faster than you think.
Distributed Map runs at most 10,000 parallel child executions per Map Run (hard quota), dispatched at up to 1,000 per second for Express children and 100 per second for Standard children.
Execution names are unique per state machine for the 90-day history window. That is a feature (use your business ID as the name and you get deduplication for free), but it means a test script that reuses test-1 fails with ExecutionAlreadyExists until the old history ages out.
Redrive restarts a failed, aborted, or timed-out Standard execution from the failing state, keeping the results of states that already succeeded. It works for 14 days after the execution closes, only for Standard, and only if the history has fewer than 24,999 events.
Build it: a saga with no Lambda functions
We will build an order saga with three forward steps and three compensations, all as direct DynamoDB service integrations. Reserve stock, charge a wallet, book a shipment. If any step fails, undo what was done, in reverse order, and end in a Fail state that says why.
The non-obvious design choice is in the error handlers. In a distributed system, a step that "failed" might have succeeded: the write landed and the response got lost, or a retry fired after a timeout. So every Catch sends the workflow to the compensation of the step that failed, not the step before it. Each compensation is idempotent and conditional: it undoes the change only if a per-order marker proves the change happened, and treats "nothing to undo" as success. The workflow never has to know whether the failed step ran. It just has to make every undo safe to attempt.
Prerequisites. An AWS account, Python 3.10+, boto3 (pip install boto3), and credentials that can create a DynamoDB table, an IAM role with an inline policy, and a state machine. The caller needs dynamodb:CreateTable, PutItem, Scan, DeleteTable, DescribeTable; iam:CreateRole, PutRolePolicy, PassRole, DeleteRolePolicy, DeleteRole; and states:ValidateStateMachineDefinition, CreateStateMachine, StartExecution, DescribeExecution, GetExecutionHistory, RedriveExecution, DeleteStateMachine. Everything runs in us-east-1; change REGION if you prefer another.
Cost of following along. Four executions use about 25 state transitions, inside the 4,000 free per month. DynamoDB on-demand for a few dozen writes is a fraction of a cent. Expect $0.00 if you run the cleanup.
Step 1: The table, the seed data, and a least-privilege role
One table holds three items: a product with stock, a customer wallet with a balance, and a shipping zone. The state machine's role gets exactly one action on exactly one table.
import json, sys, time, boto3
REGION = "us-east-1"
TABLE, ROLE, SM = "sfn-saga-demo", "sfn-saga-demo-role", "sfn-saga-demo"
ddb = boto3.client("dynamodb", region_name=REGION)
iam = boto3.client("iam")
sfn = boto3.client("stepfunctions", region_name=REGION)
acct = boto3.client("sts").get_caller_identity()["Account"]
SM_ARN = f"arn:aws:states:{REGION}:{acct}:stateMachine:{SM}"
def setup():
ddb.create_table(TableName=TABLE, BillingMode="PAY_PER_REQUEST",
KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}])
ddb.get_waiter("table_exists").wait(TableName=TABLE)
for item in ({"pk": {"S": "SKU#KB-01"}, "stock": {"N": "5"}},
{"pk": {"S": "WALLET#alice"}, "balance": {"N": "100"}},
{"pk": {"S": "ZONE#eu-west"}}):
ddb.put_item(TableName=TABLE, Item=item)
trust = {"Version": "2012-10-17", "Statement": [{"Effect": "Allow",
"Principal": {"Service": "states.amazonaws.com"}, "Action": "sts:AssumeRole",
"Condition": {"StringEquals": {"aws:SourceAccount": acct}}}]}
role_arn = iam.create_role(RoleName=ROLE,
AssumeRolePolicyDocument=json.dumps(trust))["Role"]["Arn"]
iam.put_role_policy(RoleName=ROLE, PolicyName="saga-ddb", PolicyDocument=json.dumps({
"Version": "2012-10-17", "Statement": [{"Effect": "Allow",
"Action": "dynamodb:UpdateItem",
"Resource": f"arn:aws:dynamodb:{REGION}:{acct}:table/{TABLE}"}]}))
definition = open("saga.asl.json").read()
check = sfn.validate_state_machine_definition(definition=definition, type="STANDARD")
print("validation:", check["result"], check["diagnostics"])
time.sleep(10) # IAM is eventually consistent; a fresh role is not usable instantly
sfn.create_state_machine(name=SM, definition=definition,
roleArn=role_arn, type="STANDARD")
print("created", SM_ARN)
if __name__ == "__main__":
{"setup": setup}[sys.argv[1]]()
Save it as saga.py. The trust policy adds an aws:SourceAccount condition so only Step Functions in your account can assume the role. The time.sleep(10) is not decoration: IAM is eventually consistent, and creating a state machine with a role that was created a second ago intermittently fails with an access error. validate_state_machine_definition runs the same static checks as the console before anything is created, which turns a bad JSONata expression into a readable diagnostic instead of a failed deploy.
Step 2: The state machine
Save this as saga.asl.json next to saga.py, then run python saga.py setup. You should see validation: OK [] and the state machine ARN.
{
"Comment": "Order saga: reserve stock, charge wallet, book shipment. Compensate in reverse.",
"QueryLanguage": "JSONata",
"StartAt": "Init",
"States": {
"Init": {
"Type": "Pass",
"Assign": {
"orderId": "{% $states.input.orderId %}",
"sku": "{% $states.input.sku %}",
"qty": "{% $string($states.input.qty) %}",
"customer": "{% $states.input.customer %}",
"amount": "{% $string($states.input.amount) %}",
"zone": "{% $states.input.zone %}",
"failedAt": "none",
"cause": "none"
},
"Next": "ReserveStock"
},
"ReserveStock": {
"Type": "Task",
"Resource": "arn:aws:states:::dynamodb:updateItem",
"Arguments": {
"TableName": "sfn-saga-demo",
"Key": {"pk": {"S": "{% 'SKU#' & $sku %}"}},
"UpdateExpression": "SET stock = stock - :q, #o = :q",
"ConditionExpression": "stock >= :q AND attribute_not_exists(#o)",
"ExpressionAttributeNames": {"#o": "{% 'res_' & $orderId %}"},
"ExpressionAttributeValues": {":q": {"N": "{% $qty %}"}}
},
"Retry": [
{"ErrorEquals": ["DynamoDB.ConditionalCheckFailedException"], "MaxAttempts": 0},
{
"ErrorEquals": ["States.ALL"],
"IntervalSeconds": 1,
"MaxAttempts": 3,
"BackoffRate": 2,
"JitterStrategy": "FULL"
}
],
"Catch": [
{
"ErrorEquals": ["States.ALL"],
"Next": "ReleaseStock",
"Assign": {"failedAt": "ReserveStock", "cause": "{% $states.errorOutput.Error %}"}
}
],
"Next": "ChargeWallet"
},
"ChargeWallet": {
"Type": "Task",
"Resource": "arn:aws:states:::dynamodb:updateItem",
"Arguments": {
"TableName": "sfn-saga-demo",
"Key": {"pk": {"S": "{% 'WALLET#' & $customer %}"}},
"UpdateExpression": "SET balance = balance - :a, #o = :a",
"ConditionExpression": "balance >= :a AND attribute_not_exists(#o)",
"ExpressionAttributeNames": {"#o": "{% 'chg_' & $orderId %}"},
"ExpressionAttributeValues": {":a": {"N": "{% $amount %}"}}
},
"Retry": [
{"ErrorEquals": ["DynamoDB.ConditionalCheckFailedException"], "MaxAttempts": 0},
{
"ErrorEquals": ["States.ALL"],
"IntervalSeconds": 1,
"MaxAttempts": 3,
"BackoffRate": 2,
"JitterStrategy": "FULL"
}
],
"Catch": [
{
"ErrorEquals": ["States.ALL"],
"Next": "RefundWallet",
"Assign": {"failedAt": "ChargeWallet", "cause": "{% $states.errorOutput.Error %}"}
}
],
"Next": "BookShipment"
},
"BookShipment": {
"Type": "Task",
"Resource": "arn:aws:states:::dynamodb:updateItem",
"Arguments": {
"TableName": "sfn-saga-demo",
"Key": {"pk": {"S": "{% 'ZONE#' & $zone %}"}},
"UpdateExpression": "SET #o = :q",
"ConditionExpression": "attribute_exists(pk) AND attribute_not_exists(#o)",
"ExpressionAttributeNames": {"#o": "{% 'shp_' & $orderId %}"},
"ExpressionAttributeValues": {":q": {"N": "{% $qty %}"}}
},
"Retry": [
{"ErrorEquals": ["DynamoDB.ConditionalCheckFailedException"], "MaxAttempts": 0},
{
"ErrorEquals": ["States.ALL"],
"IntervalSeconds": 1,
"MaxAttempts": 3,
"BackoffRate": 2,
"JitterStrategy": "FULL"
}
],
"Catch": [
{
"ErrorEquals": ["States.ALL"],
"Next": "CancelShipment",
"Assign": {"failedAt": "BookShipment", "cause": "{% $states.errorOutput.Error %}"}
}
],
"Next": "OrderConfirmed"
},
"OrderConfirmed": {"Type": "Succeed", "Output": "{% {'orderId': $orderId, 'status': 'CONFIRMED'} %}"},
"CancelShipment": {
"Type": "Task",
"Resource": "arn:aws:states:::dynamodb:updateItem",
"Arguments": {
"TableName": "sfn-saga-demo",
"Key": {"pk": {"S": "{% 'ZONE#' & $zone %}"}},
"UpdateExpression": "REMOVE #o",
"ConditionExpression": "attribute_exists(#o)",
"ExpressionAttributeNames": {"#o": "{% 'shp_' & $orderId %}"}
},
"Retry": [
{"ErrorEquals": ["DynamoDB.ConditionalCheckFailedException"], "MaxAttempts": 0},
{
"ErrorEquals": ["States.ALL"],
"IntervalSeconds": 2,
"MaxAttempts": 6,
"BackoffRate": 2,
"JitterStrategy": "FULL"
}
],
"Catch": [{"ErrorEquals": ["DynamoDB.ConditionalCheckFailedException"], "Next": "RefundWallet"}],
"Next": "RefundWallet"
},
"RefundWallet": {
"Type": "Task",
"Resource": "arn:aws:states:::dynamodb:updateItem",
"Arguments": {
"TableName": "sfn-saga-demo",
"Key": {"pk": {"S": "{% 'WALLET#' & $customer %}"}},
"UpdateExpression": "SET balance = balance + :a REMOVE #o",
"ConditionExpression": "attribute_exists(#o)",
"ExpressionAttributeNames": {"#o": "{% 'chg_' & $orderId %}"},
"ExpressionAttributeValues": {":a": {"N": "{% $amount %}"}}
},
"Retry": [
{"ErrorEquals": ["DynamoDB.ConditionalCheckFailedException"], "MaxAttempts": 0},
{
"ErrorEquals": ["States.ALL"],
"IntervalSeconds": 2,
"MaxAttempts": 6,
"BackoffRate": 2,
"JitterStrategy": "FULL"
}
],
"Catch": [{"ErrorEquals": ["DynamoDB.ConditionalCheckFailedException"], "Next": "ReleaseStock"}],
"Next": "ReleaseStock"
},
"ReleaseStock": {
"Type": "Task",
"Resource": "arn:aws:states:::dynamodb:updateItem",
"Arguments": {
"TableName": "sfn-saga-demo",
"Key": {"pk": {"S": "{% 'SKU#' & $sku %}"}},
"UpdateExpression": "SET stock = stock + :q REMOVE #o",
"ConditionExpression": "attribute_exists(#o)",
"ExpressionAttributeNames": {"#o": "{% 'res_' & $orderId %}"},
"ExpressionAttributeValues": {":q": {"N": "{% $qty %}"}}
},
"Retry": [
{"ErrorEquals": ["DynamoDB.ConditionalCheckFailedException"], "MaxAttempts": 0},
{
"ErrorEquals": ["States.ALL"],
"IntervalSeconds": 2,
"MaxAttempts": 6,
"BackoffRate": 2,
"JitterStrategy": "FULL"
}
],
"Catch": [{"ErrorEquals": ["DynamoDB.ConditionalCheckFailedException"], "Next": "OrderFailed"}],
"Next": "OrderFailed"
},
"OrderFailed": {"Type": "Fail", "Error": "OrderCompensated", "Cause": "{% 'failed at ' & $failedAt & ': ' & $cause %}"}
}
}
Read it top to bottom once, because every line earns its place.
Init copies the input into variables. After that, no state depends on its input shape, so you can reorder or insert states without rewiring JSONPath. Numbers become strings with $string() because DynamoDB's N type is a string on the wire.
Each forward step is a single conditional UpdateItem that changes the counter and writes a per-order marker attribute (res_ord-001, chg_ord-001, shp_ord-001) in the same atomic write. The condition attribute_not_exists(#o) makes the step idempotent: a retry after a lost response cannot reserve or charge twice. BookShipment adds attribute_exists(pk), because UpdateItem is an upsert and would otherwise happily create a shipping zone called "mars".
The Retry blocks follow the pattern in the aws-samples DynamoDB semaphore workflow: DynamoDB.ConditionalCheckFailedException is a business answer, not a transient fault, so it gets MaxAttempts: 0, and only other errors are retried with exponential backoff and full jitter. Order matters: the first retrier whose ErrorEquals matches wins, and States.ALL must come last.
Every forward Catch records failedAt and the error name in variables, then jumps to the compensation of the same step. Each compensation removes its marker and restores the counter under attribute_exists(#o). If the marker is absent, the forward step never applied, the condition fails, and the compensation's own Catch moves on to the next undo. Compensations retry transient errors six times with backoff, because a compensation that gives up is worse than a slow one.
Step 3: Run four orders
import json, time, boto3
sfn = boto3.client("stepfunctions", region_name="us-east-1")
ddb = boto3.client("dynamodb", region_name="us-east-1")
acct = boto3.client("sts").get_caller_identity()["Account"]
SM_ARN = f"arn:aws:states:us-east-1:{acct}:stateMachine:sfn-saga-demo"
ORDERS = [
{"orderId": "ord-001", "sku": "KB-01", "qty": 2, "customer": "alice", "amount": 30, "zone": "eu-west"},
{"orderId": "ord-002", "sku": "KB-01", "qty": 1, "customer": "alice", "amount": 500, "zone": "eu-west"},
{"orderId": "ord-003", "sku": "KB-01", "qty": 1, "customer": "alice", "amount": 20, "zone": "mars"},
{"orderId": "ord-004", "sku": "KB-01", "qty": 9, "customer": "alice", "amount": 20, "zone": "eu-west"},
]
def run(order):
arn = sfn.start_execution(stateMachineArn=SM_ARN, name=order["orderId"],
input=json.dumps(order))["executionArn"]
while (d := sfn.describe_execution(executionArn=arn))["status"] == "RUNNING":
time.sleep(1)
events = sfn.get_execution_history(executionArn=arn, maxResults=100)["events"]
path = [e["stateEnteredEventDetails"]["name"] for e in events
if e["type"].endswith("StateEntered")]
print(order["orderId"], d["status"], d.get("cause") or d.get("output"))
print(" ", " > ".join(path))
for o in ORDERS:
run(o)
for item in ddb.scan(TableName="sfn-saga-demo")["Items"]:
print({k: list(v.values())[0] for k, v in item.items()})
Save as run_orders.py and run it. The four orders exercise every path: a success, insufficient funds, an unknown shipping zone, and more stock than exists.
Verify it works
This is the expected output (execution ARNs and timing omitted):
ord-001 SUCCEEDED {"orderId":"ord-001","status":"CONFIRMED"}
Init > ReserveStock > ChargeWallet > BookShipment > OrderConfirmed
ord-002 FAILED failed at ChargeWallet: DynamoDB.ConditionalCheckFailedException
Init > ReserveStock > ChargeWallet > RefundWallet > ReleaseStock > OrderFailed
ord-003 FAILED failed at BookShipment: DynamoDB.ConditionalCheckFailedException
Init > ReserveStock > ChargeWallet > BookShipment > CancelShipment > RefundWallet > ReleaseStock > OrderFailed
ord-004 FAILED failed at ReserveStock: DynamoDB.ConditionalCheckFailedException
Init > ReserveStock > ReleaseStock > OrderFailed
{'pk': 'SKU#KB-01', 'stock': '3', 'res_ord-001': '2'}
{'pk': 'WALLET#alice', 'balance': '70', 'chg_ord-001': '30'}
{'pk': 'ZONE#eu-west', 'shp_ord-001': '2'}
The contract: stock went from 5 to 3, the balance from 100 to 70, and only ord-001 left markers. Three failed orders touched the table, and every change they made was undone. There is no ZONE#mars item. (The scan order of the three items may differ.)
Two more checks prove the properties that justify Standard. First, idempotency by name: start ord-001 again.
import boto3, json
sfn = boto3.client("stepfunctions", region_name="us-east-1")
arn = sfn.list_state_machines()["stateMachines"]
arn = next(m["stateMachineArn"] for m in arn if m["name"] == "sfn-saga-demo")
try:
sfn.start_execution(stateMachineArn=arn, name="ord-001", input=json.dumps({"orderId": "ord-001"}))
except sfn.exceptions.ExecutionAlreadyExists as e:
print("deduplicated:", e.response["Error"]["Code"])
You get deduplicated: ExecutionAlreadyExists, and nobody is charged twice. Your order ID is the idempotency key for 90 days, with no table of your own to maintain.
Second, open the Step Functions console, pick ord-003, and look at the graph view. The failing state is red, the compensation path is green, and the Cause reads "failed at BookShipment". This view is what you are paying $25 per million transitions for: at 3 a.m., someone who has never read the code can see what happened to one order.
When it breaks
AccessDeniedException on CreateStateMachine, or the role "cannot be assumed". The role was created too recently. Wait ten seconds and retry; that is what the sleep is for.
Validation error mentioning {% or a JSONPath field. JSONata expressions must start with {% and end with %} with no spaces outside them, and fields like Parameters or ResultPath are invalid in a JSONata state. If you copied an older JSONPath example into this definition, translate Parameters to Arguments and remove the .$ key suffixes.
States.Runtime failure on a state. Usually an expression references something that does not exist, such as $states.input.qty when the input has no qty. States.ALL does not catch States.Runtime, so the execution fails outright. Validate input before the saga, or give Init defaults.
A compensation fails after all its retries. The execution ends FAILED in RefundWallet, with a real error (throttling, a deleted table, a permissions change). Nothing is lost: fix the cause, then call aws stepfunctions redrive-execution --execution-arn <arn>. Redrive resumes at the failed compensation, keeps everything that already succeeded, and because each compensation is conditional, re-running it cannot double-refund. You have 14 days.
Everything is a ConditionalCheckFailedException. That is the design. The error name tells you a precondition failed, not which one. When you need to tell "insufficient funds" from "already charged", read the item first (dynamodb:getItem) and branch in a Choice state, or return the reason from a small Lambda function that owns the business rule.
The item grows forever. Per-order marker attributes on one item are fine for a demo, but an item caps at 400 KB and every order adds an attribute. In production, write the marker as its own item and use the aws-sdk:dynamodb:transactWriteItems integration to change the counter and the marker atomically across two items.
Cleanup
import boto3
sfn = boto3.client("stepfunctions", region_name="us-east-1")
iam, ddb = boto3.client("iam"), boto3.client("dynamodb", region_name="us-east-1")
arn = next(m["stateMachineArn"] for m in sfn.list_state_machines()["stateMachines"]
if m["name"] == "sfn-saga-demo")
sfn.delete_state_machine(stateMachineArn=arn)
iam.delete_role_policy(RoleName="sfn-saga-demo-role", PolicyName="saga-ddb")
iam.delete_role(RoleName="sfn-saga-demo-role")
ddb.delete_table(TableName="sfn-saga-demo")
print("deleted")
Deleting a state machine is asynchronous: it moves to DELETING and its executions and history go with it. Confirm with aws stepfunctions list-state-machines and aws dynamodb list-tables that nothing named sfn-saga-demo remains. Neither service has an idle charge, so once those are gone, the bill for this tutorial stops at whatever fraction of a cent the DynamoDB writes cost.
Where to take it next
Swap BookShipment for a .waitForTaskToken task that sends the token to SQS and waits for a warehouse system to call SendTaskSuccess; that is the human-in-the-loop version, and it only works on Standard. Then put a synchronous Express workflow in front of it that validates the order in under 100 ms from API Gateway and starts the Standard saga only for valid input, which is the usual production split: Express for the cheap, fast, safe-to-repeat part, Standard for the part that moves money. The question to ask of every workflow you build is not "which engine is cheaper" but "what happens if this runs twice, or half of it runs once". Step Functions makes that question answerable. It does not answer it for you.

