Guide · AWS Batch · Array Jobs
AWS Batch Array Jobs for MCP Servers — Parallel Dataset Processing
An AWS Batch array job is a single SubmitJobCommand call that launches N identical child jobs simultaneously, each receiving a unique index from 0 to N-1 via the AWS_BATCH_JOB_ARRAY_INDEX environment variable. The child job uses that index to determine which slice of the dataset to process. This model eliminates the need to write a fan-out orchestrator: submit one job, get up to 10,000 parallel workers at no additional API cost. This guide covers the full array job workflow for MCP server use cases: partitioning S3 datasets by index, monitoring parent and child job status, handling partial failures, and chaining array stages with sequential and N:N dependency types.
TL;DR
Add arrayProperties: { size: N } to SubmitJobCommand to launch N parallel child jobs. Each child reads process.env.AWS_BATCH_JOB_ARRAY_INDEX (integer 0..N-1) to determine its work slice. Poll the parent job ID with DescribeJobsCommand — the parent reaches SUCCEEDED only when all children succeed. Use ListJobsCommand with arrayJobId to paginate through individual child statuses. The parent job ID is returned by SubmitJobCommand; child job IDs are listed via ListJobs and follow the format {parentJobId}:{index}.
When to use array jobs
Array jobs are the right tool when:
- You have a fixed-size dataset (list of S3 keys, database row ranges, file manifest) that can be divided into N independent chunks.
- Each chunk is processed identically and independently — no chunk depends on another chunk's output within the same stage.
- You want maximum parallelism without writing fan-out orchestration code.
- The total dataset is too large for a single container but each slice fits within the per-container resource limits.
MCP server use cases: parallel PDF processing (one child per document), database shard migration (one child per shard), ML batch inference (one child per data partition), nightly report generation (one child per tenant/account), multi-region health checks (one child per region).
Submitting an array job
import { BatchClient, SubmitJobCommand } from "@aws-sdk/client-batch";
const batch = new BatchClient({ region: "us-east-1" });
// Submit 500 parallel child jobs
const result = await batch.send(new SubmitJobCommand({
jobName: "process-documents-20261114",
jobQueue: "arn:aws:batch:us-east-1:123456789012:job-queue/mcp-jobs",
jobDefinition: "arn:aws:batch:us-east-1:123456789012:job-definition/document-processor:1",
// Array job: launch 500 children (index 0..499)
arrayProperties: {
size: 500,
},
// Pass common context to all children via environment override
containerOverrides: {
environment: [
{ name: "INPUT_MANIFEST_KEY", value: "manifests/docs-2026-11-14.json" },
{ name: "OUTPUT_PREFIX", value: "processed/2026-11-14/" },
],
},
}));
const parentJobId = result.jobId;
console.log("Array job submitted:", parentJobId);
// parentJobId = "ff4a3b2e-1234-5678-abcd-ef0123456789"
// Child job IDs: "ff4a3b2e...:0", "ff4a3b2e...:1", ..., "ff4a3b2e...:499"
Constraints:
- Maximum array size: 10,000 children per submission.
- Minimum array size: 2 (a single-child array is not valid — submit a regular job instead).
- Each child is a separate billable job consuming resources independently.
- All children share the same job definition revision, container image, and
containerOverrides. The only per-child differentiator isAWS_BATCH_JOB_ARRAY_INDEX.
Using AWS_BATCH_JOB_ARRAY_INDEX inside the container
AWS Batch injects AWS_BATCH_JOB_ARRAY_INDEX as an integer string (0..N-1) into every child container's environment. The container code uses it to determine which data slice to process.
Pattern 1: Index into a pre-built manifest list
Write a manifest file to S3 before submitting the array job. Each child reads the manifest and processes its assigned entry:
// Before submitting: write manifest to S3
const manifest = documentKeys.map(key => ({ key }));
await s3.send(new PutObjectCommand({
Bucket: "my-bucket",
Key: "manifests/docs-2026-11-14.json",
Body: JSON.stringify(manifest),
}));
// Then submit array job with size = manifest.length
// Inside the container:
const index = parseInt(process.env.AWS_BATCH_JOB_ARRAY_INDEX!, 10);
const manifestKey = process.env.INPUT_MANIFEST_KEY!;
const response = await s3.send(new GetObjectCommand({ Bucket: "my-bucket", Key: manifestKey }));
const manifest = JSON.parse(await response.Body!.transformToString());
const { key: documentKey } = manifest[index];
await processDocument(documentKey);
Pattern 2: S3 key range by prefix listing
For large S3 listings, partition the full object list into N buckets by modular arithmetic:
// Inside the container
const index = parseInt(process.env.AWS_BATCH_JOB_ARRAY_INDEX!, 10);
const totalJobs = parseInt(process.env.ARRAY_SIZE!, 10); // pass via containerOverrides env
// List all keys under prefix, process only those where hash(key) % totalJobs === index
// This is deterministic — same key always maps to same child
let continuationToken: string | undefined;
do {
const listResult = await s3.send(new ListObjectsV2Command({
Bucket: "my-bucket",
Prefix: "uploads/",
ContinuationToken: continuationToken,
}));
for (const obj of listResult.Contents ?? []) {
const keyHash = simpleHash(obj.Key!);
if (keyHash % totalJobs === index) {
await processObject(obj.Key!);
}
}
continuationToken = listResult.NextContinuationToken;
} while (continuationToken);
function simpleHash(str: string): number {
let hash = 0;
for (let i = 0; i < str.length; i++) {
hash = ((hash << 5) - hash) + str.charCodeAt(i);
hash |= 0;
}
return Math.abs(hash);
}
Pattern 3: Row range from a database table
// Inside the container
const index = parseInt(process.env.AWS_BATCH_JOB_ARRAY_INDEX!, 10);
const totalJobs = parseInt(process.env.ARRAY_SIZE!, 10);
const totalRows = parseInt(process.env.TOTAL_ROWS!, 10);
const rowsPerChild = Math.ceil(totalRows / totalJobs);
const startRow = index * rowsPerChild;
const endRow = Math.min(startRow + rowsPerChild, totalRows);
// SELECT * FROM table WHERE id BETWEEN startRow AND endRow-1 ORDER BY id
const rows = await db.query(
"SELECT * FROM documents WHERE id >= $1 AND id < $2 ORDER BY id",
[startRow, endRow]
);
Monitoring array job status
Parent job status
The parent job ID returned by SubmitJobCommand is a summary node. It reflects aggregate status:
RUNNING— at least one child is running.SUCCEEDED— all children succeeded.FAILED— at least one child failed after exhausting retries.
// Poll parent job for overall completion
const { jobs } = await batch.send(new DescribeJobsCommand({ jobs: [parentJobId] }));
const parent = jobs![0];
console.log("Parent status:", parent.status);
// arrayProperties.statusSummary shows aggregate child counts
const summary = parent.arrayProperties?.statusSummary;
console.log("Children — SUCCEEDED:", summary?.SUCCEEDED,
"FAILED:", summary?.FAILED,
"RUNNING:", summary?.RUNNING,
"RUNNABLE:", summary?.RUNNABLE);
Listing individual child jobs
import { ListJobsCommand } from "@aws-sdk/client-batch";
// Paginate through all children of an array job
async function listArrayChildren(parentJobId: string) {
const children: any[] = [];
let nextToken: string | undefined;
do {
const result = await batch.send(new ListJobsCommand({
arrayJobId: parentJobId, // Filter by parent array job
jobStatus: "FAILED", // Or omit to list all statuses
maxResults: 100,
nextToken,
}));
children.push(...(result.jobSummaryList ?? []));
nextToken = result.nextToken;
} while (nextToken);
return children;
}
const failedChildren = await listArrayChildren(parentJobId);
console.log(`${failedChildren.length} failed children`);
for (const child of failedChildren) {
// child.jobId = "ff4a3b2e-...:42" — includes parent ID and child index
console.log(`Child index: ${child.arrayProperties?.index}, reason: ${child.statusReason}`);
}
Partial failures and retry behavior
Array job retries happen at the child level, not the parent level. Each child has its own attempts budget from the job definition's retryStrategy. The parent job does not have a retry strategy of its own — it aggregates child outcomes.
If a child fails all its retry attempts, it enters FAILED. The parent immediately enters FAILED too — it does not wait for other children to finish. Already-running children complete their current attempt, but no new children start once the parent is FAILED.
To allow partial success (process what we can, fail fast on irrecoverable errors), handle failures gracefully in the container code and exit with code 0:
// Container code that never fails the child — logs errors, writes to dead-letter
async function main() {
const index = parseInt(process.env.AWS_BATCH_JOB_ARRAY_INDEX!, 10);
const key = manifest[index].key;
try {
await processDocument(key);
console.log(`[index ${index}] OK: ${key}`);
} catch (err) {
// Write to dead-letter prefix instead of failing the child
await s3.send(new PutObjectCommand({
Bucket: "my-bucket",
Key: `dead-letter/${key}.error.json`,
Body: JSON.stringify({ key, error: String(err), index }),
}));
console.error(`[index ${index}] DEAD-LETTER: ${key} — ${err}`);
}
// Always exit 0 — parent job will SUCCEED even if some documents failed
process.exit(0);
}
Sequential dependency between array children
The SEQUENTIAL dependency type chains children within an array: child N waits for child N-1 to succeed before starting. This converts the array job from a purely parallel fan-out into a sequential pipeline — useful for ordered processing where order matters but you still want the declaration simplicity of a single submission:
// N children run in order: child[0] → child[1] → ... → child[N-1]
const result = await batch.send(new SubmitJobCommand({
jobName: "sequential-pipeline",
jobQueue: queueArn,
jobDefinition: jobDefArn,
arrayProperties: { size: 10 },
dependsOn: [
{
type: "SEQUENTIAL",
// Note: jobId is omitted for SEQUENTIAL — it refers to the array job's own children
},
],
}));
Warning: SEQUENTIAL within an array job is unusual and rarely what you want — it limits throughput to one child at a time. For true ordered processing, consider submitting individual jobs with dependsOn between them (see the job dependencies guide). SEQUENTIAL array jobs are mostly useful for staged operations where each step must see the previous step's side effects.
N:N dependency between two array jobs
An N:N dependency links two array jobs of the same size: child B[i] waits for child A[i] before starting. This creates N parallel pipelines, each of length 2 (or more with chaining). It's the natural model for multi-stage array processing:
// Stage 1: extract (500 children)
const extractResult = await batch.send(new SubmitJobCommand({
jobName: "extract-stage",
jobQueue: queueArn,
jobDefinition: extractJobDefArn,
arrayProperties: { size: 500 },
containerOverrides: { environment: [{ name: "STAGE", value: "extract" }] },
}));
// Stage 2: transform (500 children) — child[i] waits for extract[i]
const transformResult = await batch.send(new SubmitJobCommand({
jobName: "transform-stage",
jobQueue: queueArn,
jobDefinition: transformJobDefArn,
arrayProperties: { size: 500 }, // Must match extract size exactly
dependsOn: [
{
jobId: extractResult.jobId, // Parent array job ID
type: "N_TO_N", // Child i waits for child i in the dependency
},
],
containerOverrides: { environment: [{ name: "STAGE", value: "transform" }] },
}));
Requirements for N:N dependencies:
- Both array jobs must have exactly the same
arrayProperties.size. Mismatched sizes produceClientException: Array size mismatch for N_TO_N dependency. - The dependency array job must already exist (be submitted) when you submit the dependent job.
- N:N chains can be nested: stage C[i] can depend on transform[i], which depends on extract[i] — building up to a 3-stage per-index pipeline.
Full example: parallel S3 document processing
import {
BatchClient,
SubmitJobCommand,
DescribeJobsCommand,
} from "@aws-sdk/client-batch";
import {
S3Client,
ListObjectsV2Command,
PutObjectCommand,
} from "@aws-sdk/client-s3";
const batch = new BatchClient({ region: "us-east-1" });
const s3 = new S3Client({ region: "us-east-1" });
async function runParallelDocumentProcessing(inputPrefix: string, outputPrefix: string) {
// 1. Build manifest
const keys: string[] = [];
let token: string | undefined;
do {
const list = await s3.send(new ListObjectsV2Command({
Bucket: "my-bucket", Prefix: inputPrefix, ContinuationToken: token,
}));
keys.push(...(list.Contents ?? []).map(o => o.Key!));
token = list.NextContinuationToken;
} while (token);
if (keys.length === 0) { console.log("No objects to process"); return; }
if (keys.length > 10_000) throw new Error("Too many objects for one array job — paginate further");
// 2. Write manifest to S3
const manifestKey = `manifests/run-${Date.now()}.json`;
await s3.send(new PutObjectCommand({
Bucket: "my-bucket",
Key: manifestKey,
Body: JSON.stringify(keys.map(key => ({ key }))),
}));
// 3. Submit array job
const { jobId } = await batch.send(new SubmitJobCommand({
jobName: `process-${Date.now()}`,
jobQueue: "arn:aws:batch:us-east-1:123456789012:job-queue/mcp-jobs",
jobDefinition: "document-processor",
arrayProperties: { size: keys.length },
containerOverrides: {
environment: [
{ name: "MANIFEST_KEY", value: manifestKey },
{ name: "OUTPUT_PREFIX", value: outputPrefix },
{ name: "ARRAY_SIZE", value: String(keys.length) },
],
},
}));
console.log(`Submitted array job ${jobId} with ${keys.length} children`);
// 4. Poll parent job until terminal
while (true) {
const { jobs } = await batch.send(new DescribeJobsCommand({ jobs: [jobId] }));
const job = jobs![0];
const s = job.arrayProperties?.statusSummary ?? {};
console.log(`Status: ${job.status} | SUCCEEDED: ${s.SUCCEEDED ?? 0} RUNNING: ${s.RUNNING ?? 0} FAILED: ${s.FAILED ?? 0}`);
if (job.status === "SUCCEEDED") break;
if (job.status === "FAILED")
throw new Error(`Array job failed — ${s.FAILED} children failed`);
await new Promise(r => setTimeout(r, 15_000));
}
console.log("All children succeeded!");
}
await runParallelDocumentProcessing("uploads/2026-11-14/", "processed/2026-11-14/");
Related guides
- AWS Batch overview: job definitions, compute environments, and job queues
- AWS Batch with Fargate: vCPU/memory combinations and spot interruption handling
- AWS Batch job dependencies: fan-in, fan-out, and DAG workflows
- S3 Intelligent-Tiering for large-dataset cost optimization
- MCP server uptime monitoring