Sub topic 5
Moving data between states
This chapter explains how JSON moves through a state machine. It assumes you can read Amazon States Language (ASL) and have built a basic Task state, as in the earlier chapters. You should also be comfortable with JSON paths such as $.customer.id.
The state machine carries one JSON document
Every state receives one JSON value as input and produces one JSON value as output. The output of a state becomes the input of the next state. A state machine has no variables or shared memory, so a field is only available to a later state if it stays in this document.
Three limits follow from this:
- The document passed between states is limited to 256 KiB. A large payload makes the execution fail with
States.DataLimitExceeded. For big data, keep it in Amazon S3 and pass only a reference such as the bucket and key. - If a state overwrites the document, earlier fields are lost.
- Every field you keep is stored in the execution history, so sensitive values can show up there.
Step Functions has five fields for shaping the document, and a context object for metadata. This chapter covers the default JSONPath query language. Newer state machines can opt in to JSONata, which replaces these fields with Arguments, Output, and Assign. The JSONPath model is still what you will meet in most existing definitions.
The five fields and their order
| Field | Applies to | What it does |
|---|---|---|
| `InputPath` | Task, Pass, Parallel, Map, Choice, Wait | Selects the part of the input the state works on. |
| `Parameters` | Task, Pass, Parallel | Builds the payload sent to the task, using static values and paths. |
| `ResultSelector` | Task, Parallel, Map | Reshapes the raw result before it is combined with the input. |
| `ResultPath` | Task, Pass, Parallel, Map | Decides where the result goes in the state's input. |
| `OutputPath` | Task, Pass, Parallel, Map, Choice, Wait | Selects the part of the combined document to pass on. |
A Task state applies them in a fixed order, whatever order you write them in the JSON.
Note the dotted line. ResultPath merges the result into the input that InputPath already filtered, not into the original input. This detail causes many data-loss bugs.
A worked example
Suppose the state receives this input:
{
"order": {
"orderId": "1001",
"customer": { "id": "c-7", "email": "[email protected]" }
},
"traceId": "abc-123"
}The Task state below uses all five fields:
{
"ValidateOrder": {
"Type": "Task",
"Resource": "arn:aws:states:::lambda:invoke",
"InputPath": "$.order",
"Parameters": {
"FunctionName": "arn:aws:lambda:us-east-1:123456789012:function:ValidateOrder:$LATEST",
"Payload": {
"orderId.$": "$.orderId",
"customerId.$": "$.customer.id",
"executionName.$": "$$.Execution.Name",
"label.$": "States.Format('Order {}', $.orderId)"
}
},
"ResultSelector": {
"valid.$": "$.Payload.valid",
"reasons.$": "$.Payload.reasons"
},
"ResultPath": "$.validation",
"OutputPath": "$",
"End": true
}
}Follow the data through each step:
InputPathnarrows the input to theorderobject. ThetraceIdfield is no longer visible to this state.Parametersbuilds the request. A key that ends in.$is evaluated as a path or an intrinsic function, and its value replaces the key without the suffix.$$refers to the context object.States.Formatis an intrinsic function that fills{}placeholders.- The Lambda integration returns metadata around the function's result:
ExecutedVersion,Payload,SdkHttpMetadata,SdkResponseMetadata, andStatusCode. ResultSelectorkeeps only what you need:{"valid": true, "reasons": []}.ResultPathwrites that object into the filtered input at$.validation.OutputPathof$passes everything on.
The state output is:
{
"orderId": "1001",
"customer": { "id": "c-7", "email": "[email protected]" },
"validation": { "valid": true, "reasons": [] }
}The traceId field is gone, because InputPath removed it before ResultPath ran. If you need the trace ID later, do not use InputPath here. Select the order inside Parameters instead, for example "orderId.$": "$.order.orderId".
Choosing a ResultPath
ResultPath is the field that most often decides whether you lose data.
| Value | Effect |
|---|---|
| `"$"` (the default) | The result replaces the whole input. |
| `"$.validation"` | The result is added to the input at that field. An existing field of the same name is overwritten. |
| `null` | The result is discarded and the input passes through unchanged. |
Use null for tasks run only for their side effects, such as sending a notification. The path must be a simple reference path. Wildcards, slices, and filters are not allowed. If the input is not a JSON object, for example an array or a string, you cannot add a field to it and the state fails.
The context object
The context object, written $$, holds data about the execution that is not in your JSON. It is available in Parameters, and in Choice rules and ItemSelector.
| Path | Value |
|---|---|
| `$$.Execution.Id` | The execution ARN. |
| `$$.Execution.Name` | The execution name. |
| `$$.Execution.StartTime` | When the execution started. |
| `$$.State.Name` | The name of the current state. |
| `$$.State.EnteredTime` | When the current state started. |
| `$$.Task.Token` | The task token, only in `.waitForTaskToken` tasks. |
You used $$.Task.Token in the callback pattern from the previous chapter. The context object is read-only, and you can only reach it in places that accept .$ keys.
Intrinsic functions
Intrinsic functions transform values inside Parameters, ResultSelector, and ItemSelector, so you often do not need a Lambda function for simple changes. These are the most useful:
States.Format('text {}', $.value)builds a string.States.JsonToString($.obj)andStates.StringToJson($.text)convert between JSON and a string.States.Array($.a, $.b)builds an array.States.ArrayLength,States.ArrayContains, andStates.ArrayGetItemwork with arrays.States.JsonMerge($.a, $.b, false)merges two objects. The third argument must befalse, because deep merge is not supported.States.UUID()returns a random UUID, andStates.MathAdd($.n, 1)adds numbers, which is handy for counters in loops.
You can use these functions only in fields whose key ends with .$.
Data flow in other states
Other states use a subset of these fields:
- A
Choicestate reads its input withInputPath, evaluates the rules, and passes the input to the next state unchanged. You can narrow it withOutputPath. Rules refer to values withVariable, for example$.validation.valid. - A
Passstate copies input to output. WithResultit injects fixed JSON, andResultPathdecides where it goes. Pass states are useful for adding defaults or for testing a data flow before the real tasks exist. - A
Mapstate usesItemsPathto select the array. Each iteration receives one element as input, or a custom object built byItemSelector. The output is an array of the iteration results.ResultPathplaces that array in the Map state's input. Without it, the array replaces the whole input. - A
Parallelstate sends the same input to each branch, and returns an array with one result per branch, in branch order.
A common use of Pass is to set defaults, and Catch uses ResultPath in the same way. In the order-validation machine, Catch writes the error to $.error so the original input stays available to the failure path:
{
"Catch": [
{
"ErrorEquals": ["States.ALL"],
"ResultPath": "$.error",
"Next": "OrderFailed"
}
]
}Without that ResultPath, the error object (Error and Cause) replaces the input, and the failure handler cannot see the order.
Common errors
States.Runtimeerror on a path that returns nothing. A path inParametersorChoicepoints to a field that does not exist. Check the previous state's output in the execution history. Keep in mind thatResultPathandInputPathchange what is present.- Forgetting the
.$suffix."orderId": "$.orderId"sends the literal text$.orderId. Add.$to the key to evaluate it. - Adding
.$to a static value."mode.$": "fast"fails, because the value is not a valid path or function. - Losing fields with the default
ResultPath. If a state's result replaces the input, later states cannot reach earlier fields. SetResultPathto a named field. - Dropping fields with
InputPathorOutputPath. Both filter what the state keeps. Use them only when you are sure that later states do not need the rest. - Passing a raw Lambda result downstream. The integration wraps the output in metadata. Reference
$.Payloador useResultSelector, and do not assume the function's return value is at the top level. - Exceeding 256 KiB. Large results, especially from Map states, can fill the document. Use
ResultSelectorto trim,ResultPath: nullto discard, or write the data to S3. - Branches that expect shared state. Parallel branches and Map iterations cannot see each other's data. Combine their results after the state finishes.
To debug a data flow, open the execution in the console and select the state. The input, effective input, result, effective result, and output show each stage of processing. Compare them against the order above.
Exercise
A state receives {"order": {"id": "7"}, "user": "kim"}. It has "InputPath": "$.order", a Lambda task that returns {"total": 40}, "ResultSelector": {"amount.$": "$.Payload.total"}, and "ResultPath": "$.pricing". What is the state's output, and what would you change to keep the user field in the output?
Show answer
The output is {"id": "7", "pricing": {"amount": 40}}. InputPath removed the user field before ResultPath merged the result, so user is lost. Remove InputPath and read the order in Parameters instead, for example "orderId.$": "$.order.id". Then the full input stays in place, and the output becomes {"order": {"id": "7"}, "user": "kim", "pricing": {"amount": 40}}.