AWS Cloud Map · MCP Server Service Discovery & ECS Integration · 2026-11-21 · Cloud Map arc

AWS Cloud Map for MCP Server Microservices: Service Discovery, ECS Integration, and Eight Gotchas That Silently Break Your Deployment

MCP servers running as ECS microservices need service discovery: they must find each other without hardcoded IP addresses, they need to remove themselves from client routing before graceful shutdown, and they need to register custom metadata (tool capabilities, protocol version, deployment color) so that callers can route to the right instance for the right job. AWS Cloud Map is the managed service registry that handles all of this — but its defaults are tuned for REST APIs, not for the long-lived SSE connections and careful drain sequences that MCP servers require. This guide synthesises the full Cloud Map arc for MCP server developers: the three namespace types and when each is the right choice, the GetOperation polling pattern required for async namespace creation, the RegisterInstance attribute requirements that differ by DNS record type, the ECS serviceRegistries integration and the ARN vs ID confusion that breaks it, the healthCheckGracePeriodSeconds calculation that prevents endless task-restart cycles, the DiscoverInstances HealthStatus default that routes traffic to unhealthy instances, the QueryParameters exact-match constraint that dictates how you must design your capability attributes, and the graceful shutdown sequence that prevents active SSE sessions from being abruptly terminated during scale-in.

Why MCP servers need service discovery that REST APIs don't

A REST API can tolerate a simple ALB that round-robins new requests across any healthy instance. If an instance disappears mid-request, the client retries. No session state is lost. The reconnect is invisible to the user.

MCP servers using the SSE transport cannot tolerate this model. An SSE connection is a long-lived HTTP stream — the client and server negotiate the session, exchange capability handshakes, and then hold the connection open for the duration of the interaction. When a load balancer routes an existing SSE session to a new backend instance (because the original instance stopped or was replaced during a deployment), the session is broken. The client must reconnect, re-negotiate capabilities, and may lose in-flight tool call results. For user-facing MCP applications, this is a visible failure.

AWS Cloud Map provides the primitives to build a deployment model that avoids this failure mode. It gives each MCP server instance a stable DNS record and a health status entry. When an instance is about to stop, it marks itself UNHEALTHY in Cloud Map before initiating shutdown — causing DNS to stop routing new connections to it — then waits for existing SSE sessions to drain, then deregisters. The result is a graceful drain that the ALB alone cannot provide, because the ALB routes by connection (which is active), not by session (which should finish).

Cloud Map also solves the multi-instance coordination problem beyond health management. Each registered instance can carry arbitrary key-value attributes: the MCP protocol version it supports, the tool categories it handles, its deployment color (blue/green), and its model backend region. Callers — whether other MCP server microservices or a gateway service — can use DiscoverInstances with custom attribute filters to find exactly the right instance type, not just any available instance.

Gotcha #1: The IAM namespace is servicediscovery:*, not cloudmap:*

Before writing any Cloud Map code, correct this IAM configuration error that every new Cloud Map user makes. The service's IAM action prefix is servicediscovery — not cloudmap.

AWS renamed the service from "Route 53 Auto Naming" to "AWS Cloud Map" in 2018, but the IAM action namespace was never updated. The correct IAM policy looks like this:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "CloudMapControl",
      "Effect": "Allow",
      "Action": [
        "servicediscovery:CreatePrivateDnsNamespace",
        "servicediscovery:CreateHttpNamespace",
        "servicediscovery:CreateService",
        "servicediscovery:GetOperation",
        "servicediscovery:ListNamespaces",
        "servicediscovery:ListServices",
        "servicediscovery:GetNamespace",
        "servicediscovery:GetService"
      ],
      "Resource": "*"
    },
    {
      "Sid": "CloudMapRuntime",
      "Effect": "Allow",
      "Action": [
        "servicediscovery:RegisterInstance",
        "servicediscovery:DeregisterInstance",
        "servicediscovery:ListInstances",
        "servicediscovery:GetInstancesHealthStatus",
        "servicediscovery:UpdateInstanceCustomHealthStatus",
        "servicediscovery:DiscoverInstances",
        "servicediscovery:DiscoverInstancesRevision"
      ],
      "Resource": "*"
    },
    {
      "Sid": "Route53ForPrivateDns",
      "Effect": "Allow",
      "Action": [
        "route53:CreateHostedZone",
        "route53:DeleteHostedZone",
        "route53:ChangeResourceRecordSets",
        "route53:GetHostedZone"
      ],
      "Resource": "*"
    },
    {
      "Sid": "EC2ForVPCAssociation",
      "Effect": "Allow",
      "Action": [
        "ec2:DescribeVpcs",
        "ec2:DescribeSubnets"
      ],
      "Resource": "*"
    }
  ]
}

The route53:* and ec2:Describe* permissions are needed only on the principal that creates and deletes namespaces — the provisioning role in your IaC pipeline. ECS task roles that only call RegisterInstance, DeregisterInstance, and DiscoverInstances need only the runtime statement. ECS handles auto-registration via its own service-linked role when you configure serviceRegistries, so your task role only needs the runtime actions if your application code calls Cloud Map directly.

If you see AccessDeniedException: User is not authorized to perform: cloudmap:CreateNamespace in your logs — that error message itself is wrong (it should say servicediscovery:CreateNamespace). The underlying problem is that someone wrote a policy with cloudmap:* instead of servicediscovery:*.

Choosing the right namespace type for MCP server microservices

Cloud Map offers three namespace types. The correct choice depends on whether you need DNS-based discovery, the operational simplicity tradeoff, and your budget for Route 53 hosted zone charges.

Namespace type Creation Discovery mechanism Cost MCP server use case
CreatePrivateDnsNamespace Async — poll GetOperation DNS A/CNAME/SRV records within the VPC + DiscoverInstances API $1.00/namespace/month + $0.50/Route 53 zone/month ECS Fargate fleets where microservices use DNS resolution to locate each other without SDK calls
CreateHttpNamespace Synchronous (effectively) DiscoverInstances API only — no DNS records created $1.00/namespace/month (no Route 53 charge) Architectures where the caller already calls DiscoverInstances and doesn't need DNS; cheapest option
CreatePublicDnsNamespace Async — poll GetOperation Public DNS + DiscoverInstances API $1.00/namespace/month + $0.50/Route 53 zone/month Publicly accessible MCP server endpoints — rarely appropriate; ALB at the public boundary is safer

For most MCP server deployments on ECS Fargate, private DNS namespace is the right choice: it gives you both DNS-based discovery (simple mcp-server.mcp.internal hostnames that other microservices can resolve without SDK calls) and DiscoverInstances API access with custom attribute filtering. The extra $0.50/month for the Route 53 hosted zone is negligible compared to the operational simplicity.

Use an HTTP namespace when you have a programmatic discovery layer (a gateway or proxy service) that always calls DiscoverInstances and you want to avoid the Route 53 dependency and its async creation lifecycle.

Gotcha #2: Private DNS namespace creation is asynchronous — always poll GetOperation

Unlike most AWS create-resource APIs that return the created resource in the response, CreatePrivateDnsNamespaceCommand returns an OperationId immediately — before the Route 53 hosted zone has been provisioned. If you proceed to create a service or register instances without waiting for the namespace to be READY, you get a NamespaceNotFound error that is confusing because you just created it.

import {
  ServiceDiscoveryClient,
  CreatePrivateDnsNamespaceCommand,
  GetOperationCommand,
  CreateServiceCommand,
} from "@aws-sdk/client-servicediscovery";

const cloudMap = new ServiceDiscoveryClient({ region: process.env.AWS_REGION! });

async function createMcpNamespace(vpcId: string): Promise<string> {
  const { OperationId } = await cloudMap.send(
    new CreatePrivateDnsNamespaceCommand({
      Name: "mcp.internal",
      Vpc: vpcId,
      // CreatorRequestId is an idempotency key — deterministic value only
      // Using a random UUID here would create duplicate namespaces on retry
      CreatorRequestId: "mcp-internal-ns-v1",
      Description: "MCP server microservices — private DNS",
    })
  );

  // Must poll until SUCCESS before creating services or registering instances
  const namespaceId = await pollUntilDone(OperationId!);
  console.log("Namespace ready:", namespaceId);
  return namespaceId;
}

async function pollUntilDone(
  operationId: string,
  maxWaitMs = 120_000
): Promise<string> {
  const deadline = Date.now() + maxWaitMs;
  let delay = 2_000;

  while (Date.now() < deadline) {
    await new Promise((r) => setTimeout(r, delay));
    delay = Math.min(delay * 1.5, 10_000); // exponential back-off, cap at 10s

    const { Operation } = await cloudMap.send(
      new GetOperationCommand({ OperationId: operationId })
    );

    switch (Operation?.Status) {
      case "SUCCESS":
        return Operation.Targets?.["NAMESPACE"] ?? "";
      case "FAIL":
        throw new Error(`Cloud Map operation failed: ${Operation.ErrorMessage}`);
      // "SUBMITTED" and "PENDING" — keep polling
    }
  }
  throw new Error(`Operation ${operationId} timed out after ${maxWaitMs}ms`);
}

Namespace creation takes between 10 and 30 seconds in practice. The exponential back-off in the polling loop is important: hammering GetOperation every 100ms during the Route 53 provisioning window generates unnecessary API calls and can hit Cloud Map's control-plane rate limits in accounts with heavy parallel provisioning.

HTTP namespaces, by contrast, complete synchronously. CreateHttpNamespaceCommand still returns an OperationId for API consistency, but the resource is usable almost immediately. You can poll the OperationId once to confirm and retrieve the namespace ID, but you don't need the multi-second polling loop.

Gotcha #3: InstanceId must be stable — never use a random UUID

The InstanceId in RegisterInstance is Cloud Map's idempotency key for a specific endpoint. If you call RegisterInstance twice with the same InstanceId and Attributes, the second call is a no-op. If you call it with the same InstanceId and different Attributes, the second call atomically replaces all attributes. This behavior is intentional and useful — but only if you use a stable, deterministic InstanceId.

Using a random UUID as the instance ID, which is a natural impulse, creates a silent correctness problem: when a Lambda that calls RegisterInstance times out and retries, each retry generates a new UUID and creates a new independent registration. The service registry fills with phantom instances — IPs that may no longer be active — and DiscoverInstances returns them alongside healthy instances until someone manually runs cleanup.

Use a stable identifier that is unique within the service and tied to the lifecycle of the resource:

// Get ECS task metadata — the task ARN is the right InstanceId for ECS Fargate
async function getEcsTaskArn(): Promise<string> {
  const metadataUri = process.env.ECS_CONTAINER_METADATA_URI_V4;
  if (!metadataUri) throw new Error("Not running in ECS");

  const response = await fetch(`${metadataUri}/task`);
  const metadata = await response.json();
  return metadata.TaskARN as string;
  // "arn:aws:ecs:us-east-1:123456789012:task/cluster-name/TASK_ID"
}

// Register at MCP server startup
const instanceId = await getEcsTaskArn();
await cloudMap.send(
  new RegisterInstanceCommand({
    ServiceId: serviceId,
    InstanceId: instanceId,          // stable — same value on retry
    CreatorRequestId: `register-${serviceId}-${instanceId}`, // idempotent
    Attributes: {
      AWS_INSTANCE_IPV4: privateIp,  // task ENI IP
      AWS_INSTANCE_PORT: "3000",
      MCP_PROTOCOL_VERSION: "2024-11-05",
      APP_VERSION: process.env.APP_VERSION ?? "unknown",
    },
  })
);

InstanceId uniqueness is scoped to the service, not globally. Two different services can have instances with the same InstanceId (e.g., both using the same ECS task ARN if the task registers in both services). The scope is per-service, not per-namespace or per-account.

Registering instances: required attributes by DNS record type

The Attributes map passed to RegisterInstance must contain specific reserved keys that match the DNS record type configured in the parent service's DnsConfig. Missing a required attribute returns an InvalidInput error immediately at registration time — it does not silently register without the DNS record:

DNS record type Required attributes Notes for MCP servers
A (most common) AWS_INSTANCE_IPV4 Also set AWS_INSTANCE_PORT so callers can build host:port without out-of-band config
CNAME AWS_INSTANCE_CNAME Use when registering an ALB DNS name in Cloud Map rather than instance IPs
SRV AWS_INSTANCE_IPV4 + AWS_INSTANCE_PORT Both IP and port are required; port is embedded in the DNS record
HTTP namespace (no DNS) None required Convention: include IP and port for consistent DiscoverInstances response shape

When you call RegisterInstance again with the same InstanceId and new attributes, the update is atomic and complete — it replaces all attributes, not just the ones you specified. If your update omits AWS_INSTANCE_IPV4, the IP is deleted and DNS breaks. Always re-include the routing attributes when updating other metadata:

// Hot-reload capability flags without changing routing attributes
async function updateCapabilityFlags(
  serviceId: string,
  instanceId: string,
  currentIp: string,
  flags: Record<string, string>
): Promise<void> {
  // Always re-include required routing attrs in updates — attribute update is a full replacement
  await cloudMap.send(
    new RegisterInstanceCommand({
      ServiceId: serviceId,
      InstanceId: instanceId,
      Attributes: {
        AWS_INSTANCE_IPV4: currentIp,  // must re-include or IP is deleted
        AWS_INSTANCE_PORT: "3000",
        ...flags,
      },
    })
  );
}

Gotcha #4: ECS serviceRegistries uses service ARN, not service ID

When configuring the ECS service to auto-register Cloud Map instances, the serviceRegistries field requires the Cloud Map service's ARN — not its ID. This is a confusing inconsistency in the AWS SDK: most Cloud Map API calls that modify a service (like DeleteService or UpdateService) take a service ID like srv-xxxxxxxx, but the ECS serviceRegistries.registryArn field requires the full ARN format: arn:aws:servicediscovery:REGION:ACCOUNT:service/srv-XXXXXXXX.

Passing a service ID in the ARN field results in an InvalidParameterException at ECS service creation time with a message like "Invalid parameter: serviceRegistry.registryArn" — which does not mention the ARN vs ID confusion.

import { ECSClient, CreateServiceCommand } from "@aws-sdk/client-ecs";
import { ServiceDiscoveryClient, CreateServiceCommand as CloudMapCreateService, GetServiceCommand } from "@aws-sdk/client-servicediscovery";

// Step 1: Create Cloud Map service, capture the ARN (not the ID)
const cloudMap = new ServiceDiscoveryClient({ region: "us-east-1" });
const { Service } = await cloudMap.send(
  new CloudMapCreateService({
    Name: "mcp-server",
    NamespaceId: namespaceId,
    CreatorRequestId: "mcp-server-service-v1",
    DnsConfig: {
      NamespaceId: namespaceId,
      RoutingPolicy: "MULTIVALUE",
      DnsRecords: [{ Type: "A", TTL: 30 }],
    },
    HealthCheckCustomConfig: { FailureThreshold: 1 },
  })
);

const cloudMapServiceArn = Service!.Arn!;  // arn:aws:servicediscovery:...
// NOT: Service!.Id!  — which is srv-XXXXXXXX format

// Step 2: Reference the ARN in ECS service creation
const ecs = new ECSClient({ region: "us-east-1" });
await ecs.send(
  new CreateServiceCommand({
    cluster: clusterArn,
    serviceName: "mcp-server",
    taskDefinition: taskDefinitionArn,
    desiredCount: 2,
    launchType: "FARGATE",
    serviceRegistries: [
      {
        registryArn: cloudMapServiceArn,  // ARN — not the service ID
        containerName: "mcp-server",      // must match containerDefinitions[].name
        containerPort: 3000,              // must match portMappings[].containerPort
      },
    ],
    networkConfiguration: {
      awsvpcConfiguration: {
        subnets: subnetIds,
        securityGroups: securityGroupIds,
        assignPublicIp: "DISABLED",
      },
    },
    healthCheckGracePeriodSeconds: 180, // see Gotcha #5 below
  })
);

When serviceRegistries is configured, ECS's service scheduler takes full responsibility for the Cloud Map lifecycle. At task start, ECS calls RegisterInstance using the task ENI's private IP as AWS_INSTANCE_IPV4 and the mapped container port as AWS_INSTANCE_PORT. At task stop — whether from a scale-in event, deployment, or unexpected failure — ECS calls DeregisterInstance and waits for the DNS change to propagate before allowing the task to terminate.

This ECS-managed lifecycle is more reliable than calling the Cloud Map SDK from your application code: ECS handles race conditions, retries on Cloud Map API failures, and cleanup even when tasks are OOM-killed without running shutdown hooks. Use application-level Cloud Map calls only for the custom health status update pattern or for manual registration outside of ECS.

Gotcha #5: healthCheckGracePeriodSeconds is not what you think it is

The ECS service's healthCheckGracePeriodSeconds and the container's healthCheck.startPeriod are different parameters that many teams confuse — and misconfiguring either one causes a maddening symptom: ECS tasks start successfully, pass their container health check, and are then replaced by ECS in an endless loop.

Here is the distinction:

The correct formula for healthCheckGracePeriodSeconds when using Cloud Map integration is:

// healthCheckGracePeriodSeconds = startPeriod + (interval × retries) + buffer
//
// For an MCP server with these container health check settings:
//   startPeriod: 60 seconds (time to initialize, connect to database, load schemas)
//   interval: 30 seconds (time between health check attempts)
//   retries: 3 (consecutive failures before marking unhealthy)
//
// worst-case health check time = 60 + (30 × 3) = 150 seconds
// add 30 seconds network/registration buffer
//
// healthCheckGracePeriodSeconds = 180

const ecsServiceConfig = {
  healthCheckGracePeriodSeconds: 180,
  // ...
};

The failure mode when healthCheckGracePeriodSeconds is too short:

  1. ECS launches a new task. The task starts and enters RUNNING.
  2. ECS calls RegisterInstance in Cloud Map. The instance status is initially UNKNOWN (because HealthCheckCustomConfig means the status starts unknown until UpdateInstanceCustomHealthStatus is called).
  3. The grace period expires before the container health check passes and ECS calls UpdateInstanceCustomHealthStatus(HEALTHY).
  4. ECS evaluates the Cloud Map status as UNKNOWN/UNHEALTHY and decides the task is unhealthy.
  5. ECS replaces the task. Go to step 1. Infinite loop.

The symptom appears in the ECS service events as repeated "service mcp-server has started X tasks that are unhealthy" messages, even though the tasks themselves are starting correctly. The ECS console shows no container errors.

Gotcha #6: DiscoverInstances default HealthStatus is "ALL", not "HEALTHY"

The DiscoverInstances API's HealthStatus parameter defaults to "ALL" when omitted. "ALL" includes instances with HEALTHY, UNHEALTHY, and UNKNOWN status. For a production MCP server client, this means the client may receive connection information for instances that are stopping, have failed their health check, or were registered but never had their health status initialized.

Always specify HealthStatus: "HEALTHY" explicitly in every production DiscoverInstances call:

// WRONG: returns UNHEALTHY and UNKNOWN instances too
const { Instances: badInstances } = await cloudMap.send(
  new DiscoverInstancesCommand({
    NamespaceName: "mcp.internal",
    ServiceName: "mcp-server",
    // HealthStatus omitted — defaults to "ALL" — includes degraded instances
  })
);

// CORRECT: returns only HEALTHY instances
const { Instances } = await cloudMap.send(
  new DiscoverInstancesCommand({
    NamespaceName: "mcp.internal",
    ServiceName: "mcp-server",
    HealthStatus: "HEALTHY",  // explicit — never rely on default
    MaxResults: 100,
  })
);

Cloud Map supports four HealthStatus values:

Value Returns Use for
"HEALTHY" Instances with HEALTHY status only Standard production routing — never routes to degraded instances
"UNHEALTHY" Instances with UNHEALTHY status only Debugging: find which instances are currently failing
"ALL" HEALTHY + UNHEALTHY + UNKNOWN Default if omitted — do not use in production routing
"HEALTHY_OR_ELSE_ALL" HEALTHY if any exist; otherwise ALL Fault-tolerant monitoring agents: routes to any instance during total outage to still attempt diagnosis

The "HEALTHY_OR_ELSE_ALL" option is useful for AliveMCP-style health monitoring agents: if all MCP server instances are UNHEALTHY, the monitor still needs to attempt connections to report on what it finds. Using "HEALTHY" in that case would return an empty list, preventing diagnosis.

Gotcha #7: QueryParameters is exact-match only — design attributes accordingly

The QueryParameters field in DiscoverInstances allows filtering on custom instance attributes — but it uses exact string matching only. There is no contains, prefix, suffix, or regex matching. This constraint dictates how you must design your MCP server's attribute schema.

The common mistake is storing compound values:

// BAD attribute design — cannot filter on individual tools
Attributes: {
  AWS_INSTANCE_IPV4: privateIp,
  TOOLS_AVAILABLE: "web-search,code-execution,file-system", // compound value
}

// This will NOT work:
QueryParameters: { TOOLS_AVAILABLE: "code-execution" }
// Returns 0 instances — because "code-execution" !== "web-search,code-execution,file-system"

The correct design stores one boolean attribute per dimension you want to filter on independently:

// GOOD attribute design — one boolean flag per capability
Attributes: {
  AWS_INSTANCE_IPV4: privateIp,
  AWS_INSTANCE_PORT: "3000",

  // One boolean per tool capability — exact-match filter works
  TOOL_WEB_SEARCH: "true",
  TOOL_CODE_EXECUTION: "true",
  TOOL_FILE_SYSTEM: "true",

  // Deployment routing attributes
  DEPLOY_COLOR: "blue",           // exact: "blue" | "green"
  MCP_PROTOCOL_VERSION: "2024-11-05",  // exact: pick a canonical set of versions
  REGION: "us-east-1",           // exact: standard AWS region name
}

// Now this works correctly:
QueryParameters: {
  TOOL_CODE_EXECUTION: "true",  // exact match — returns all instances with this tool
  DEPLOY_COLOR: "green",        // AND semantics — both conditions must match
}

When no instances match the QueryParameters filter, DiscoverInstances returns an empty array — not an error. Always handle the empty-result case with a fallback:

// Try to find instances with the preferred attributes; fall back to any healthy instance
async function discoverWithFallback(
  namespaceName: string,
  serviceName: string,
  preferredAttributes: Record<string, string>
): Promise<HttpInstanceSummary[]> {
  // Preferred: filtered by capability + deployment color
  const { Instances: preferred } = await cloudMap.send(
    new DiscoverInstancesCommand({
      NamespaceName: namespaceName,
      ServiceName: serviceName,
      HealthStatus: "HEALTHY",
      QueryParameters: preferredAttributes,
    })
  );

  if (preferred && preferred.length > 0) {
    return preferred;
  }

  // Fallback: any healthy instance
  const { Instances: fallback } = await cloudMap.send(
    new DiscoverInstancesCommand({
      NamespaceName: namespaceName,
      ServiceName: serviceName,
      HealthStatus: "HEALTHY",
    })
  );

  return fallback ?? [];
}

Using DiscoverInstancesRevision for change-detection without polling overhead

MCP server clients that maintain a local instance pool need to keep the pool current as instances come and go during deployments. Polling DiscoverInstances every 10 seconds works but generates constant API calls regardless of whether anything changed.

DiscoverInstancesRevisionCommand provides a lightweight alternative: it returns only a revision counter, not the full instance payload. If the revision counter is the same as your last-known revision, nothing has changed and you can skip the full DiscoverInstances call:

import {
  DiscoverInstancesCommand,
  DiscoverInstancesRevisionCommand,
  type HttpInstanceSummary,
} from "@aws-sdk/client-servicediscovery";

class McpServerPool {
  private instances: HttpInstanceSummary[] = [];
  private lastRevision: bigint = 0n;
  private roundRobinIndex = 0;

  async refresh(): Promise<void> {
    const { Revision } = await cloudMap.send(
      new DiscoverInstancesRevisionCommand({
        NamespaceName: "mcp.internal",
        ServiceName: "mcp-server",
      })
    );

    const currentRevision = BigInt(Revision ?? 0);

    if (currentRevision === this.lastRevision && this.instances.length > 0) {
      return; // no change — skip the full DiscoverInstances call
    }

    const { Instances } = await cloudMap.send(
      new DiscoverInstancesCommand({
        NamespaceName: "mcp.internal",
        ServiceName: "mcp-server",
        HealthStatus: "HEALTHY",
        MaxResults: 100,
      })
    );

    this.instances = Instances ?? [];
    this.lastRevision = currentRevision;
  }

  next(): HttpInstanceSummary {
    if (this.instances.length === 0) {
      throw new Error("No healthy MCP server instances available");
    }
    const instance = this.instances[this.roundRobinIndex % this.instances.length];
    this.roundRobinIndex++;
    return instance;
  }

  startPolling(intervalMs = 10_000): void {
    setInterval(() => this.refresh().catch(console.error), intervalMs);
  }
}

When a tool call fails with a connection error (ECONNREFUSED, ECONNRESET, timeout), call pool.refresh() immediately before retrying — the failed instance may have been deregistered since the last poll, and an immediate refresh fetches the current healthy pool:

async function callToolWithRetry(
  pool: McpServerPool,
  toolName: string,
  params: unknown
): Promise<unknown> {
  for (let attempt = 1; attempt <= 3; attempt++) {
    const instance = pool.next();
    const url = `http://${instance.Attributes!.AWS_INSTANCE_IPV4}:${instance.Attributes!.AWS_INSTANCE_PORT}`;

    try {
      const response = await fetch(`${url}/mcp`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ jsonrpc: "2.0", method: "tools/call", params: { name: toolName, arguments: params }, id: crypto.randomUUID() }),
        signal: AbortSignal.timeout(30_000),
      });
      if (!response.ok) throw new Error(`HTTP ${response.status}`);
      return await response.json();
    } catch (err: any) {
      const isConnectionError = err.name === "TypeError" || err.code === "ECONNREFUSED" || err.code === "ECONNRESET" || err.name === "TimeoutError";
      if (isConnectionError && attempt < 3) {
        await pool.refresh(); // pull current healthy pool immediately
        continue;
      }
      throw err;
    }
  }
}

Gotcha #8: Graceful shutdown requires four ordered steps, not just DeregisterInstance

Calling DeregisterInstance immediately on SIGTERM is not safe for MCP servers with active SSE sessions. DeregisterInstance removes the DNS record and excludes the instance from DiscoverInstances — but DNS clients that have already cached the A record will continue routing new connections to the deregistered IP for up to the service TTL (typically 30 seconds). During that window, new connections arrive at a shutting-down instance.

The correct graceful shutdown sequence:

  1. Mark UNHEALTHY in Cloud Map — stops DiscoverInstances from returning this instance to new callers, and excludes it from DNS once the Route 53 change propagates.
  2. Wait for DNS TTL — wait at least the service TTL (e.g., 30 seconds) so cached DNS entries expire and no new connections arrive.
  3. Drain active SSE sessions — stop accepting new MCP connections but allow in-progress tool calls and existing sessions to complete (or timeout).
  4. Deregister from Cloud Map — clean up the registry entry.
// SIGTERM handler for ECS Fargate MCP servers
// ECS sends SIGTERM, then waits stopTimeout seconds (default 30) before SIGKILL
// Configure stopTimeout: 90 in the task definition to give this handler time to complete

process.on("SIGTERM", async () => {
  console.log("SIGTERM received — beginning graceful shutdown");

  // 1. Stop accepting new MCP connections
  httpServer.close();

  // 2. Mark Cloud Map instance unhealthy — stops new clients from routing here
  if (cloudMapServiceId && cloudMapInstanceId) {
    await cloudMap.send(
      new UpdateInstanceCustomHealthStatusCommand({
        ServiceId: cloudMapServiceId,
        InstanceId: cloudMapInstanceId,
        Status: "UNHEALTHY",
      })
    );
  }

  // 3. Wait for DNS TTL (30s service TTL + 5s buffer)
  // During this window, DNS-cached clients may still send new connections —
  // but httpServer.close() above refuses new TCP connections after current ones drain
  await new Promise((r) => setTimeout(r, 35_000));

  // 4. Drain active SSE sessions (up to 45 seconds)
  await Promise.race([
    waitForAllSessionsToClose(),   // your MCP session tracker
    new Promise((r) => setTimeout(r, 45_000)),
  ]);

  // 5. Deregister from Cloud Map
  if (cloudMapServiceId && cloudMapInstanceId) {
    const { OperationId } = await cloudMap.send(
      new DeregisterInstanceCommand({
        ServiceId: cloudMapServiceId,
        InstanceId: cloudMapInstanceId,
      })
    );
    if (OperationId) await pollUntilDone(OperationId);
  }

  console.log("Graceful shutdown complete");
  process.exit(0);
});

This sequence takes roughly 35–80 seconds in the worst case (35s DNS drain + up to 45s session drain). Configure the ECS task definition's stopTimeout to at least 90 seconds so ECS waits long enough before sending SIGKILL. The default stopTimeout of 30 seconds is too short — it will SIGKILL the process during the DNS TTL wait, defeating the entire graceful shutdown.

ECS's Cloud Map integration performs its own DeregisterInstance call when it stops the task. If your application code also calls DeregisterInstance, catch and ignore the InstanceNotFound error that results when ECS deregisters before your handler completes:

try {
  await cloudMap.send(new DeregisterInstanceCommand({ ServiceId, InstanceId }));
} catch (err: any) {
  if (err.name !== "InstanceNotFound") throw err;
  // ECS already deregistered — no action needed
}

DNS-based discovery vs DiscoverInstances: choosing the right approach

For private DNS namespaces, you have two discovery mechanisms. DNS resolution — a simple dns.resolve4("mcp-server.mcp.internal") — works from any process within the VPC without SDK dependencies. DiscoverInstances returns the full attribute payload but requires an API call. The right choice depends on your pool size and routing complexity:

DNS resolution DiscoverInstances API
Max instances returned 8 (MULTIVALUE policy) 100 per call
Custom attribute access No — IPs only Yes — full attribute map per instance
Freshness Subject to DNS TTL caching Always current state
SDK dependency None — standard dns module Requires @aws-sdk/client-servicediscovery
Works for HTTP namespaces No Yes

Use DNS for simple stateless pools of up to 8 MCP server instances where you don't need attribute-based routing. Use DiscoverInstances when your pool exceeds 8 instances, when you need to route by tool capability or deployment color, or when you need sub-TTL freshness during deployments.

The MULTIVALUE routing policy's 8-instance DNS limit is a hard ceiling — the DNS resolver returns at most 8 A records per query even if 50 healthy instances are registered. If your MCP server pool grows beyond 8 instances and you are relying on DNS, some instances will never receive traffic from DNS-based clients. The selection of which 8 to return is non-deterministic across queries; there is no configuration option to increase this limit.

Consolidated failure patterns table

Symptom Root cause Fix
AccessDeniedException on every Cloud Map call IAM policy uses cloudmap:* instead of servicediscovery:* Change IAM action prefix to servicediscovery:
NamespaceNotFound immediately after CreatePrivateDnsNamespace Did not poll GetOperation before proceeding Add pollUntilDone(operationId) after namespace creation
Cloud Map registry fills with phantom instances after Lambda retries InstanceId was a random UUID — each retry creates a new entry Use stable ID: ECS task ARN, EC2 instance ID, or hostname
InvalidParameterException on ECS service creation with Cloud Map serviceRegistries.registryArn was set to service ID (srv-...) instead of ARN Use Service.Arn not Service.Id from Cloud Map create response
ECS tasks restart in an endless loop during deployment healthCheckGracePeriodSeconds too short — ECS acts on UNKNOWN health status before container health check passes Set healthCheckGracePeriodSeconds = startPeriod + (interval × retries) + 30s buffer
DiscoverInstances returns unhealthy or stopped instances HealthStatus omitted — defaults to "ALL" Always set HealthStatus: "HEALTHY" explicitly
QueryParameters filter returns 0 results for multi-value attribute Attribute stored as comma-separated string; exact-match semantics cannot filter on substring Store one boolean attribute per filterable capability: TOOL_X: "true"
New SSE connections arrive at a shutting-down MCP server instance DeregisterInstance called without waiting for DNS TTL Mark UNHEALTHY → wait TTL → drain sessions → deregister
InvalidInput on RegisterInstance for A-record service AWS_INSTANCE_IPV4 attribute missing from attributes map Include required routing attributes for the DNS record type (see attribute table above)
Attribute update wipes existing routing attributes RegisterInstance update is a full replacement — omitted attributes are deleted Always re-include AWS_INSTANCE_IPV4 and AWS_INSTANCE_PORT in every update call

Putting it together: a production-ready Cloud Map setup for MCP server ECS fleets

The complete Cloud Map deployment for an MCP server ECS fleet requires these components in order:

  1. IAM setup: provisioning role with servicediscovery:* + route53:* + ec2:Describe*; ECS service-linked role gets servicediscovery:* automatically; task role needs servicediscovery:DiscoverInstances + servicediscovery:DiscoverInstancesRevision if the application calls these directly.
  2. Namespace creation: CreatePrivateDnsNamespaceCommand with deterministic CreatorRequestId, followed by GetOperation polling until SUCCESS.
  3. Service creation: CreateServiceCommand with MULTIVALUE routing policy, A-record DNS config with 30-second TTL, and HealthCheckCustomConfig so ECS controls health status. Capture Service.Arn (not Service.Id).
  4. ECS service creation: serviceRegistries[0].registryArn = service ARN from step 3, containerName + containerPort matching task definition, healthCheckGracePeriodSeconds = startPeriod + interval×retries + 30s buffer.
  5. Application startup: read task ARN from ECS metadata endpoint (if augmenting ECS's auto-registration with custom attributes), call RegisterInstance with stable InstanceId = task ARN.
  6. Application discovery: McpServerPool with DiscoverInstancesRevision polling every 10s, DiscoverInstances with HealthStatus: "HEALTHY" on revision change, connection-error handler calling pool.refresh() immediately.
  7. Application shutdown: SIGTERM handler with stopTimeout: 90 in task definition — markUnhealthy → wait 35s → drain sessions 45s → deregister.

Monitor each MCP server instance's /health endpoint independently with AliveMCP to get an external view of instance health that is independent of Cloud Map's internal health reporting. Cloud Map measures health from the Route 53 health checker perspective (periodic HTTP probes); AliveMCP measures end-to-end MCP protocol connectivity including tool call success rates and latency. When a Cloud Map instance transitions to UNHEALTHY, AliveMCP's log gives you the timeline: when the first probe failed, whether it was a connection refusal vs a 5xx error, and how long before recovery.

See the full SEO reference guides for each topic covered in this post: