Guide · AWS Compute Optimizer · Cost Optimization

AWS Compute Optimizer for MCP Servers — Rightsize Lambda, EC2, and ECS

AWS Compute Optimizer uses machine learning to analyze 14 days of CloudWatch metrics and recommend right-sized compute configurations for Lambda functions, EC2 instances, ECS services on Fargate, Auto Scaling groups, EBS volumes, and RDS. For MCP server builders running Lambda-heavy or ECS-based architectures, Compute Optimizer answers the question "how much memory should I actually give this Lambda function?" and "is my Fargate task over-provisioned?" — without manual analysis of CloudWatch percentiles. The @aws-sdk/client-compute-optimizer package exposes the full recommendation API. This guide covers opt-in, all major resource types, finding interpretation, and building an MCP tool to surface rightsizing opportunities.

TL;DR

Compute Optimizer requires explicit opt-in via UpdateEnrollmentStatusCommand before any recommendations appear. After opt-in, wait 24–48 hours for the first analysis cycle. Query recommendations with GetLambdaFunctionRecommendationsCommand, GetEC2InstanceRecommendationsCommand, and GetECSServiceRecommendationsCommand. Each recommendation includes a Finding (OVER_PROVISIONED, UNDER_PROVISIONED, OPTIMIZED, NOT_OPTIMIZED) and a SavingsOpportunity with estimated monthly savings. The service is free for base recommendations; Enhanced Infrastructure Metrics (3 months of data, enhanced CloudWatch) requires a paid tier.

Package installation and opt-in

npm install @aws-sdk/client-compute-optimizer
import {
  ComputeOptimizerClient,
  UpdateEnrollmentStatusCommand,
  GetEnrollmentStatusCommand,
} from "@aws-sdk/client-compute-optimizer";

// Compute Optimizer is regional — use the region where your resources live
const optimizer = new ComputeOptimizerClient({ region: "us-east-1" });

Opt the account in to Compute Optimizer (must be done once per account; run this in your initialization/bootstrap code, not on every Lambda invocation):

// Check current enrollment status first
const { Status } = await optimizer.send(new GetEnrollmentStatusCommand({}));
console.log("Enrollment status:", Status); // ACTIVE, INACTIVE, PENDING, FAILED

if (Status !== "ACTIVE") {
  await optimizer.send(new UpdateEnrollmentStatusCommand({
    Status: "Active",    // "Active" = opt in, "Inactive" = opt out
    IncludeMemberAccounts: false,  // true = also opt in all org member accounts
  }));
  console.log("Opted in — first recommendations available in 24-48 hours");
}

Note: Status in the response uses uppercase ("ACTIVE"), but the UpdateEnrollmentStatus input uses title-case ("Active"). This is an SDK inconsistency — the enum values differ between input and output.

Lambda function recommendations

Compute Optimizer analyzes Lambda invocation metrics (average/max duration, memory used, cold starts) to recommend optimal memory settings. The critical insight is that Lambda bills for memory × duration in GB-seconds — an over-provisioned function may cost more per invocation even though each execution finishes faster:

import {
  ComputeOptimizerClient,
  GetLambdaFunctionRecommendationsCommand,
} from "@aws-sdk/client-compute-optimizer";

const optimizer = new ComputeOptimizerClient({ region: "us-east-1" });

// Get recommendations for all Lambda functions in the account/region
const { LambdaFunctionRecommendations, NextToken } = await optimizer.send(
  new GetLambdaFunctionRecommendationsCommand({
    MaxResults: 50,
    // FunctionArns: ["arn:aws:lambda:..."]  // optional — filter to specific functions
    // Filters: [{ name: "Finding", values: ["OVER_PROVISIONED"] }]
  })
);

for (const rec of LambdaFunctionRecommendations ?? []) {
  console.log(`\nFunction: ${rec.FunctionArn}`);
  console.log(`Finding: ${rec.Finding}`);  // OVER_PROVISIONED | UNDER_PROVISIONED | OPTIMIZED | NOT_OPTIMIZED | UNAVAILABLE
  console.log(`Current memory: ${rec.CurrentMemorySize} MB`);

  for (const opt of rec.MemorySizeRecommendationOptions ?? []) {
    const savings = opt.SavingsOpportunity;
    console.log(
      `  → ${opt.MemorySize} MB: rank=${opt.Rank} ` +
      `perf-risk=${opt.PerformanceRisk?.toFixed(2)} ` +
      `est-savings=$${savings?.EstimatedMonthlySavings?.Value?.toFixed(2)}/mo ` +
      `(${savings?.SavingsOpportunityPercentage?.toFixed(0)}%)`
    );
  }
}

Lambda Finding types

Finding What it means Action
OVER_PROVISIONED Memory allocation is higher than what the function actually used. Reducing memory would lower cost with minimal performance impact. Lower memory — cost savings likely
UNDER_PROVISIONED Function consistently uses near 100% of allocated memory, risking OOM errors or degraded performance. Increase memory — reliability improvement
OPTIMIZED Current memory is correctly sized for the workload. No action needed
NOT_OPTIMIZED Insufficient invocation data to determine optimal memory (e.g., rarely invoked function). Wait for more invocation data
UNAVAILABLE Recommendations temporarily unavailable (function just created, or analysis error). Retry in 24 hours

PerformanceRisk interpretation

Each recommendation option includes a PerformanceRisk score from 0.0 (no risk) to 4.0 (very high risk of degraded performance). Use it to avoid recommending memory reductions that might cause production issues:

// Only suggest options with low performance risk
const safeOptions = rec.MemorySizeRecommendationOptions?.filter(
  opt => (opt.PerformanceRisk ?? 4) < 1.0 && opt.MemorySize! < rec.CurrentMemorySize!
) ?? [];

EC2 instance recommendations

Compute Optimizer analyzes EC2 CPU, memory (requires CloudWatch Agent), network, and disk metrics to recommend alternative instance types:

import {
  GetEC2InstanceRecommendationsCommand,
} from "@aws-sdk/client-compute-optimizer";

const { InstanceRecommendations } = await optimizer.send(
  new GetEC2InstanceRecommendationsCommand({
    MaxResults: 50,
    // InstanceArns: ["arn:aws:ec2:..."]
    // Filters: [{ name: "Finding", values: ["OVER_PROVISIONED"] }]
  })
);

for (const rec of InstanceRecommendations ?? []) {
  console.log(`\nInstance: ${rec.InstanceName} (${rec.InstanceArn})`);
  console.log(`Current: ${rec.CurrentInstanceType} — Finding: ${rec.Finding}`);

  for (const opt of (rec.RecommendationOptions ?? []).slice(0, 3)) {
    const savings = opt.SavingsOpportunity;
    console.log(
      `  → ${opt.InstanceType}: ` +
      `perf-risk=${opt.PerformanceRisk?.toFixed(2)} ` +
      `est-savings=$${savings?.EstimatedMonthlySavings?.Value?.toFixed(2)}/mo ` +
      `(${savings?.SavingsOpportunityPercentage?.toFixed(0)}%)`
    );

    // Projected utilization at the recommended instance type
    for (const proj of opt.ProjectedUtilizationMetrics ?? []) {
      console.log(
        `    ${proj.Name} ${proj.Statistic}: ${proj.Value?.toFixed(1)}%`
      );
    }
  }
}

EC2 recommendations include up to three alternative instance types sorted by rank (1 = best balance of performance and savings). Each option shows projected CPU/memory/network utilization at the recommended type, letting you validate the recommendation before applying it.

EC2 Finding types

Finding What it means
OVER_PROVISIONED At least one resource (CPU, memory, network, disk) is significantly under-utilized — downsizing recommended
UNDER_PROVISIONED At least one resource is consistently near-saturated — upsizing recommended for reliability
OPTIMIZED All resources are sized appropriately for the observed workload
NOT_OPTIMIZED Insufficient metrics to determine (memory metrics require CloudWatch Agent with mem_used_percent metric)

ECS service recommendations (Fargate)

For ECS services on Fargate, Compute Optimizer recommends optimal CPU and memory sizes for task definitions:

import {
  GetECSServiceRecommendationsCommand,
} from "@aws-sdk/client-compute-optimizer";

const { EcsServiceRecommendations } = await optimizer.send(
  new GetECSServiceRecommendationsCommand({
    MaxResults: 50,
    // ServiceArns: ["arn:aws:ecs:..."]
    // Filters: [{ name: "Finding", values: ["OVER_PROVISIONED"] }]
  })
);

for (const rec of EcsServiceRecommendations ?? []) {
  console.log(`\nService: ${rec.ServiceArn}`);
  console.log(
    `Current: ${rec.CurrentServiceConfiguration?.Cpu} CPU units / ` +
    `${rec.CurrentServiceConfiguration?.Memory} MB memory`
  );
  console.log(`Finding: ${rec.Finding}`);

  for (const opt of rec.ServiceRecommendationOptions ?? []) {
    const cfg     = opt.ContainerRecommendations?.[0];
    const savings = opt.SavingsOpportunity;
    console.log(
      `  → cpu=${cfg?.Cpu} mem=${cfg?.Memory} MB: ` +
      `perf-risk=${opt.PerformanceRisk?.toFixed(2)} ` +
      `est-savings=$${savings?.EstimatedMonthlySavings?.Value?.toFixed(2)}/mo`
    );
  }
}

ECS recommendations are only available for Fargate launch type services. EC2 launch type ECS tasks are covered indirectly through EC2 instance recommendations. ECS recommendations analyze CpuUtilized and MemoryUtilized CloudWatch Container Insights metrics — Container Insights must be enabled on the cluster or no ECS recommendations will be generated.

Filtering recommendations

All Get*Recommendations commands accept a Filters array to narrow results:

// Only return Lambda functions that are over-provisioned
const { LambdaFunctionRecommendations } = await optimizer.send(
  new GetLambdaFunctionRecommendationsCommand({
    Filters: [
      {
        name: "Finding",
        values: ["OVER_PROVISIONED"],
      },
    ],
  })
);

// Only return EC2 instances with low performance risk recommendations
const { InstanceRecommendations } = await optimizer.send(
  new GetEC2InstanceRecommendationsCommand({
    Filters: [
      { name: "Finding", values: ["OVER_PROVISIONED"] },
      { name: "RecommendationSourceType", values: ["Ec2Instance"] },
    ],
  })
);

Complete MCP tool: rightsizing report

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import {
  ComputeOptimizerClient,
  GetLambdaFunctionRecommendationsCommand,
  GetEC2InstanceRecommendationsCommand,
} from "@aws-sdk/client-compute-optimizer";
import { z } from "zod";

const optimizer = new ComputeOptimizerClient({ region: "us-east-1" });
const server = new McpServer({ name: "compute-optimizer-tool", version: "1.0.0" });

server.tool(
  "get_rightsizing_report",
  "Return AWS Compute Optimizer recommendations for over-provisioned Lambda functions and EC2 instances, sorted by estimated monthly savings",
  {
    min_savings_usd: z.number().min(0).default(5)
      .describe("Only include recommendations with estimated savings above this monthly amount"),
    max_perf_risk: z.number().min(0).max(4).default(1)
      .describe("Only include options with performance risk below this value (0=none, 4=very high)"),
  },
  async ({ min_savings_usd, max_perf_risk }) => {
    const lines: string[] = [];
    let totalSavings = 0;

    // Lambda recommendations
    try {
      const { LambdaFunctionRecommendations } = await optimizer.send(
        new GetLambdaFunctionRecommendationsCommand({
          MaxResults: 50,
          Filters: [{ name: "Finding", values: ["OVER_PROVISIONED"] }],
        })
      );

      for (const rec of LambdaFunctionRecommendations ?? []) {
        const fnName = rec.FunctionArn?.split(":").slice(-1)[0] ?? rec.FunctionArn;
        const bestOpt = rec.MemorySizeRecommendationOptions
          ?.filter(o =>
            (o.PerformanceRisk ?? 4) <= max_perf_risk &&
            o.MemorySize! < rec.CurrentMemorySize!
          )
          .sort((a, b) =>
            (b.SavingsOpportunity?.EstimatedMonthlySavings?.Value ?? 0) -
            (a.SavingsOpportunity?.EstimatedMonthlySavings?.Value ?? 0)
          )[0];

        if (!bestOpt) continue;
        const savings = bestOpt.SavingsOpportunity?.EstimatedMonthlySavings?.Value ?? 0;
        if (savings < min_savings_usd) continue;

        totalSavings += savings;
        lines.push(
          `Lambda: ${fnName}\n` +
          `  Current: ${rec.CurrentMemorySize} MB → Recommended: ${bestOpt.MemorySize} MB\n` +
          `  Savings: ~$${savings.toFixed(2)}/mo | Perf risk: ${bestOpt.PerformanceRisk?.toFixed(2)}`
        );
      }
    } catch (e: any) {
      lines.push(`Lambda recommendations unavailable: ${e.message}`);
    }

    // EC2 recommendations
    try {
      const { InstanceRecommendations } = await optimizer.send(
        new GetEC2InstanceRecommendationsCommand({
          MaxResults: 50,
          Filters: [{ name: "Finding", values: ["OVER_PROVISIONED"] }],
        })
      );

      for (const rec of InstanceRecommendations ?? []) {
        const bestOpt = rec.RecommendationOptions
          ?.filter(o => (o.PerformanceRisk ?? 4) <= max_perf_risk)
          .sort((a, b) =>
            (b.SavingsOpportunity?.EstimatedMonthlySavings?.Value ?? 0) -
            (a.SavingsOpportunity?.EstimatedMonthlySavings?.Value ?? 0)
          )[0];

        if (!bestOpt) continue;
        const savings = bestOpt.SavingsOpportunity?.EstimatedMonthlySavings?.Value ?? 0;
        if (savings < min_savings_usd) continue;

        totalSavings += savings;
        lines.push(
          `EC2: ${rec.InstanceName ?? rec.InstanceArn}\n` +
          `  Current: ${rec.CurrentInstanceType} → Recommended: ${bestOpt.InstanceType}\n` +
          `  Savings: ~$${savings.toFixed(2)}/mo | Perf risk: ${bestOpt.PerformanceRisk?.toFixed(2)}`
        );
      }
    } catch (e: any) {
      lines.push(`EC2 recommendations unavailable: ${e.message}`);
    }

    if (lines.length === 0) {
      return {
        content: [{
          type: "text",
          text: `No over-provisioned resources found with savings ≥ $${min_savings_usd}/mo and perf risk ≤ ${max_perf_risk}.`,
        }],
      };
    }

    return {
      content: [{
        type: "text",
        text: [
          `Rightsizing opportunities (${lines.length} resources):`,
          `Estimated total savings: ~$${totalSavings.toFixed(2)}/month`,
          "",
          lines.join("\n\n"),
        ].join("\n"),
      }],
    };
  }
);

IAM permissions

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "compute-optimizer:GetEnrollmentStatus",
        "compute-optimizer:UpdateEnrollmentStatus",
        "compute-optimizer:GetLambdaFunctionRecommendations",
        "compute-optimizer:GetEC2InstanceRecommendations",
        "compute-optimizer:GetECSServiceRecommendations",
        "compute-optimizer:GetAutoScalingGroupRecommendations",
        "compute-optimizer:GetEBSVolumeRecommendations",
        "compute-optimizer:GetRecommendationSummaries"
      ],
      "Resource": "*"
    }
  ]
}

ECS recommendations additionally require ecs:ListClusters, ecs:ListServices, and cloudwatch:GetMetricData for the Container Insights metrics lookup. Compute Optimizer reads CloudWatch data on your behalf once enrolled — it does not require direct CloudWatch access in the MCP server's IAM role unless you are building custom metric collection.

Enhanced Infrastructure Metrics

The free tier of Compute Optimizer uses 14 days of CloudWatch metric history for analysis. The paid Enhanced Infrastructure Metrics tier extends this to 3 months, which improves accuracy for workloads with weekly or monthly patterns (batch jobs, end-of-month reports, weekly builds). Enable it per resource type:

import { PutRecommendationPreferencesCommand } from "@aws-sdk/client-compute-optimizer";

// Enable enhanced metrics for all Lambda functions in this account+region
await optimizer.send(new PutRecommendationPreferencesCommand({
  ResourceType: "LambdaFunction",
  Scope: { name: "AccountId", value: "123456789012" },
  EnhancedInfrastructureMetrics: "Active",   // "Active" or "Inactive"
}));

Enhanced Infrastructure Metrics cost approximately $0.0010 per resource per month. For accounts with hundreds of Lambda functions, this adds up — enable it selectively on production functions or high-spend resources only.

Key limits and constraints

Constraint Details
Minimum invocation data for Lambda At least 50 invocations in 14 days — functions with fewer invocations return NOT_OPTIMIZED
EC2 memory metrics CloudWatch Agent with mem_used_percent metric required for memory-based recommendations; without it, only CPU-based recommendations are generated
ECS Container Insights Must be enabled at the cluster level (containerInsights: "enabled" in cluster settings) for ECS service recommendations
Analysis delay 24–48 hours after enrollment before first recommendations; re-analysis every 24 hours thereafter
Supported EC2 types Recommendations generated for instances in running state only; stopped instances, spot instances, and instances in Auto Scaling groups use the ASG recommendation API instead
Pagination All Get*Recommendations commands return max 1000 results per page; use NextToken for pagination

Common errors

Error Cause and fix
OptInRequiredException Account is not enrolled in Compute Optimizer. Call UpdateEnrollmentStatusCommand({ Status: "Active" }) first.
AccessDeniedException Missing compute-optimizer: IAM permissions. Also check that the execution role has the managed policy ComputeOptimizerReadOnlyAccess or equivalent.
InvalidParameterValueException Filter values array contains an invalid finding type or the resource type does not support the requested filter. Check the allowed values for the specific filter name.
Empty recommendations Enrollment is active but no recommendations yet — wait 24–48 hours for the first analysis cycle. Check GetRecommendationSummariesCommand to see when the last analysis ran.