Guide · AWS Batch · Batch Computing
AWS Batch for MCP Servers — Managed Batch Computing with Fargate and EC2
AWS Batch is a fully managed service that provisions, scales, and terminates the compute capacity needed to run containerized batch jobs. Unlike Lambda (15-minute limit, ephemeral filesystem) or always-on ECS services (pay even when idle), Batch scales from zero — you submit a job, Batch provisions capacity, runs the container, and terminates the capacity when done. For MCP server teams, Batch solves three problems that Lambda can't: processing documents or datasets that take hours rather than minutes, running jobs that need more than 10 GB of memory or 6 vCPUs, and building multi-stage pipelines where each stage's output feeds the next. This guide covers the AWS Batch JavaScript SDK end to end: registering job definitions, creating compute environments, creating job queues, submitting jobs, and tracking status.
TL;DR
AWS Batch requires three one-time infrastructure objects before you can submit a job: a Compute Environment (the fleet — Fargate or EC2), a Job Queue (the work buffer — routes submissions to a compute environment), and a Job Definition (the template — container image, vCPU/memory, IAM roles, retry strategy). Once those exist, every SubmitJobCommand produces a job that moves through SUBMITTED → PENDING → RUNNABLE → STARTING → RUNNING → SUCCEEDED/FAILED. Poll with DescribeJobsCommand or subscribe to EventBridge Batch Job State Change events instead of polling. The minimum IAM permissions needed to submit and monitor jobs: batch:SubmitJob, batch:DescribeJobs, and batch:ListJobs.
When MCP servers use AWS Batch
AWS Batch is the right choice for MCP server use cases that exceed Lambda's constraints:
- Long document processing — PDF/Office extraction, OCR, format conversion where a single document can take 2–20 minutes. Lambda's 15-minute timeout eliminates the tail of large files. Batch has no timeout by default (you configure one per job definition).
- Large-memory data processing — Embedding generation, ML inference on large models, or in-memory joins of multi-GB datasets. Lambda caps at 10 GB RAM; Batch on EC2 supports up to 448 GB on memory-optimized instances.
- Report generation and data export — Nightly or on-demand exports from a database that might read 100 million rows and write a 2 GB CSV to S3. Lambda timeouts before the query finishes; Batch is designed for it.
- Parallel dataset processing — Array jobs split a large dataset into N identical slices processed in parallel. A 10,000-item array job runs all 10,000 children concurrently (subject to compute environment capacity).
- Multi-stage ETL pipelines — Native job dependencies let stage B wait for stage A's success before starting. For complex branching, combine Batch dependencies with Step Functions.
The AWS Batch vs Lambda vs ECS decision simplifies to: Lambda for quick stateless actions (<15 min, <10 GB), ECS for long-lived services, Batch for jobs that have a defined start and end and unpredictable volume.
| Dimension | Lambda | ECS Fargate | AWS Batch (Fargate) |
|---|---|---|---|
| Max duration | 15 minutes | Unlimited (service) | Unlimited (configurable timeout) |
| Max vCPU | 6 vCPU | 16 vCPU | 16 vCPU (Fargate), 96+ (EC2) |
| Max memory | 10 GB | 120 GB | 120 GB (Fargate), 384+ GB (EC2) |
| Idle cost | $0 | $$ (always running) | $0 (scales to zero) |
| Queue + priority | No | No | Yes (multiple queues, priorities) |
| Array jobs | No | No | Yes (up to 10,000 children) |
| Job dependencies | No | No | Yes (fan-in, fan-out, N:N) |
| Retry with reason filters | Yes (Lambda destinations) | No | Yes (exit-code and reason filters) |
Install the Batch SDK client
npm install @aws-sdk/client-batch
import {
BatchClient,
RegisterJobDefinitionCommand,
CreateComputeEnvironmentCommand,
CreateJobQueueCommand,
SubmitJobCommand,
DescribeJobsCommand,
ListJobsCommand,
TerminateJobCommand,
} from "@aws-sdk/client-batch";
const batch = new BatchClient({ region: "us-east-1" });
Step 1 — Create a Compute Environment
A Compute Environment (CE) defines the capacity pool. For most MCP server use cases, choose FARGATE or FARGATE_SPOT — no AMI management, faster scaling, and per-second billing.
const ceResult = await batch.send(new CreateComputeEnvironmentCommand({
computeEnvironmentName: "mcp-fargate-ce",
type: "MANAGED", // MANAGED = Batch provisions capacity
state: "ENABLED",
computeResources: {
type: "FARGATE", // FARGATE | FARGATE_SPOT | EC2 | SPOT
maxvCpus: 256, // Max total vCPUs across all running jobs
subnets: ["subnet-0abc123", "subnet-0def456"],
securityGroupIds: ["sg-0a1b2c3d"],
},
serviceRole: "arn:aws:iam::123456789012:role/AWSBatchServiceRole",
}));
// computeEnvironmentArn is used when creating job queues
const ceArn = ceResult.computeEnvironmentArn;
Key parameters:
type: "MANAGED"— Batch provisions, scales, and terminates instances.UNMANAGEDmeans you bring your own EC2 fleet (rare for Fargate workloads).computeResources.type—FARGATEfor on-demand;FARGATE_SPOTfor up to 70% discount with interruption risk;EC2andSPOTfor custom instance types.maxvCpus— Hard ceiling on total vCPUs Batch will provision. If a queue has more submitted jobs thanmaxvCpuscan accommodate, jobs stayRUNNABLEuntil capacity is freed. Set this generously for throughput-sensitive workloads.subnets— Fargate tasks need VPC subnets with internet access (NAT gateway or VPC endpoints) if jobs pull from ECR or call AWS APIs.serviceRole— Must be theAWSBatchServiceRoleIAM role, which allows Batch to manage ECS tasks on your behalf. Use the AWS-managed version:arn:aws:iam::ACCOUNT:role/AWSBatchServiceRole. If the role does not exist, create it via the Batch console's first-run wizard.
For Fargate compute environments, instanceTypes, allocationStrategy, bidPercentage, and minvCpus are not valid — Fargate does not expose instance types. Including them causes ClientException: computeResources.instanceTypes is not supported for FARGATE.
Step 2 — Create a Job Queue
A Job Queue buffers submitted jobs and routes them to one or more Compute Environments in priority order. Batch picks the highest-priority CE that has available capacity.
const queueResult = await batch.send(new CreateJobQueueCommand({
jobQueueName: "mcp-jobs",
state: "ENABLED",
priority: 100, // Higher = more preferred when sharing CEs across queues
computeEnvironmentOrder: [
{
order: 1, // Try CE #1 first
computeEnvironment: ceArn,
},
// Add a spot CE as overflow at order 2 for cost savings:
// { order: 2, computeEnvironment: spotCeArn }
],
}));
const queueArn = queueResult.jobQueueArn;
When multiple queues share the same Compute Environment, the queue with the higher priority value gets its RUNNABLE jobs dispatched first. Priority must be a positive integer — no particular scale is defined, so use 1–1000 by convention (100 = normal, 10 = background, 1000 = urgent).
Step 3 — Register a Job Definition
A Job Definition is a versioned template for a job. Registering a new revision does not replace the old one — the old revision stays ACTIVE until you explicitly deregister it. Submit jobs by definition ARN to pin to a specific version, or by name to use the latest active revision.
const defResult = await batch.send(new RegisterJobDefinitionCommand({
jobDefinitionName: "document-processor",
type: "container",
platformCapabilities: ["FARGATE"], // Required for Fargate CEs
containerProperties: {
image: "123456789012.dkr.ecr.us-east-1.amazonaws.com/doc-processor:latest",
// For Fargate, use resourceRequirements instead of vcpus/memory (deprecated)
resourceRequirements: [
{ type: "VCPU", value: "1" },
{ type: "MEMORY", value: "2048" }, // MB
],
// executionRoleArn — used by ECS agent to pull ECR image and push CloudWatch logs
executionRoleArn: "arn:aws:iam::123456789012:role/ecsTaskExecutionRole",
// jobRoleArn — used by application code to call S3, DynamoDB, etc.
jobRoleArn: "arn:aws:iam::123456789012:role/BatchDocProcessorJobRole",
// networkConfiguration required for Fargate
networkConfiguration: {
assignPublicIp: "ENABLED", // DISABLED if using NAT gateway
},
// fargatePlatformConfiguration — optional, defaults to LATEST
fargatePlatformConfiguration: {
platformVersion: "LATEST", // Or pin: "1.4.0"
},
// Environment variables available to all jobs using this definition
environment: [
{ name: "OUTPUT_BUCKET", value: "my-output-bucket" },
{ name: "LOG_LEVEL", value: "info" },
],
// CloudWatch Logs configuration
logConfiguration: {
logDriver: "awslogs",
options: {
"awslogs-group": "/aws/batch/document-processor",
"awslogs-region": "us-east-1",
"awslogs-stream-prefix": "job",
},
},
},
retryStrategy: {
attempts: 3, // Retry up to 3 times on non-zero exit
evaluateOnExit: [
{
onExitCode: "0",
action: "EXIT", // Success — do not retry
},
{
onReason: "CannotPullContainerError*",
action: "RETRY", // Transient ECR pull failure — retry
},
{
onStatusReason: "Host EC2*terminated",
action: "RETRY", // Spot interruption — retry
},
],
},
timeout: {
attemptDurationSeconds: 3600, // 1-hour per-attempt wall clock limit
},
}));
const jobDefArn = defResult.jobDefinitionArn;
// e.g. "arn:aws:batch:us-east-1:123456789012:job-definition/document-processor:1"
Important field notes:
platformCapabilities: ["FARGATE"]— Required when you intend to submit to a Fargate CE. If omitted, Batch assumes EC2 and rejects submission to a Fargate queue withINVALIDstatus reason.resourceRequirements— The old top-levelvcpusandmemoryfields are deprecated for Fargate. UseresourceRequirementswith typeVCPU(string, not integer) andMEMORY(MB). Valid Fargate vCPU:memory pairs are enumerated — see the AWS Batch Fargate guide for the full table.executionRoleArn— Used by the ECS agent (Fargate's control plane) to pull the Docker image from ECR and push log streams to CloudWatch. Must haveAmazonECSTaskExecutionRolePolicyattached, pluslogs:CreateLogGroupif you want Batch to auto-create the log group.jobRoleArn— Credentials that your application code inside the container uses. Separate fromexecutionRoleArn. Attach only the S3/DynamoDB/SQS permissions the job actually needs.evaluateOnExit— Conditional retry rules evaluated after each attempt. Supports glob patterns ononExitCode,onReason, andonStatusReason. The first matching rule wins.RETRYconsumes one of theattemptsbudget;EXITterminates regardless of remaining attempts.
Step 4 — Submit a Job
const submitResult = await batch.send(new SubmitJobCommand({
jobName: "process-doc-20261114",
jobQueue: queueArn, // Or queue name string
jobDefinition: jobDefArn, // Or "document-processor" for latest revision
// Override specific fields from the job definition
containerOverrides: {
environment: [
{ name: "INPUT_KEY", value: "uploads/report-2026.pdf" },
{ name: "OUTPUT_KEY", value: "processed/report-2026.json" },
],
// Override resource allocation per-submission if needed:
// resourceRequirements: [{ type: "MEMORY", value: "4096" }],
},
// Pass named parameters defined in the job definition template
// parameters: { docType: "pdf", maxPages: "500" },
}));
const jobId = submitResult.jobId;
console.log("Submitted job:", jobId);
jobName must be 1–128 characters, alphanumeric plus -_. It does not have to be unique — Batch uses the returned jobId (UUID) as the unique identifier.
Step 5 — Track Job Status
Job status lifecycle
Every Batch job passes through a linear status progression:
| Status | Meaning |
|---|---|
SUBMITTED |
Job accepted by Batch, not yet evaluated for dependencies or placement |
PENDING |
Waiting for a job it depends on to complete |
RUNNABLE |
Ready to run; waiting for compute capacity in the CE |
STARTING |
ECS task is being provisioned |
RUNNING |
Container is executing |
SUCCEEDED |
Container exited with code 0 |
FAILED |
Container exited non-zero, or Batch could not start it, after all retries exhausted |
Polling approach
async function waitForJob(jobId: string, pollIntervalMs = 10_000): Promise<string> {
const terminalStatuses = new Set(["SUCCEEDED", "FAILED"]);
while (true) {
const { jobs } = await batch.send(new DescribeJobsCommand({ jobs: [jobId] }));
const job = jobs?.[0];
if (!job) throw new Error(`Job ${jobId} not found`);
console.log(`Job ${jobId}: ${job.status} — ${job.statusReason ?? ""}`);
if (terminalStatuses.has(job.status!)) {
if (job.status === "FAILED") {
throw new Error(`Job failed: ${job.statusReason}`);
}
return job.status!;
}
await new Promise(r => setTimeout(r, pollIntervalMs));
}
}
DescribeJobsCommand accepts up to 100 job IDs per call. For monitoring multiple concurrent jobs, batch them into groups of 100 to minimize API calls. DescribeJobs is in the standard service quota (no throttle concern at typical volumes).
EventBridge approach (preferred for production)
Polling burns Lambda invocations and adds latency. For production pipelines, subscribe to Batch events via EventBridge instead:
// EventBridge rule pattern — catches any terminal state change
{
"source": ["aws.batch"],
"detail-type": ["Batch Job State Change"],
"detail": {
"status": ["SUCCEEDED", "FAILED"]
}
}
// The event detail contains:
// { jobId, jobName, jobQueue, jobDefinition, status, statusReason, attempts, container }
Wire the rule to an SNS topic, SQS queue, or Lambda function. This eliminates polling latency and reduces cost for long-running jobs where polling would run for hours.
IAM configuration
AWS Batch requires three distinct IAM roles:
| Role | Used by | Required policies |
|---|---|---|
AWSBatchServiceRole |
Batch control plane | AWSBatchServiceRole managed policy (auto-attached if you let the console create it) |
ecsTaskExecutionRole |
ECS agent (pulls image, pushes logs) | AmazonECSTaskExecutionRolePolicy + logs:CreateLogGroup |
| Job role (your name) | Application code inside the container | Specific permissions: s3:GetObject, s3:PutObject, dynamodb:PutItem, etc. |
The IAM principal that calls SubmitJobCommand from your MCP server needs:
{
"Effect": "Allow",
"Action": [
"batch:SubmitJob",
"batch:DescribeJobs",
"batch:ListJobs",
"batch:TerminateJob"
],
"Resource": "*"
}
For tighter scoping, replace "Resource": "*" with the specific job queue ARN and job definition ARN.
Terminate a running job
await batch.send(new TerminateJobCommand({
jobId,
reason: "Cancelled by MCP tool request",
}));
TerminateJobCommand works on jobs in SUBMITTED, PENDING, RUNNABLE, STARTING, or RUNNING states. The job moves to FAILED with the provided reason. Termination is not instantaneous for RUNNING jobs — the ECS task receives a SIGTERM and has 30 seconds before SIGKILL.
List jobs by status
// List all RUNNING jobs in a queue
const { jobSummaryList } = await batch.send(new ListJobsCommand({
jobQueue: queueArn,
jobStatus: "RUNNING", // SUBMITTED | PENDING | RUNNABLE | STARTING | RUNNING | SUCCEEDED | FAILED
maxResults: 100,
}));
for (const job of jobSummaryList ?? []) {
console.log(job.jobId, job.jobName, job.status, job.createdAt);
}
ListJobsCommand does not return the full job detail (logs, container exit code, etc.) — it returns a summary. Use DescribeJobsCommand with the returned jobIds when you need the full record.
CloudWatch Logs
When logConfiguration.logDriver is awslogs, each job attempt writes to a CloudWatch log stream named {prefix}/{jobId}/attempt/{attemptIndex}. Navigate to the log group defined in your job definition to find per-attempt logs.
// Retrieve CloudWatch log stream name from a completed job
const { jobs } = await batch.send(new DescribeJobsCommand({ jobs: [jobId] }));
const attempt = jobs?.[0]?.attempts?.[0];
const logStreamName = attempt?.container?.logStreamName;
// e.g. "job/ff4a3b2e-1234-5678-abcd-ef0123456789/attempt/0"
Use the CloudWatch Logs Insights console or @aws-sdk/client-cloudwatch-logs with GetLogEventsCommand to fetch the logs programmatically.
Common errors
| Error / Symptom | Root cause | Fix |
|---|---|---|
Job stuck in RUNNABLE |
CE has reached maxvCpus, or CE is DISABLED, or queue has no enabled CE |
Increase maxvCpus, enable CE, or add a second CE to the queue order |
ClientException: platformCapabilities not supported |
Job definition has platformCapabilities: ["EC2"] but queue points to Fargate CE |
Register a new job definition revision with platformCapabilities: ["FARGATE"] |
Job fails with CannotPullContainerError |
Fargate subnet has no internet access; ECR image pull fails | Add NAT gateway to subnet, or add VPC endpoints for ECR and S3 |
Job fails with ResourceInitializationError |
executionRoleArn missing ecr:GetAuthorizationToken |
Attach AmazonECSTaskExecutionRolePolicy to the execution role |
INVALID job status (never runs) |
Job definition platformCapabilities mismatch with CE type |
Check statusReason in DescribeJobs; re-register job definition with correct platform |
AccessDeniedException inside container |
jobRoleArn missing required permissions for the AWS API called |
Attach the needed policies to the job role, not to the execution role |
Related guides
- AWS Batch with Fargate: vCPU/memory combinations, spot interruption, and Fargate-specific configuration
- AWS Batch array jobs: parallel dataset processing with AWS_BATCH_JOB_ARRAY_INDEX
- AWS Batch job dependencies: fan-in, fan-out, and N:N DAG workflows
- Amazon ECS service auto-scaling for long-running MCP server processes
- Lambda provisioned concurrency for latency-sensitive MCP tools
- MCP server uptime monitoring