Guide · AWS Cloud Map · MCP Server Service Discovery

AWS Cloud Map for MCP Server Microservices — Namespaces, Service Types, and SDK Overview

AWS Cloud Map is the service discovery layer that lets MCP server instances find each other, lets clients locate healthy MCP server endpoints without hardcoded URLs, and lets ECS automatically register and deregister MCP server tasks as they start and stop. This guide covers the three namespace types (private DNS, public DNS, HTTP), the CreateService routing policies that determine how instances appear in DNS, the RegisterInstance attribute requirements for each routing type, and the GetOperation polling pattern required for async namespace creation. For ECS task definition integration with Cloud Map, see Cloud Map ECS Integration. For instance registration and custom health attributes, see Service Registration and Instance Management. For DiscoverInstances and health-status filtering, see Cloud Map DiscoverInstances.

TL;DR

Use CreatePrivateDnsNamespace for intra-VPC MCP server microservice discovery (creates a Route 53 private hosted zone), CreateHttpNamespace for API-based discovery without DNS overhead (cheapest, no Route 53), and CreatePublicDnsNamespace only when you need public internet DNS resolution. Both private and public DNS namespace creation is asynchronous — poll GetOperation until Status: SUCCESS before creating services. The MULTIVALUE routing policy returns up to 8 healthy instance A records per DNS query; the WEIGHTED policy returns a single record with configurable weight. HTTP namespaces require DiscoverInstances API calls instead of DNS resolution. The IAM action is servicediscovery:* (not cloudmap:*).

Why MCP servers need service discovery

An MCP server deployment in production typically runs multiple instances behind a load balancer. But MCP servers using the SSE transport establish long-lived HTTP connections — a single ALB distributes new connections but cannot migrate existing sessions to a different backend instance once established. When you scale down or deploy a new version, the instances receiving existing SSE sessions must drain gracefully before termination.

Service discovery complements the ALB by giving each MCP server instance a stable DNS name that clients can resolve to a healthy backend IP, independent of the load balancer's routing decisions. It also gives other microservices (tool services, model proxy services, context storage services) a way to locate MCP server instances without embedding environment-specific hostnames in configuration files.

AWS Cloud Map serves three additional use cases beyond basic service registration:

The three namespace types and when to use each

A Cloud Map namespace is the DNS domain or logical container that groups related services. Services within a namespace share the same DNS suffix for private/public DNS namespaces, or the same namespace ID for HTTP namespaces. Cloud Map supports three namespace types, each with different discovery mechanisms and pricing implications:

Private DNS namespace — CreatePrivateDnsNamespace

Creates a private Route 53 hosted zone, enabling DNS-based discovery within a specified VPC. Instances registered in services under this namespace appear as DNS records. MCP server instances running in ECS Fargate within the same VPC can resolve mcp-server.service.internal (or whatever DNS suffix you choose) to the IP addresses of healthy instances.

Use this for:

Pricing: $1.00 per namespace per month (first 5 private DNS namespaces are free each month in some regions). There is a Route 53 private hosted zone charge of $0.50 per hosted zone per month.

HTTP namespace — CreateHttpNamespace

Creates a logical namespace with no DNS component. Instances registered here are only discoverable via the DiscoverInstances API — DNS queries against an HTTP namespace return no records. This is the cheapest namespace type and the only one where CreateHttpNamespace returns synchronously (no polling required).

Use this for:

Public DNS namespace — CreatePublicDnsNamespace

Creates a public Route 53 hosted zone. Registered instances appear in public DNS and are resolvable from anywhere on the internet. For MCP servers exposed via a public endpoint, public DNS namespaces let you manage DNS entries programmatically through the Cloud Map API rather than the Route 53 API directly.

Use this for: publicly accessible MCP server endpoints where DNS-based client-side load balancing is preferred over ALB. Most MCP server deployments should use a private DNS namespace and place the ALB at the public boundary rather than exposing instance IPs publicly.

Namespace creation and GetOperation polling

Private and public DNS namespace creation is asynchronous because Cloud Map must provision the Route 53 hosted zone. The API returns an OperationId immediately; the namespace is not usable until you poll GetOperation until Status is SUCCESS.

import {
  ServiceDiscoveryClient,
  CreatePrivateDnsNamespaceCommand,
  CreateHttpNamespaceCommand,
  GetOperationCommand,
  ListNamespacesCommand,
  type CreatePrivateDnsNamespaceCommandInput,
} from "@aws-sdk/client-servicediscovery";
import { randomUUID } from "crypto";

const cloudMap = new ServiceDiscoveryClient({ region: "us-east-1" });

// --- Create a private DNS namespace (async) ---
async function createPrivateDnsNamespace(
  name: string, // e.g., "service.internal"
  vpcId: string
): Promise<string> {
  // CreatorRequestId is an idempotency key — reuse same value to safely retry
  const input: CreatePrivateDnsNamespaceCommandInput = {
    Name: name,
    Vpc: vpcId,
    CreatorRequestId: `create-ns-${name}`, // idempotent: same value = no duplicate
    Description: "MCP server microservices namespace",
  };

  const result = await cloudMap.send(
    new CreatePrivateDnsNamespaceCommand(input)
  );
  const operationId = result.OperationId!;

  // Poll until SUCCESS (typically 10–30 seconds)
  return await pollOperation(operationId);
}

// --- GetOperation polling helper ---
async function pollOperation(
  operationId: string,
  maxWaitMs = 120_000
): Promise<string> {
  const deadline = Date.now() + maxWaitMs;
  let delay = 2000;

  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":
        // Operation.Targets contains the resource ARN/ID that was created
        return Operation.Targets?.["NAMESPACE"] ?? "";
      case "FAIL":
        throw new Error(
          `Cloud Map operation failed: ${Operation.ErrorMessage ?? "unknown error"}`
        );
      case "SUBMITTED":
      case "PENDING":
        // Keep polling
        break;
      default:
        throw new Error(`Unexpected operation status: ${Operation?.Status}`);
    }
  }
  throw new Error(`Operation ${operationId} did not complete within timeout`);
}

// --- Create an HTTP namespace (synchronous — no polling needed) ---
async function createHttpNamespace(name: string): Promise<string> {
  const result = await cloudMap.send(
    new CreateHttpNamespaceCommand({
      Name: name,
      CreatorRequestId: `create-http-ns-${name}`,
    })
  );
  // HTTP namespace: OperationId is still returned but the resource is created
  // synchronously — the Operation status is SUCCESS immediately.
  // Poll anyway to retrieve the namespace ID.
  return await pollOperation(result.OperationId!);
}

// --- List all namespaces ---
async function listNamespaces(): Promise<void> {
  let nextToken: string | undefined;
  do {
    const { Namespaces, NextToken } = await cloudMap.send(
      new ListNamespacesCommand({ NextToken: nextToken })
    );
    for (const ns of Namespaces ?? []) {
      console.log(`${ns.Type}: ${ns.Name} (${ns.Id}) — ${ns.ServiceCount} services`);
    }
    nextToken = NextToken;
  } while (nextToken);
}

The CreatorRequestId parameter is Cloud Map's idempotency key. If you call CreatePrivateDnsNamespaceCommand twice with the same CreatorRequestId, the second call returns the original OperationId without creating a duplicate namespace. Always set this to a deterministic value (not a random UUID) so that retries after Lambda timeouts or ECS task restarts do not create duplicate namespaces.

Creating a service within the namespace

A Cloud Map service is a named group of endpoints within a namespace. For DNS namespaces, the service has a DnsConfig that determines what DNS record type is created when instances are registered. For HTTP namespaces, DnsConfig is omitted.

import {
  CreateServiceCommand,
  type CreateServiceCommandInput,
} from "@aws-sdk/client-servicediscovery";

// --- Service for a private DNS namespace ---
// Registers A records; DiscoverInstances also works
async function createDnsService(
  namespaceName: string,
  namespaceId: string
): Promise<string> {
  const input: CreateServiceCommandInput = {
    Name: "mcp-server",
    NamespaceId: namespaceId,
    CreatorRequestId: `create-svc-mcp-server-${namespaceId}`,
    DnsConfig: {
      NamespaceId: namespaceId,
      RoutingPolicy: "MULTIVALUE", // or "WEIGHTED"
      DnsRecords: [
        {
          Type: "A",   // IPv4 address record
          TTL: 30,     // 30 seconds — balance freshness vs DNS query cost
        },
      ],
    },
    // Optional: Route53-managed health check on each registered instance
    // HealthCheckConfig: {
    //   Type: "HTTP",
    //   ResourcePath: "/health",
    //   FailureThreshold: 1,  // number of consecutive checks to flip status
    // },
  };

  const { Service } = await cloudMap.send(new CreateServiceCommand(input));
  return Service!.Id!;
}

// --- Service for an HTTP namespace ---
// No DnsConfig — discovery only via DiscoverInstances API
async function createHttpService(namespaceId: string): Promise<string> {
  const { Service } = await cloudMap.send(
    new CreateServiceCommand({
      Name: "mcp-server",
      NamespaceId: namespaceId,
      CreatorRequestId: `create-http-svc-${namespaceId}`,
      // HealthCheckCustomConfig lets you call UpdateInstanceCustomHealthStatus
      // from your own health checker (ECS agent does this automatically)
      HealthCheckCustomConfig: {
        FailureThreshold: 1,
      },
    })
  );
  return Service!.Id!;
}

The MULTIVALUE routing policy returns up to 8 instance A records per DNS query, distributing load across multiple healthy instances. The WEIGHTED policy returns a single A record from the pool — it is primarily used for canary deployments where you give a new instance a low weight (e.g., 1 out of 100) and gradually increase it. For most MCP server deployments, MULTIVALUE is the right default because it allows client-side load balancing across all healthy instances.

The TTL of 30 seconds is a reasonable default for MCP servers: short enough that deregistered instances drain from DNS caches within half a minute, but not so short that you pay for excessive DNS query volume. Each DNS query to a Cloud Map private DNS namespace is billed at standard Route 53 rates.

Routing policy comparison: MULTIVALUE vs WEIGHTED

Routing policy DNS records returned Use case for MCP servers Health check behavior
MULTIVALUE Up to 8 A records (all healthy instances) Stateless MCP server instances; client-side round-robin across the pool Unhealthy instances excluded from DNS responses automatically
WEIGHTED Single A record; each instance has a weight (0–1000) Blue/green cutover; canary traffic splitting between new and old MCP server versions Unhealthy instances excluded; weight 0 completely removes from rotation

Setting an instance's weight to 0 is equivalent to deregistering it from DNS routing without actually calling DeregisterInstance — useful for graceful draining. Update the weight via UpdateInstanceCustomHealthStatusCommand does not change the weight; use RegisterInstanceCommand with the same InstanceId to overwrite attributes including AWS_INSTANCE_WEIGHT.

IAM permissions for Cloud Map operations

Cloud Map's IAM action namespace is servicediscovery — not cloudmap. This trips up teams who try to write policies with cloudmap:* and get AccessDeniedException on every call.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "CloudMapControl",
      "Effect": "Allow",
      "Action": [
        "servicediscovery:CreatePrivateDnsNamespace",
        "servicediscovery:CreateHttpNamespace",
        "servicediscovery:CreatePublicDnsNamespace",
        "servicediscovery:CreateService",
        "servicediscovery:DeleteNamespace",
        "servicediscovery:DeleteService",
        "servicediscovery:GetOperation",
        "servicediscovery:ListNamespaces",
        "servicediscovery:ListServices",
        "servicediscovery:GetNamespace",
        "servicediscovery:GetService"
      ],
      "Resource": "*"
    },
    {
      "Sid": "CloudMapInstanceManagement",
      "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",
        "route53:ListHostedZonesByName"
      ],
      "Resource": "*"
    },
    {
      "Sid": "EC2ForVPCAssociation",
      "Effect": "Allow",
      "Action": [
        "ec2:DescribeVpcs",
        "ec2:DescribeSubnets"
      ],
      "Resource": "*"
    }
  ]
}

The route53:* and ec2:Describe* actions are needed because Cloud Map creates and manages Route 53 private hosted zones and must look up VPC metadata when creating private DNS namespaces. The Route 53 permissions are only required on the principal that creates/deletes namespaces, not on principals that only register instances or call DiscoverInstances.

For ECS task definitions that need to register instances at runtime, the task execution role needs servicediscovery:RegisterInstance and servicediscovery:DeregisterInstance. ECS handles this automatically when you configure serviceRegistries in the ECS service definition — the ECS service-linked role (not the task role) performs the registration calls on behalf of the task.

Namespace and service limits

Cloud Map has soft limits that matter at scale:

Cloud Map charges $1.00 per namespace per month, $1.00 per service per month, and $1.00 per instance per month for instances in private DNS namespaces (first 5 namespaces, 5 services, and 25 instances are free each month). Route53-managed health checks on instances cost an additional $0.50 per health check per month — if each instance registers a health check, costs scale linearly with your fleet size. Consider using ECS custom health check integration (which calls UpdateInstanceCustomHealthStatus from the container agent) instead of Route53-managed health checks to avoid this per-instance charge.

Complete namespace and service setup example

// Full setup: create namespace + service, then verify
import {
  ServiceDiscoveryClient,
  CreatePrivateDnsNamespaceCommand,
  CreateServiceCommand,
  GetOperationCommand,
  GetServiceCommand,
} from "@aws-sdk/client-servicediscovery";

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

async function setupCloudMapForMcpServer(vpcId: string): Promise<{
  namespaceId: string;
  serviceId: string;
  serviceArn: string;
}> {
  // Step 1: Create namespace (async)
  const { OperationId: nsOpId } = await cloudMap.send(
    new CreatePrivateDnsNamespaceCommand({
      Name: "mcp.internal",
      Vpc: vpcId,
      CreatorRequestId: "mcp-internal-ns-v1",
      Description: "MCP server microservices — private DNS",
    })
  );

  const namespaceId = await waitForOperation(nsOpId!);
  console.log("Namespace created:", namespaceId);

  // Step 2: Create service within namespace
  const { Service } = await cloudMap.send(
    new CreateServiceCommand({
      Name: "mcp-server",
      NamespaceId: namespaceId,
      CreatorRequestId: "mcp-server-service-v1",
      Description: "MCP server instances",
      DnsConfig: {
        NamespaceId: namespaceId,
        RoutingPolicy: "MULTIVALUE",
        DnsRecords: [{ Type: "A", TTL: 30 }],
      },
      HealthCheckCustomConfig: { FailureThreshold: 1 },
    })
  );

  const serviceId = Service!.Id!;
  const serviceArn = Service!.Arn!;
  console.log("Service created:", serviceId);
  // DNS name: mcp-server.mcp.internal

  return { namespaceId, serviceId, serviceArn };
}

async function waitForOperation(operationId: string): Promise<string> {
  for (let attempt = 0; attempt < 30; attempt++) {
    await new Promise((r) => setTimeout(r, 3000 + attempt * 1000));
    const { Operation } = await cloudMap.send(
      new GetOperationCommand({ OperationId: operationId })
    );
    if (Operation?.Status === "SUCCESS") {
      return Operation.Targets?.["NAMESPACE"] ?? "";
    }
    if (Operation?.Status === "FAIL") {
      throw new Error(`Operation failed: ${Operation.ErrorMessage}`);
    }
  }
  throw new Error("Namespace creation timed out after 90 seconds");
}

Once the service is created, the DNS hostname for your MCP server instances is mcp-server.mcp.internal — resolvable from any resource in the associated VPC. MCP server clients within the VPC can connect to https://mcp-server.mcp.internal:3000 and the DNS resolver returns the IP addresses of all healthy registered instances, distributing connections across the pool.

Use AliveMCP to monitor the health endpoint of each individual MCP server instance independently of Cloud Map's health reporting — Cloud Map measures health from the Route 53 health checker perspective (periodic HTTP probes from outside your VPC), while AliveMCP measures end-to-end MCP protocol connectivity including tool call latency.