Guide · AWS Batch · Job Dependencies

AWS Batch Job Dependencies for MCP Servers — Fan-In, Fan-Out, and DAG Workflows

AWS Batch native job dependencies allow you to build multi-stage pipelines where each job waits for one or more predecessors to succeed before starting. The dependsOn field on SubmitJobCommand accepts a list of job IDs (and optionally a dependency type for array jobs). This covers linear chains, fan-out (one job triggers many), fan-in (many jobs merge into one), and N:N array dependencies. For pipelines that require conditional branching — "if stage A fails, go to stage C instead of stage B" — combine Batch native dependencies with AWS Step Functions. This guide covers all these patterns with JavaScript SDK code examples.

TL;DR

dependsOn: [{ jobId }] makes a job wait for another to reach SUCCEEDED. A job can depend on multiple predecessors — it starts only when all of them succeed. If any predecessor fails, all dependent jobs immediately fail without running (no charge). Max dependency chain depth: 20 levels. For branching logic, use Step Functions with Batch SDK integrations. For parallel array pipelines, use dependsOn: [{ jobId: parentId, type: "N_TO_N" }] with matching array sizes.

Basic dependency: linear chain

To run job B after job A succeeds:

import { BatchClient, SubmitJobCommand } from "@aws-sdk/client-batch";

const batch = new BatchClient({ region: "us-east-1" });

// Submit A first (no dependencies)
const { jobId: jobAId } = await batch.send(new SubmitJobCommand({
  jobName: "stage-a-ingest",
  jobQueue: queueArn,
  jobDefinition: ingestJobDefArn,
}));

// Submit B — it waits for A to SUCCEED
const { jobId: jobBId } = await batch.send(new SubmitJobCommand({
  jobName: "stage-b-transform",
  jobQueue: queueArn,
  jobDefinition: transformJobDefArn,
  dependsOn: [
    { jobId: jobAId },   // B starts only after A reaches SUCCEEDED
  ],
}));

// Submit C — it waits for B
const { jobId: jobCId } = await batch.send(new SubmitJobCommand({
  jobName: "stage-c-load",
  jobQueue: queueArn,
  jobDefinition: loadJobDefArn,
  dependsOn: [
    { jobId: jobBId },
  ],
}));

console.log("Pipeline submitted:", { jobAId, jobBId, jobCId });

All three jobs can be submitted in immediate succession before any of them starts running. Batch maintains the dependency graph internally and only transitions jobs to RUNNABLE when their predecessors are satisfied.

Fan-out: one job triggers many

Fan-out runs N jobs in parallel after one job completes. All children depend on the same parent job ID:

// Submit the ingestion job
const { jobId: ingestId } = await batch.send(new SubmitJobCommand({
  jobName: "ingest",
  jobQueue: queueArn,
  jobDefinition: ingestJobDefArn,
}));

// Submit 3 parallel processing jobs, all waiting for ingest
const processingJobIds = await Promise.all(
  ["region-us", "region-eu", "region-ap"].map(region =>
    batch.send(new SubmitJobCommand({
      jobName: `process-${region}`,
      jobQueue: queueArn,
      jobDefinition: processJobDefArn,
      dependsOn: [{ jobId: ingestId }],
      containerOverrides: {
        environment: [{ name: "REGION_FILTER", value: region }],
      },
    })).then(r => r.jobId)
  )
);

console.log("Fan-out submitted:", processingJobIds);

When ingest reaches SUCCEEDED, all three process-{region} jobs simultaneously move from PENDING to RUNNABLE. If ingest fails, all three children immediately fail without running — no compute charges incurred.

Fan-in: many jobs converge into one

Fan-in starts one job only after all predecessors succeed. Add all predecessor IDs to the dependsOn array:

// Three parallel preprocessing jobs (no dependencies)
const [job1Id, job2Id, job3Id] = await Promise.all([
  batch.send(new SubmitJobCommand({
    jobName: "preprocess-chunk-1", jobQueue: queueArn, jobDefinition: preprocessDef,
    containerOverrides: { environment: [{ name: "CHUNK", value: "1" }] },
  })).then(r => r.jobId),
  batch.send(new SubmitJobCommand({
    jobName: "preprocess-chunk-2", jobQueue: queueArn, jobDefinition: preprocessDef,
    containerOverrides: { environment: [{ name: "CHUNK", value: "2" }] },
  })).then(r => r.jobId),
  batch.send(new SubmitJobCommand({
    jobName: "preprocess-chunk-3", jobQueue: queueArn, jobDefinition: preprocessDef,
    containerOverrides: { environment: [{ name: "CHUNK", value: "3" }] },
  })).then(r => r.jobId),
]);

// Fan-in: merge job waits for all three preprocessors
const { jobId: mergeId } = await batch.send(new SubmitJobCommand({
  jobName: "merge-and-index",
  jobQueue: queueArn,
  jobDefinition: mergeJobDefArn,
  dependsOn: [
    { jobId: job1Id },
    { jobId: job2Id },
    { jobId: job3Id },
  ],
}));

console.log("Fan-in submitted — merge job:", mergeId);

Maximum dependsOn array size: 20 entries per job. If you need a job to wait for more than 20 predecessors, build an intermediate aggregator job that waits for the first 20, then chain further dependencies off that aggregator.

Cascading failure behavior

When a job fails and other jobs depend on it, Batch immediately propagates FAILED status through the dependency graph:

// Detect and report cascading failures
async function monitorPipeline(jobs: { name: string; id: string }[]) {
  const jobIds = jobs.map(j => j.id);

  while (true) {
    const { jobs: descriptions } = await batch.send(
      new DescribeJobsCommand({ jobs: jobIds })
    );

    for (const desc of descriptions ?? []) {
      const def = jobs.find(j => j.id === desc.jobId);
      if (desc.status === "FAILED") {
        console.error(`${def?.name} FAILED: ${desc.statusReason}`);
        // Check if this is cascading: "Job was cancelled due to dependency failure"
        if (desc.statusReason?.includes("dependency")) {
          console.error(`  → Cascading failure from upstream job`);
        }
      }
    }

    const allTerminal = descriptions?.every(
      d => d.status === "SUCCEEDED" || d.status === "FAILED"
    );
    if (allTerminal) break;
    await new Promise(r => setTimeout(r, 15_000));
  }
}

The statusReason for a cascading-failed job is: "Job was cancelled due to a dependent job failure". This distinguishes cascading failures from independent failures in your monitoring logic.

N:N array dependencies

N:N dependencies link two array jobs of the same size: child B[i] waits for child A[i]. Each index runs as an independent mini-pipeline in parallel with the others:

// Stage 1: extract — 200 parallel children
const { jobId: extractId } = await batch.send(new SubmitJobCommand({
  jobName: "extract",
  jobQueue: queueArn,
  jobDefinition: extractJobDefArn,
  arrayProperties: { size: 200 },
}));

// Stage 2: enrich — child[i] waits for extract[i]
const { jobId: enrichId } = await batch.send(new SubmitJobCommand({
  jobName: "enrich",
  jobQueue: queueArn,
  jobDefinition: enrichJobDefArn,
  arrayProperties: { size: 200 },             // Must match extract exactly
  dependsOn: [{ jobId: extractId, type: "N_TO_N" }],
}));

// Stage 3: load — child[i] waits for enrich[i]
const { jobId: loadId } = await batch.send(new SubmitJobCommand({
  jobName: "load",
  jobQueue: queueArn,
  jobDefinition: loadJobDefArn,
  arrayProperties: { size: 200 },
  dependsOn: [{ jobId: enrichId, type: "N_TO_N" }],
}));

// Final fan-in: single consolidation job waits for the entire load array
const { jobId: consolidateId } = await batch.send(new SubmitJobCommand({
  jobName: "consolidate",
  jobQueue: queueArn,
  jobDefinition: consolidateJobDefArn,
  // No arrayProperties — this is a single job
  dependsOn: [{ jobId: loadId }],  // No type — wait for entire array parent to SUCCEED
}));

When you use dependsOn: [{ jobId: parentArrayId }] without a type, the dependent job waits for the entire array job parent to reach SUCCEEDED (all children done). This is the correct pattern for the final fan-in after an N:N chain.

Complete multi-stage ETL pipeline

A realistic 5-stage ETL pipeline for an MCP server that processes nightly data exports:

async function submitETLPipeline(runDate: string) {
  const env = (k: string, v: string) => ({ name: k, value: v });

  // Stage 1: Validate input files (single job)
  const { jobId: validateId } = await batch.send(new SubmitJobCommand({
    jobName: `validate-${runDate}`,
    jobQueue: queueArn, jobDefinition: validateDef,
    containerOverrides: { environment: [env("RUN_DATE", runDate)] },
  }));

  // Stage 2: Extract — 50 parallel shards (fan-out from validate)
  const { jobId: extractId } = await batch.send(new SubmitJobCommand({
    jobName: `extract-${runDate}`,
    jobQueue: queueArn, jobDefinition: extractDef,
    arrayProperties: { size: 50 },
    dependsOn: [{ jobId: validateId }],
    containerOverrides: { environment: [env("RUN_DATE", runDate), env("TOTAL_SHARDS", "50")] },
  }));

  // Stage 3: Transform — 50 N:N children, one per extract shard
  const { jobId: transformId } = await batch.send(new SubmitJobCommand({
    jobName: `transform-${runDate}`,
    jobQueue: queueArn, jobDefinition: transformDef,
    arrayProperties: { size: 50 },
    dependsOn: [{ jobId: extractId, type: "N_TO_N" }],
    containerOverrides: { environment: [env("RUN_DATE", runDate)] },
  }));

  // Stage 4: Load — 50 N:N children, one per transform shard
  const { jobId: loadId } = await batch.send(new SubmitJobCommand({
    jobName: `load-${runDate}`,
    jobQueue: queueArn, jobDefinition: loadDef,
    arrayProperties: { size: 50 },
    dependsOn: [{ jobId: transformId, type: "N_TO_N" }],
    containerOverrides: { environment: [env("RUN_DATE", runDate)] },
  }));

  // Stage 5: Report — single job, waits for all 50 load children
  const { jobId: reportId } = await batch.send(new SubmitJobCommand({
    jobName: `report-${runDate}`,
    jobQueue: queueArn, jobDefinition: reportDef,
    dependsOn: [{ jobId: loadId }],      // Wait for entire load array to SUCCEED
    containerOverrides: { environment: [env("RUN_DATE", runDate)] },
  }));

  console.log("ETL pipeline submitted for", runDate, {
    validateId, extractId, transformId, loadId, reportId,
  });

  return reportId;  // Monitor the terminal job
}

When to use Step Functions instead

AWS Batch native dependencies handle success-only transitions — a dependent job starts when its predecessors succeed. They cannot express:

For these patterns, use AWS Step Functions with the Batch SDK integration. Step Functions orchestrates Batch jobs using the aws-sdk:batch:submitJob optimistic integration or the .sync pattern that waits for job completion:

// Step Functions state machine definition (simplified)
{
  "Comment": "ETL with error recovery",
  "StartAt": "Validate",
  "States": {
    "Validate": {
      "Type": "Task",
      "Resource": "arn:aws:states:::batch:submitJob.sync",
      "Parameters": {
        "JobName": "validate",
        "JobQueue.$": "$.jobQueue",
        "JobDefinition": "validate-job"
      },
      "Next": "Extract",
      "Catch": [{
        "ErrorEquals": ["States.TaskFailed"],
        "Next": "ValidationFailed"       // Conditional branch on failure
      }]
    },
    "Extract": {
      "Type": "Task",
      "Resource": "arn:aws:states:::batch:submitJob.sync",
      "Parameters": { "JobName": "extract", "JobQueue.$": "$.jobQueue", "JobDefinition": "extract-job" },
      "Next": "Transform"
    },
    "ValidationFailed": {
      "Type": "Task",
      "Resource": "arn:aws:states:::sns:publish",
      "Parameters": { "TopicArn": "arn:aws:sns:us-east-1:123456789012:alerts", "Message": "Validation failed" },
      "End": true
    },
    "Transform": { "..." : "..." },
    "Load": { "..." : "..." }
  }
}

The .sync integration pattern polls the Batch job until it completes — it uses EventBridge under the hood, not SDK polling from a Lambda. This is the recommended approach for Step Functions + Batch because it does not burn Lambda invocations and supports Step Functions execution history.

Dependency limits and constraints

Constraint Value
Max dependsOn entries per job 20
Max dependency chain depth 20 levels
Dependency resolution timeout None (jobs stay PENDING indefinitely if predecessor stays RUNNING)
Cross-queue dependencies Supported — jobs in different queues can depend on each other
Cross-account dependencies Not supported — dependencies must be within the same AWS account
Dependency on a specific array child Not supported — you can depend on the array parent (waits for all children) or use N:N (child-level), but not child[3] specifically

Monitoring dependencies with EventBridge

Rather than polling DescribeJobs in a loop, subscribe to Batch state change events via EventBridge to trigger the next stage or alerting logic:

// EventBridge rule: catch SUCCEEDED on specific job names
{
  "source": ["aws.batch"],
  "detail-type": ["Batch Job State Change"],
  "detail": {
    "status": ["SUCCEEDED", "FAILED"],
    "jobName": [{ "prefix": "nightly-etl-" }]
  }
}

// Lambda handler receives event detail:
// { jobId, jobName, status, jobQueue, jobDefinition, statusReason, createdAt, startedAt, stoppedAt }

export async function handler(event: any) {
  const { jobId, jobName, status } = event.detail;
  if (status === "FAILED") {
    await notifyOncall(jobName, jobId);
  } else if (status === "SUCCEEDED" && jobName.startsWith("nightly-etl-load")) {
    // Trigger next pipeline stage via SDK
    await submitReportJob(jobId);
  }
}

Related guides