Sub topic 13
Processing large datasets with Distributed Map
This chapter assumes you know the inline Map state, Retry and Catch, and how a Standard workflow differs from an Express workflow. It also assumes you can read an IAM policy. By the end you should be able to configure a Distributed Map that reads a large S3 object, fans out to child executions, tolerates some failures, and writes results back to S3.
Why inline Map is not enough
An inline Map runs its iterations inside the parent execution. That has three limits:
- The input array must fit in the 256 KiB state payload.
- Iterations count against the parent's execution history, which has a hard event limit.
- Concurrency is capped at a small number.
A Distributed Map removes all three. It reads items directly from S3 and starts a separate child workflow execution for each item or batch. Each child has its own execution history. You can run up to 10,000 child executions in parallel, subject to your account's quotas. Typical uses are converting millions of images, validating a large CSV, or running a Lambda function over every object in a bucket.
A Distributed Map state must live in a Standard workflow. Its children can be Standard or Express.
The shape of a Distributed Map
The state has four parts you configure beyond a normal Map:
ItemReadertells the state where the items come from.ItemBatcher(optional) groups items so that one child handles many.ItemProcessorwith"Mode": "DISTRIBUTED"defines the child workflow.ResultWriter(optional) stores the combined results in S3.
Reading items from S3
ItemReader supports these sources:
| Source | `InputType` | Notes |
|---|---|---|
| JSON array in an S3 object | `JSON` | The object must hold an array at the top level. |
| JSON Lines file | `JSONL` | One JSON object per line. |
| CSV file | `CSV` | Set `CSVHeaderLocation` to `FIRST_ROW` or `GIVEN`. |
| S3 inventory report | `MANIFEST` | Useful for buckets with very many objects. |
| Listing of objects under a prefix | none (uses `s3:listObjectsV2`) | Each item is object metadata, not contents. |
For CSV with FIRST_ROW, each item is an object whose keys are the column headers. If a column is named orderId, the child sees {"orderId": "1001", ...}.
You can also feed a Distributed Map from the state input, for example when the previous state produced a large array. S3 is the usual choice, because it avoids the payload limit altogether.
A complete example
This state machine reads orders.csv, batches 100 rows at a time, invokes a Lambda function per batch in Express child executions, tolerates up to 5 percent failed batches, and writes the results to S3.
{
"Comment": "Process a large CSV of orders in batches",
"StartAt": "ProcessOrders",
"States": {
"ProcessOrders": {
"Type": "Map",
"ItemReader": {
"Resource": "arn:aws:states:::s3:getObject",
"ReaderConfig": {
"InputType": "CSV",
"CSVHeaderLocation": "FIRST_ROW"
},
"Parameters": {
"Bucket": "example-orders-bucket",
"Key": "input/orders.csv"
}
},
"ItemBatcher": {
"MaxItemsPerBatch": 100,
"BatchInput": {
"source": "orders.csv"
}
},
"MaxConcurrency": 1000,
"ToleratedFailurePercentage": 5,
"Label": "orderbatch",
"ItemProcessor": {
"ProcessorConfig": {
"Mode": "DISTRIBUTED",
"ExecutionType": "EXPRESS"
},
"StartAt": "HandleBatch",
"States": {
"HandleBatch": {
"Type": "Task",
"Resource": "arn:aws:states:::lambda:invoke",
"Parameters": {
"FunctionName": "arn:aws:lambda:us-east-1:123456789012:function:ProcessOrderBatch:$LATEST",
"Payload.$": "$"
},
"OutputPath": "$.Payload",
"Retry": [
{
"ErrorEquals": ["Lambda.ServiceException", "Lambda.TooManyRequestsException"],
"IntervalSeconds": 2,
"MaxAttempts": 3,
"BackoffRate": 2.0
}
],
"End": true
}
}
},
"ResultWriter": {
"Resource": "arn:aws:states:::s3:putObject",
"Parameters": {
"Bucket": "example-orders-bucket",
"Prefix": "output"
}
},
"End": true
}
}
}With ItemBatcher, each child receives one input of this form:
{
"BatchInput": { "source": "orders.csv" },
"Items": [
{ "orderId": "1001", "amount": "19.99" },
{ "orderId": "1002", "amount": "5.00" }
]
}Your Lambda function must therefore loop over event["Items"]. A common mistake is to write the function for single items and then add a batcher. The function then fails on every invocation because orderId is not a top-level key.
Batching
Starting a child execution per row is wasteful for small rows. Batching trades parallelism for lower overhead and fewer child executions. Choose it based on these constraints:
- A batch is limited by
MaxItemsPerBatchand byMaxInputBytesPerBatch. A batch's input must stay under 256 KiB, so wide rows need smaller batches. - A child processes its batch as one unit. If one row fails, the whole batch is a failure unless your code reports per-row failures in its own output.
- Use
MaxItemsPerBatchPathorMaxInputBytesPerBatchPathwhen you want to set these values from the state input at run time.
Concurrency, failure tolerance, and labels
MaxConcurrency limits how many child executions run at once. If you omit it, the service uses its maximum. Set it explicitly when a downstream system, such as a database or a Lambda function with limited reserved concurrency, cannot absorb a burst.
Failure thresholds decide when the whole Map Run stops:
ToleratedFailurePercentagetakes 0 to 100.ToleratedFailureCounttakes an absolute number of failed items or batches.
If the failures exceed the threshold, the Map state fails with States.ExceedToleratedFailureThreshold and the remaining children are stopped. With the default of zero, the first failed child fails the state. A Catch on the Map state handles that error like any other.
Label is a prefix for the Map Run's name. It helps you find the run, and its child executions, in the console and CLI.
Child execution type: Standard or Express
| Property | `STANDARD` child | `EXPRESS` child |
|---|---|---|
| Maximum duration | up to one year | 5 minutes |
| Semantics | exactly-once workflow execution | at-least-once |
| History | full execution history via the API | CloudWatch Logs only |
| Cost profile | priced per state transition | priced per request and duration |
Pick Express for short, high-volume, idempotent work. Express children can run more than once, so a non-idempotent write, such as charging a card, needs an idempotency key. Pick Standard when children are long, include .waitForTaskToken or .sync steps, or need a queryable history per item.
Writing results
The output of a Distributed Map can exceed the 256 KiB limit that applies to any state's output. ResultWriter avoids this by writing results to S3. The state's own output then contains only a pointer, including the Map Run ARN and the location of the result files. Under your prefix, Step Functions writes:
manifest.json, which lists the other files and summarizes counts of succeeded, failed, and pending items.SUCCEEDED_0.json,FAILED_0.json, andPENDING_0.json, each of which may be split into numbered parts when large.
Without a ResultWriter, the state attempts to return all results inline, and the execution fails if they do not fit. For a large run, always configure one.
Permissions
The parent's execution role needs more than the usual task permissions:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::example-orders-bucket/input/*"
},
{
"Effect": "Allow",
"Action": "s3:PutObject",
"Resource": "arn:aws:s3:::example-orders-bucket/output/*"
},
{
"Effect": "Allow",
"Action": "states:StartExecution",
"Resource": "arn:aws:states:us-east-1:123456789012:stateMachine:OrderWorkflow"
},
{
"Effect": "Allow",
"Action": "lambda:InvokeFunction",
"Resource": "arn:aws:lambda:us-east-1:123456789012:function:ProcessOrderBatch:*"
}
]
}The states:StartExecution statement targets the state machine itself because child executions run under the same state machine definition. If you read by listing a prefix, add s3:ListBucket on the bucket ARN. The distinction between bucket-level and object-level resources causes frequent AccessDenied failures.
Inspecting a Map Run
Each Distributed Map execution creates a Map Run resource. It tracks totals of pending, running, succeeded, failed, timed-out, and aborted children. You can inspect it in the console or with the CLI:
aws stepfunctions describe-map-run \
--map-run-arn arn:aws:states:us-east-1:123456789012:mapRun:OrderWorkflow/orderbatch:11111111-2222-3333-4444-555555555555You can also call list-executions with a --map-run-arn to list the child executions, and update-map-run to change MaxConcurrency and the failure thresholds while the run is in progress. After a partial failure, redrive the parent execution to rerun only the failed children, instead of repeating the entire dataset. Redrive is available for Standard parent executions within a limited time after they finish.
Common errors
- Payload too large. Either the batch exceeds 256 KiB, or you have no
ResultWriterand the combined output is too big. - Throttling downstream. High
MaxConcurrencyagainst a rate-limited Lambda function or API produces throttle errors. Lower the concurrency, or retry with backoff. - Wrong item shape. A function that expects single items gets a batch, or the CSV header row is treated as data because
CSVHeaderLocationis missing. - Non-idempotent Express children. At-least-once execution leads to duplicate side effects.
- Missing S3 permissions. The role can read the object but not list the bucket, or cannot write the result prefix.
Exercise
A Distributed Map reads a 5 million-row CSV. Each row is about 400 bytes. Your Lambda function takes one row and takes about 50 ms. You see high cost and many throttles. Name two configuration changes you would make, and say what each one fixes.
Show answer
Add an ItemBatcher (for example MaxItemsPerBatch of 500, giving about 200 KB per batch, under the 256 KiB limit) and update the Lambda function to loop over the Items array. This reduces the number of child executions and their per-execution overhead. Then lower MaxConcurrency, or use Express children with Retry and backoff for Lambda.TooManyRequestsException, so that the function's concurrency limit is not exceeded. Also add a ResultWriter so the combined output does not hit the payload limit.
Exercise
Your Distributed Map has ToleratedFailurePercentage set to 0. One of 10,000 batches fails. What happens, and how can you let the run complete?
Show answer
The first failed child pushes failures over the threshold, so the Map state fails with States.ExceedToleratedFailureThreshold and the remaining children stop. To let the run finish, set ToleratedFailurePercentage or ToleratedFailureCount to an acceptable value, then review FAILED_0.json and redrive or reprocess only the failed batches.