Guide · AWS Batch · Fargate
AWS Batch with Fargate for MCP Servers — vCPU/Memory, Spot, and Configuration Details
AWS Batch on Fargate removes the need to manage EC2 instances, AMIs, or launch templates. You define the container, the vCPU and memory requirements, and the IAM roles — Batch provisions and de-provisions Fargate tasks automatically. This guide focuses on the Fargate-specific details that differ from EC2 Batch: the enforced vCPU-to-memory pairing table, the difference between FARGATE and FARGATE_SPOT compute environments, spot interruption handling strategies, network configuration requirements, and the error messages that only appear when you get the Fargate configuration wrong. For the overview of AWS Batch concepts and SDK setup, see the AWS Batch overview guide.
TL;DR
Fargate Batch uses resourceRequirements instead of the deprecated vcpus/memory fields. Only specific vCPU/memory pairings are valid — a 0.25 vCPU job cannot request 8 GB of memory. FARGATE_SPOT is 40–70% cheaper than FARGATE but can be interrupted; handle interruptions by implementing checkpointing or using evaluateOnExit retry rules that catch Host EC2*terminated status reasons. networkConfiguration.assignPublicIp: "ENABLED" is required unless your subnets route through a NAT gateway. executionRoleArn is required for Fargate (optional for EC2 Batch).
FARGATE vs FARGATE_SPOT — which to use
When creating a Compute Environment, computeResources.type determines the pricing and interruption model:
| CE type | Pricing | Interruption | Best for |
|---|---|---|---|
FARGATE |
Standard on-demand rates ($0.04048/vCPU-hr, $0.004445/GB-hr) | Never interrupted by AWS | Jobs that cannot tolerate restart: stateful pipelines, final-stage exports, real-time triggered jobs |
FARGATE_SPOT |
40–70% discount over on-demand; varies by region and capacity pool | Can be reclaimed with 2-minute warning; container receives SIGTERM then SIGKILL | Fault-tolerant jobs: embarrassingly parallel array jobs, idempotent ETL, jobs with checkpointing |
A common pattern is to create two Compute Environments in the same Job Queue — Spot as order 1 (preferred), on-demand as order 2 (fallback). Batch fills jobs from Spot first; if Spot capacity is unavailable or the job fails due to interruption, the retry attempt may land on the on-demand CE:
// Two-CE queue: Spot first, on-demand fallback
const twoTierQueue = await batch.send(new CreateJobQueueCommand({
jobQueueName: "mcp-jobs-hybrid",
state: "ENABLED",
priority: 100,
computeEnvironmentOrder: [
{ order: 1, computeEnvironment: spotCeArn }, // Try Spot first
{ order: 2, computeEnvironment: ondemandCeArn }, // Fall back to on-demand
],
}));
Batch does not automatically migrate a running Spot task to the on-demand CE if Spot capacity is reclaimed mid-run. The job fails, and the retry starts fresh on whichever CE has capacity — which may again be Spot or may be on-demand. For jobs where you want guaranteed on-demand retries after Spot interruption, use evaluateOnExit rules (see below).
Valid Fargate vCPU and memory combinations
Fargate enforces specific vCPU-to-memory pairings. Requesting an invalid combination produces ClientException: Invalid combination of vCPU and memory for FARGATE during job registration or at submission time.
| vCPU (string value) | Valid memory values (MB) |
|---|---|
"0.25" |
512, 1024, 2048 |
"0.5" |
1024, 2048, 3072, 4096 |
"1" |
2048, 3072, 4096, 5120, 6144, 7168, 8192 |
"2" |
4096 through 16384 (in 1024 increments) |
"4" |
8192 through 30720 (in 1024 increments) |
"8" |
16384 through 61440 (in 4096 increments) |
"16" |
32768 through 122880 (in 8192 increments) |
The vCPU value is a string in resourceRequirements, not a number. Memory is also a string (MB). Both must pass the pairing table or the job definition registration fails.
// 4 vCPU, 16 GB — valid Fargate combination
containerProperties: {
resourceRequirements: [
{ type: "VCPU", value: "4" },
{ type: "MEMORY", value: "16384" }, // 16 GB in MB
],
// ...
}
If you need more than 16 vCPU or 120 GB of memory, switch to an EC2 Compute Environment. Memory-optimized EC2 instance families (r6i, r7g) support up to 384–512 GB per instance.
Registering a Fargate job definition
Fargate job definitions differ from EC2 job definitions in four mandatory ways: platformCapabilities, executionRoleArn, networkConfiguration, and resourceRequirements. All four must be present or the job will be marked INVALID when submitted to a Fargate queue.
import { RegisterJobDefinitionCommand } from "@aws-sdk/client-batch";
await batch.send(new RegisterJobDefinitionCommand({
jobDefinitionName: "mcp-etl-job",
type: "container",
// Required for Fargate
platformCapabilities: ["FARGATE"],
containerProperties: {
image: "123456789012.dkr.ecr.us-east-1.amazonaws.com/mcp-etl:latest",
// Required for Fargate (optional for EC2)
executionRoleArn: "arn:aws:iam::123456789012:role/ecsTaskExecutionRole",
// Application-level AWS access
jobRoleArn: "arn:aws:iam::123456789012:role/EtlJobRole",
// Required for Fargate — not used in EC2 job defs
networkConfiguration: {
assignPublicIp: "DISABLED", // Using NAT gateway
},
// Required for Fargate (deprecated vcpus/memory not honored)
resourceRequirements: [
{ type: "VCPU", value: "2" },
{ type: "MEMORY", value: "8192" }, // 8 GB
],
// Optional Fargate platform version
fargatePlatformConfiguration: {
platformVersion: "LATEST", // Recommended — tracks stable releases
},
logConfiguration: {
logDriver: "awslogs",
options: {
"awslogs-group": "/aws/batch/mcp-etl-job",
"awslogs-region": "us-east-1",
"awslogs-stream-prefix": "job",
},
},
},
retryStrategy: {
attempts: 3,
evaluateOnExit: [
{ onExitCode: "0", action: "EXIT" },
{ onStatusReason: "Host EC2*terminated", action: "RETRY" }, // Spot reclaim
{ onReason: "CannotPullContainer*", action: "RETRY" }, // ECR transient
],
},
timeout: { attemptDurationSeconds: 7200 }, // 2-hour per-attempt wall clock
}));
Spot interruption handling
When a FARGATE_SPOT task is reclaimed, the ECS agent sends SIGTERM to PID 1 in the container. The container has approximately 120 seconds to checkpoint state before receiving SIGKILL. The job then moves to FAILED with statusReason: "Host EC2 (ip-N-N-N-N) terminated".
Strategy 1: Idempotent jobs with retry on spot reclaim
The simplest approach: design jobs to be safe to restart from scratch, and use evaluateOnExit to auto-retry on spot reclaim:
retryStrategy: {
attempts: 5, // Allow multiple spot interruptions
evaluateOnExit: [
{ onExitCode: "0", action: "EXIT" },
{ onStatusReason: "Host EC2*terminated", action: "RETRY" },
{ onReason: "CannotPullContainer*", action: "RETRY" },
// All other failures (non-zero exit) fall through to default: FAILED after attempts exhausted
],
}
Strategy 2: Checkpoint to S3
For long jobs where restarting from scratch is too expensive, checkpoint progress to S3 periodically and resume from the last checkpoint on restart:
// In job container code — checkpoint every N items processed
async function processWithCheckpoint(items: string[]) {
const checkpointKey = `checkpoints/${process.env.AWS_BATCH_JOB_ID}.json`;
// Load checkpoint if job is a retry
let startIndex = 0;
try {
const cp = await s3.send(new GetObjectCommand({
Bucket: "my-checkpoints", Key: checkpointKey
}));
startIndex = JSON.parse(await cp.Body!.transformToString()).processedCount;
console.log(`Resuming from checkpoint: ${startIndex} items already processed`);
} catch { /* no checkpoint — fresh start */ }
for (let i = startIndex; i < items.length; i++) {
await processItem(items[i]);
// Checkpoint every 100 items
if ((i + 1) % 100 === 0) {
await s3.send(new PutObjectCommand({
Bucket: "my-checkpoints",
Key: checkpointKey,
Body: JSON.stringify({ processedCount: i + 1, updatedAt: new Date().toISOString() }),
}));
}
}
}
Strategy 3: Graceful shutdown on SIGTERM
Register a SIGTERM handler to flush in-flight work before the container is killed:
process.on("SIGTERM", async () => {
console.log("SIGTERM received — flushing checkpoint before shutdown");
await flushCheckpoint(); // Write progress to S3
await closeDbConnections(); // Release database connections
process.exit(143); // 128 + 15 (SIGTERM) — conventional exit code
});
Network configuration
Fargate Batch tasks run in your VPC and need network connectivity to pull the container image from ECR and to call AWS APIs. The two valid assignPublicIp values have different prerequisites:
| Setting | What it requires | Use when |
|---|---|---|
ENABLED |
Subnet must have an internet gateway route in its route table (public subnet) | Development, simple setups without NAT gateway |
DISABLED |
Subnet must route outbound traffic through a NAT gateway OR have VPC endpoints for ECR, S3, CloudWatch Logs, and any other AWS APIs the job calls | Production — private subnets; jobs that should not have public IPs |
The required VPC endpoints for fully private Fargate Batch (no NAT gateway):
com.amazonaws.{region}.ecr.dkr— image pull from ECR private registrycom.amazonaws.{region}.ecr.api— ECR API calls (GetAuthorizationToken)com.amazonaws.{region}.s3— Gateway endpoint (free) for ECR layer storage in S3com.amazonaws.{region}.logs— CloudWatch Logs streaming (awslogs driver)com.amazonaws.{region}.batch— Batch control plane calls- Any other service your container code calls (e.g.,
dynamodb,secretsmanager)
Missing the S3 gateway endpoint is the most common cause of CannotPullContainerError in private subnets — ECR stores image layers in S3, and the ECR interface endpoints alone are not sufficient without S3 routing.
Fargate platform version
fargatePlatformConfiguration.platformVersion controls which ECS Fargate agent version the task uses. LATEST tracks the latest stable version and is recommended unless you need to pin for compatibility:
fargatePlatformConfiguration: {
platformVersion: "LATEST", // Recommended
// platformVersion: "1.4.0", // Pin to specific version
}
Fargate 1.4.0 introduced EFS volume support in Batch tasks. If you need EFS volumes mounted in your Batch job container (for sharing data between task retries without S3), you must use platform version 1.4.0 or later — LATEST satisfies this. The volumes and mountPoints fields in the job definition container properties support EFS volumes using the same syntax as ECS task definitions.
Using EFS volumes in Fargate Batch jobs
EFS volumes allow multiple Batch job attempts to share a filesystem — useful for checkpoint files that persist across spot interruptions without going through S3:
await batch.send(new RegisterJobDefinitionCommand({
jobDefinitionName: "mcp-etl-with-efs",
type: "container",
platformCapabilities: ["FARGATE"],
containerProperties: {
image: "123456789012.dkr.ecr.us-east-1.amazonaws.com/mcp-etl:latest",
executionRoleArn: "arn:aws:iam::123456789012:role/ecsTaskExecutionRole",
jobRoleArn: "arn:aws:iam::123456789012:role/EtlJobRole",
networkConfiguration: { assignPublicIp: "DISABLED" },
fargatePlatformConfiguration: { platformVersion: "1.4.0" }, // EFS requires 1.4+
resourceRequirements: [
{ type: "VCPU", value: "1" },
{ type: "MEMORY", value: "4096" },
],
// Mount the EFS access point at /mnt/checkpoints
mountPoints: [
{ containerPath: "/mnt/checkpoints", readOnly: false, sourceVolume: "checkpoints-vol" },
],
volumes: [
{
name: "checkpoints-vol",
efsVolumeConfiguration: {
fileSystemId: "fs-0abc123",
transitEncryption: "ENABLED",
authorizationConfig: {
accessPointId: "fsap-0def456",
iam: "ENABLED",
},
},
},
],
logConfiguration: {
logDriver: "awslogs",
options: { "awslogs-group": "/aws/batch/mcp-etl-with-efs", "awslogs-region": "us-east-1", "awslogs-stream-prefix": "job" },
},
},
retryStrategy: { attempts: 5, evaluateOnExit: [
{ onExitCode: "0", action: "EXIT" },
{ onStatusReason: "Host EC2*terminated", action: "RETRY" },
]},
}));
The executionRoleArn must include elasticfilesystem:ClientMount and elasticfilesystem:ClientWrite (or attach AmazonElasticFileSystemClientFullAccess) for Fargate to mount the EFS access point.
Fargate-specific error messages
| Error / symptom | Root cause | Fix |
|---|---|---|
ClientException: Invalid combination of vCPU and memory |
vCPU/memory pairing violates the Fargate constraint table | Use a valid pairing from the table above |
ClientException: platformCapabilities not supported for FARGATE |
Included EC2-only fields (instanceType, allocationStrategy) in a Fargate CE or job def |
Remove EC2-specific fields; they are not valid in Fargate definitions |
Job status: INVALID, reason: FARGATE platform not supported |
Job definition has platformCapabilities: ["EC2"] but submitted to Fargate queue |
Register a new revision with platformCapabilities: ["FARGATE"] |
ResourceInitializationError: unable to pull secrets or registry auth |
executionRoleArn missing ecr:GetAuthorizationToken, or no ECR VPC endpoint |
Attach AmazonECSTaskExecutionRolePolicy; add ECR VPC endpoints if private subnet |
CannotPullContainerError in private subnet |
Missing S3 gateway endpoint (ECR layers are stored in S3) | Add S3 gateway endpoint to the VPC; free and required for ECR pulls without NAT |
Job stuck RUNNABLE with FARGATE_SPOT |
Spot capacity unavailable in selected AZs for the requested vCPU/memory size | Add more subnets in different AZs; add on-demand CE as fallback; reduce resource size |
fargatePlatformConfiguration not supported |
Included fargatePlatformConfiguration in an EC2 job definition |
Only include fargatePlatformConfiguration in job defs with platformCapabilities: ["FARGATE"] |
Cost example
Processing 1,000 documents per night, each taking 90 seconds at 2 vCPU / 8 GB on FARGATE_SPOT vs FARGATE on-demand (us-east-1 rates, approximate):
| FARGATE | FARGATE_SPOT (~60% discount) | |
|---|---|---|
| vCPU-hours (2 vCPU × 90s × 1000 jobs) | 50 vCPU-hr × $0.04048 = $2.02 | 50 vCPU-hr × $0.0162 ≈ $0.81 |
| GB-hours (8 GB × 90s × 1000 jobs) | 200 GB-hr × $0.004445 = $0.89 | 200 GB-hr × $0.00178 ≈ $0.36 |
| Total per nightly batch | ~$2.91 | ~$1.17 |
| Monthly (30 nights) | ~$87 | ~$35 |
Spot discount varies by region, instance family, and time of day. Check the Fargate pricing page for current rates. The savings are most significant for high-throughput array jobs running thousands of tasks per day.
Related guides
- AWS Batch overview: job definitions, compute environments, job queues, and status tracking
- 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
- EFS with Lambda: persistent filesystem for warm Lambda containers
- ECS Fargate Spot: interruption handling and spot capacity strategies
- MCP server uptime monitoring