Amazon Bedrock · Cross-Region Inference, System Profiles, Application Profiles & Retry Logic · 2026-11-22 · Cross-Region Inference arc
Amazon Bedrock Cross-Region Inference Profiles for MCP Servers: Ten Production Gotchas and a Complete TypeScript Handler
Four Bedrock cross-region inference arc pages synthesised into a complete production playbook for MCP server developers — covering cross-region routing mechanics (how the us./eu./ap. prefix turns a single ConverseCommand into a multi-region capacity pool), system inference profiles (AWS-owned, discovered via ListInferenceProfilesCommand({typeEquals:"SYSTEM_DEFINED"}) not ListFoundationModels), application inference profiles (user-created wrappers for cost-allocation tags and stable naming, created with CreateInferenceProfileCommand), and production MCP tool handler patterns (startup validation, Retry-After-aware exponential backoff, streaming with ConverseStreamCommand, and CloudWatch alarms for sustained throttling). The ten production gotchas extracted from all four pages are consolidated below — each one silently breaks a real deployment.
Why MCP servers need cross-region inference
An MCP server is an always-on process fielding tool calls from AI agents around the clock. When an agent pipeline scales — a code-review agent processing hundreds of pull requests overnight, a data-enrichment pipeline calling an MCP lookup tool on every record in a dataset — it hits Amazon Bedrock on-demand capacity in bursts that exceed what a single region can absorb. The result is a storm of ThrottlingException errors from BedrockRuntimeClient that the calling agent interprets as tool failures, breaking the agent loop.
The standard remediation is provisioned throughput, but provisioned throughput requires a minimum 1-month commitment and costs money even when idle. Cross-region inference is the lower-commitment alternative: Bedrock routes requests across multiple regions at on-demand rates, and you pay only for tokens consumed. For an MCP server with bursty, unpredictable traffic — triggered by users, agent runs, or events — cross-region inference on-demand is the right first step before committing to provisioned throughput.
The API surface change is a single character: replace anthropic.claude-3-5-sonnet-20241022-v2:0 with us.anthropic.claude-3-5-sonnet-20241022-v2:0 as your modelId. That prefix is the only code change required. The routing, failover, and capacity management happen entirely inside Bedrock. The rest of this guide is about everything that breaks in production because developers assume it really is that simple.
How cross-region routing actually works
When you call ConverseCommand with a cross-region profile ID, the HTTP request goes to the Bedrock endpoint in your SDK client's configured region (for example, https://bedrock-runtime.us-east-1.amazonaws.com). Bedrock accepts the request there, determines which regions are covered by the us. cross-region profile, checks capacity availability across the pool, and forwards the request internally to whichever region has capacity. The response comes back from the same regional endpoint your client called — your MCP server never establishes a direct connection to any region other than its home region.
This design has two important practical consequences for MCP server infrastructure:
- VPC and network boundaries stay simple. Your MCP server needs outbound HTTPS access only to the Bedrock endpoint in its home region. No VPC peering, no multi-region PrivateLink endpoints, no changes to security groups.
- IAM policies still reference the home region. The IAM resource ARN for a cross-region system profile has your home region in the ARN, not the region where computation actually occurs. The ARN is
arn:aws:bedrock:us-east-1::foundation-model/us.anthropic.claude-3-5-sonnet-20241022-v2:0—us-east-1is the region where you manage access, even though Bedrock may actually run the tokens inus-west-2.
Region pools by prefix:
| Prefix | Regions in pool | Notes |
|---|---|---|
us. | us-east-1, us-west-2, us-east-2 | Largest capacity pool; most Claude 3.5+ models available |
eu. | eu-west-1, eu-central-1, eu-west-3 | GDPR-scoped: data never leaves the EU geography |
ap. | ap-northeast-1, ap-southeast-1, ap-south-1 | Asia Pacific; model availability narrower than US pool |
Not all models are available in all regions within a prefix pool. If a model is unavailable in a specific target region, Bedrock skips that region silently — the profile degrades gracefully to the available regions. This is different from the model access gotcha described next, which causes active throttling rather than graceful skipping.
Gotcha #1 — Model access must be enabled in every region of the pool, not just your home region
AWS requires you to explicitly request model access in each region before Bedrock can invoke a model there. If you request model access only in us-east-1 and use the us. cross-region profile, Bedrock will throw ThrottlingException from us-west-2 and us-east-2 when it tries to route there — because Bedrock treats missing model access as equivalent to no capacity, and the exception surfaces as throttling rather than access denial.
The confusing part: the exception name is ThrottlingException, not AccessDeniedException. Many developers see throttling errors, assume they just need better retry logic, add jitter and backoff, and ship to production — only to discover that the retries never stop because the access problem is permanent. The diagnostic tell is that throttling errors persist indefinitely regardless of retry delay, while genuine capacity throttling clears after a few retries during off-peak periods.
To enable model access in all pool regions via CLI:
for region in us-east-1 us-west-2 us-east-2; do
aws bedrock put-foundation-model-entitlement \
--model-id "anthropic.claude-3-5-sonnet-20241022-v2:0" \
--region "$region"
done
No CDK L1 construct exists for Bedrock model access as of late 2026 — it is an account-level console/CLI setting. Validate after enabling by calling GetFoundationModelCommand in each region and checking that modelLifecycle.status is "ACTIVE".
Gotcha #2 — System profiles are not in ListFoundationModels
The first thing most developers do when they want to use cross-region inference is call ListFoundationModelsCommand looking for profile IDs. They find only single-region model IDs like anthropic.claude-3-5-sonnet-20241022-v2:0 and no cross-region profiles. This is not a permissions issue or a region misconfiguration — system inference profiles simply do not appear in ListFoundationModels results at all.
The correct API is ListInferenceProfilesCommand with the typeEquals filter set to "SYSTEM_DEFINED":
import { BedrockClient, ListInferenceProfilesCommand } from "@aws-sdk/client-bedrock";
const bedrockClient = new BedrockClient({ region: "us-east-1" });
async function listSystemProfiles() {
const profiles = [];
let nextToken: string | undefined;
do {
const response = await bedrockClient.send(new ListInferenceProfilesCommand({
typeEquals: "SYSTEM_DEFINED",
maxResults: 100,
nextToken,
}));
for (const summary of response.inferenceProfileSummaries ?? []) {
profiles.push({
id: summary.inferenceProfileId!, // "us.anthropic.claude-3-5-sonnet-20241022-v2:0"
arn: summary.inferenceProfileArn!, // "arn:aws:bedrock:us-east-1::foundation-model/us.anthropic...."
status: summary.status!, // "ACTIVE"
models: (summary.models ?? []).map(m => m.modelArn!),
});
}
nextToken = response.nextToken;
} while (nextToken);
return profiles;
}
The returned inferenceProfileId (e.g., us.anthropic.claude-3-5-sonnet-20241022-v2:0) is the string you pass as modelId in ConverseCommand. The models[] array in GetInferenceProfileCommand response contains one entry per region in the routing pool — each with the region-specific ARN for the underlying foundation model. This list is the authoritative source for which regions the profile routes to and therefore which regions need model access enabled.
Available system profiles as of 2026:
| System profile ID | Geography | Regions in pool |
|---|---|---|
us.anthropic.claude-opus-4-7-20251101-v1:0 | US | us-east-1, us-west-2, us-east-2 |
us.anthropic.claude-sonnet-4-6-20251101-v1:0 | US | us-east-1, us-west-2, us-east-2 |
us.anthropic.claude-3-5-sonnet-20241022-v2:0 | US | us-east-1, us-west-2, us-east-2 |
us.anthropic.claude-3-5-haiku-20241022-v1:0 | US | us-east-1, us-west-2, us-east-2 |
eu.anthropic.claude-3-5-sonnet-20241022-v2:0 | EU | eu-west-1, eu-central-1, eu-west-3 |
eu.anthropic.claude-3-5-haiku-20241022-v1:0 | EU | eu-west-1, eu-central-1, eu-west-3 |
ap.anthropic.claude-3-5-sonnet-20241022-v2:0 | AP | ap-northeast-1, ap-southeast-1, ap-south-1 |
Use ListInferenceProfilesCommand at startup for the authoritative current list — AWS adds new profiles as models become available in additional regions.
Gotcha #3 — The IAM ARN includes the geographic prefix
The IAM resource ARN for a cross-region system profile looks almost identical to a regular foundation model ARN, with one critical difference: the model ID in the ARN includes the us. prefix.
| Identifier type | IAM Resource ARN |
|---|---|
| Single-region foundation model | arn:aws:bedrock:us-east-1::foundation-model/anthropic.claude-3-5-sonnet-20241022-v2:0 |
| System inference profile (US) | arn:aws:bedrock:us-east-1::foundation-model/us.anthropic.claude-3-5-sonnet-20241022-v2:0 |
| Application inference profile | arn:aws:bedrock:us-east-1:123456789012:application-inference-profile/mcp-server-claude-prod |
If your MCP server's IAM task role has bedrock:InvokeModel on arn:aws:bedrock:us-east-1::foundation-model/anthropic.claude-... (without the us. prefix) but you switch the modelId to us.anthropic.claude-..., you will get AccessDeniedException immediately on every invocation — before any routing logic is involved. The fix is to update the IAM Resource to include the prefix:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"bedrock:InvokeModel",
"bedrock:InvokeModelWithResponseStream"
],
"Resource": [
"arn:aws:bedrock:us-east-1::foundation-model/us.anthropic.claude-3-5-sonnet-20241022-v2:0",
"arn:aws:bedrock:us-east-1::foundation-model/us.anthropic.claude-3-haiku-20240307-v1:0"
]
},
{
"Effect": "Allow",
"Action": [
"bedrock:GetInferenceProfile",
"bedrock:ListInferenceProfiles"
],
"Resource": "*"
}
]
}
Three common IAM mistakes: (1) Using the foundation model ARN without the prefix — AccessDeniedException on every call. (2) Using the wrong region in the ARN — the region should be your home region (where your BedrockClient is configured), not any region in the routing pool. (3) Forgetting that application inference profile ARNs include your account ID while system profile ARNs do not (the double-colon :: before foundation-model is correct — AWS-managed ARNs have no account ID in that segment).
Gotcha #4 — CreateInferenceProfileCommand.modelSource.copyFrom requires a system profile ID, not a foundation model ID
When creating an application inference profile, the modelSource.copyFrom field takes a system profile ID (e.g., us.anthropic.claude-3-5-sonnet-20241022-v2:0) — not a plain foundation model ID (e.g., anthropic.claude-3-5-sonnet-20241022-v2:0). Passing the foundation model ID without the geographic prefix returns ValidationException. The error message is not always clear about which field is invalid, so this can burn time diagnosing.
The correct creation workflow:
import { BedrockClient, CreateInferenceProfileCommand } from "@aws-sdk/client-bedrock";
const bedrockClient = new BedrockClient({ region: "us-east-1" });
async function createMcpServerProfile(options: {
name: string; // e.g. "mcp-server-claude-prod"
systemProfileId: string; // e.g. "us.anthropic.claude-3-5-sonnet-20241022-v2:0" ← with prefix
environment: string; // "production" | "staging" | "dev"
service: string; // "code-review-agent" | "data-enrichment" | ...
costCenter: string;
}) {
const response = await bedrockClient.send(new CreateInferenceProfileCommand({
inferenceProfileName: options.name,
description: `Bedrock profile for ${options.service} in ${options.environment}`,
modelSource: {
copyFrom: options.systemProfileId, // ← must be system profile ID, not foundation model ID
},
tags: [
{ key: "environment", value: options.environment },
{ key: "service", value: options.service },
{ key: "cost-center", value: options.costCenter },
{ key: "managed-by", value: "mcp-server-platform" },
],
}));
return response.inferenceProfileArn!;
// "arn:aws:bedrock:us-east-1:123456789012:application-inference-profile/mcp-server-claude-prod"
}
The returned application profile ARN is the value you pass as modelId in ConverseCommand. The profile is immediately ACTIVE after creation — no async polling needed.
Gotcha #5 — Duplicate profile names return ConflictException
inferenceProfileName must be unique within the region. Attempting to create two profiles with the same name returns ConflictException. This comes up most often in automated deployment scripts that do not check for an existing profile before creating. The recommended pattern for idempotent creation:
async function getOrCreateProfile(name: string, systemProfileId: string, tags: Array<{key: string; value: string}>) {
// Try to get existing profile first
try {
const existing = await bedrockClient.send(new GetInferenceProfileCommand({
inferenceProfileIdentifier: name,
}));
if (existing.status === "ACTIVE") {
return existing.inferenceProfileArn!;
}
} catch (err: any) {
if (err.name !== "ResourceNotFoundException") throw err;
// Not found — proceed to create
}
const created = await bedrockClient.send(new CreateInferenceProfileCommand({
inferenceProfileName: name,
modelSource: { copyFrom: systemProfileId },
tags,
}));
return created.inferenceProfileArn!;
}
Use a naming convention like {service}-{model-short-name}-{environment} (e.g., code-review-claude35-prod) to minimize collision risk. Profile names are reusable after deletion — if you delete a profile, a new profile can be created with the same name immediately.
Gotcha #6 — Application profile IAM uses account-scoped ARN, not foundation-model ARN
The IAM policy for invoking an application profile is structurally different from the policy for invoking a system profile or foundation model. Application profile ARNs include your account ID and use a different resource type path (application-inference-profile instead of foundation-model):
{
"Sid": "BedrockApplicationProfileInvoke",
"Effect": "Allow",
"Action": [
"bedrock:InvokeModel",
"bedrock:InvokeModelWithResponseStream"
],
"Resource": [
"arn:aws:bedrock:us-east-1:123456789012:application-inference-profile/mcp-server-claude-prod"
]
}
If your ECS task role has bedrock:InvokeModel on arn:aws:bedrock:us-east-1::foundation-model/us.anthropic.claude-... but NOT on the application profile ARN, invocations via the application profile return AccessDeniedException. This is easy to miss when migrating from system profiles to application profiles — both profile types route through the same underlying foundation model, but IAM evaluates the ARN you passed as modelId, not the underlying model.
Use IAM conditions to scope each service to only its own profile:
{
"Effect": "Allow",
"Action": "bedrock:InvokeModel",
"Resource": "arn:aws:bedrock:us-east-1:123456789012:application-inference-profile/*",
"Condition": {
"StringEquals": {
"aws:ResourceTag/service": "code-review-agent"
}
}
}
This prevents one service's task role from invoking on another service's billing line, even if the ARN format is known. Store the application profile ARN in an ECS task definition environment variable (BEDROCK_PROFILE_ARN) rather than constructing it dynamically in code — this makes profile rotation a configuration change, not a code deployment.
Gotcha #7 — The Retry-After header must be respected, not ignored
When Bedrock returns ThrottlingException (HTTP 429), the response includes a Retry-After header indicating how many seconds the caller should wait before retrying. Ignoring this header and retrying immediately has two consequences, both negative:
- It makes throttling worse. Bedrock tracks requests per second (RPS) at the account level. Rapid retries increase effective RPS, causing more requests to be throttled rather than fewer. A retry storm against a throttled endpoint drives the success rate down, not up.
- It masks the model-access configuration problem from Gotcha #1. When model access is missing in a pool region, Bedrock returns
ThrottlingExceptionin a loop. Without the Retry-After delay, retries fire fast and the logs show thousands of throttle failures with no indication of the root cause. With the delay, consecutive failures become obvious in logs before the quota is fully exhausted.
The Retry-After header is accessible in AWS SDK v3 errors via err.$response?.headers?.["retry-after"]. The value is in seconds:
async function withBedrockRetry<T>(
fn: () => Promise<T>,
opts: { maxAttempts?: number; baseDelayMs?: number; maxDelayMs?: number } = {}
): Promise<T> {
const { maxAttempts = 4, baseDelayMs = 1000, maxDelayMs = 30_000 } = opts;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
return await fn();
} catch (err: any) {
const isThrottling =
err.name === "ThrottlingException" ||
err.name === "ServiceUnavailableException" ||
err.$metadata?.httpStatusCode === 429 ||
err.$metadata?.httpStatusCode === 503;
if (!isThrottling || attempt === maxAttempts) throw err;
// Respect Retry-After if present
const retryAfterHeader = err.$response?.headers?.["retry-after"];
let delayMs = retryAfterHeader
? parseInt(retryAfterHeader, 10) * 1000
: Math.min(baseDelayMs * Math.pow(2, attempt - 1), maxDelayMs);
// ±20% jitter to avoid thundering herd
const jitter = delayMs * 0.2 * (Math.random() * 2 - 1);
delayMs = Math.max(0, delayMs + jitter);
console.warn(
`[bedrock] ${err.name} on attempt ${attempt}/${maxAttempts}. ` +
`Retrying in ${Math.round(delayMs)}ms.`
);
await new Promise(resolve => setTimeout(resolve, delayMs));
}
}
throw new Error("[bedrock] unreachable: exceeded maxAttempts without returning or throwing");
}
When retries exhaust maxAttempts, include a diagnostic message listing the common causes so the error is actionable: model access missing in pool regions, account-level quota exhausted, or a region-wide Bedrock service event.
Gotcha #8 — Startup validation before accepting tool calls
Rather than discovering at runtime — during an active agent execution — that an inference profile does not exist or is inactive, perform a validation call when your MCP server initializes. A fast fail at startup means the deployment fails predictably in CI, not mid-flight during an agent run.
import { BedrockClient, GetInferenceProfileCommand } from "@aws-sdk/client-bedrock";
const bedrockClient = new BedrockClient({ region: process.env.AWS_REGION ?? "us-east-1" });
const MODEL_ID = process.env.BEDROCK_MODEL_ID ?? "us.anthropic.claude-3-5-sonnet-20241022-v2:0";
export async function validateInferenceProfile(): Promise<void> {
try {
const profile = await bedrockClient.send(new GetInferenceProfileCommand({
inferenceProfileIdentifier: MODEL_ID,
}));
if (profile.status !== "ACTIVE") {
throw new Error(
`Bedrock inference profile "${MODEL_ID}" status is "${profile.status}" — expected ACTIVE.`
);
}
const targetRegions = (profile.models ?? [])
.map(m => m.modelArn?.split(":")[3])
.filter(Boolean);
console.log(
`[bedrock] Profile OK: "${MODEL_ID}" ACTIVE. Routes to: ${targetRegions.join(", ")}`
);
} catch (err: any) {
if (err.name === "ResourceNotFoundException") {
throw new Error(
`Bedrock inference profile "${MODEL_ID}" not found in region "${process.env.AWS_REGION}". ` +
`System profiles use format "us.anthropic.claude-...", ` +
`application profiles use the full ARN.`
);
}
if (err.name === "AccessDeniedException") {
throw new Error(
`AccessDeniedException on GetInferenceProfileCommand for "${MODEL_ID}". ` +
`Add bedrock:GetInferenceProfile to the task/function IAM role.`
);
}
throw err;
}
}
Call validateInferenceProfile() before the MCP server starts accepting connections — before server.connect(transport). The function also logs the target regions, which helps verify that model access is enabled where you expect during first deployment.
Gotcha #9 — System profiles cannot be tagged; use application profiles for cost visibility
System inference profiles are AWS-owned and immutable — you cannot tag them. This means GetCostAndUsageCommand in Cost Explorer cannot attribute Bedrock token spend to a specific MCP server, feature, or team. All cross-region invocations via system profiles appear as a single undifferentiated line item in the monthly Bedrock invoice.
Application inference profiles solve this. Each profile wraps a system profile and adds custom tags that propagate to Cost and Usage Report line items. The routing behavior is identical — an application profile copying from us.anthropic.claude-3-5-sonnet-20241022-v2:0 routes across the same three US regions as the system profile. The only difference is cost visibility and naming.
To see Bedrock spend broken down by application profile tag in Cost Explorer:
- Create application profiles with consistent tag keys:
service,environment,cost-center. - Go to AWS Billing → Cost allocation tags, select your tags, choose Activate. Tag activation takes up to 24 hours to reflect in Cost Explorer.
- Open Cost Explorer, filter by Service: Bedrock, group by your tag key to see spend per MCP service.
Important: tags propagate only to invocations made after profile creation. Invocations using the system profile ID directly carry no custom tags and appear as untagged Bedrock spend. During migration from system to application profiles there will be a gap in cost attribution. The quota is 100 application inference profiles per region per account — sufficient for most teams (one profile per service per environment = 20–40 profiles at typical scale).
Gotcha #10 — ConverseStream retry wraps the connection, not the stream iteration
Streaming tool calls present a subtle retry challenge: ConverseStreamCommand returns a stream, not a complete response. You cannot retry mid-stream because the response has already started arriving. The correct pattern is to wrap the initial ConverseStreamCommand call (the connection) in the retry helper, and let stream iteration errors propagate directly to the caller:
export async function* streamModel(params: {
messages: Message[];
system?: SystemContentBlock[];
maxTokens?: number;
}): AsyncGenerator<string> {
// Retry wraps only the connection, not the stream iteration
const response = await withBedrockRetry(() =>
runtimeClient.send(new ConverseStreamCommand({
modelId: MODEL_ID,
system: params.system,
messages: params.messages,
inferenceConfig: { maxTokens: params.maxTokens ?? 4096 },
}))
);
for await (const event of response.stream ?? []) {
if (event.contentBlockDelta?.delta?.text) {
yield event.contentBlockDelta.delta.text;
}
if (event.messageStop?.stopReason) {
console.log(`[bedrock] stream complete, stopReason=${event.messageStop.stopReason}`);
}
}
}
If Bedrock returns ThrottlingException before the stream starts (at connection time), withBedrockRetry handles it transparently. If a network error occurs mid-stream, the generator throws and the MCP tool handler receives the error. For MCP tools with streaming output, the calling agent will need to handle partial tool responses — either by designing tools to be idempotent (safe to retry from scratch) or by using non-streaming ConverseCommand for work that cannot tolerate partial failure.
Cross-region routing adds ~50–200 ms of first-token latency only when Bedrock redirects to a non-home region. For MCP tools with tight latency budgets — real-time code autocomplete, sub-100ms lookup tools — benchmark whether this overhead is acceptable before switching production workloads to cross-region profiles.
The complete MCP tool handler
Assembling all patterns above into a production-ready module:
// bedrock-client.ts — complete module for MCP server Bedrock integration
import {
BedrockClient,
GetInferenceProfileCommand,
} from "@aws-sdk/client-bedrock";
import {
BedrockRuntimeClient,
ConverseCommand,
ConverseStreamCommand,
type Message,
type SystemContentBlock,
} from "@aws-sdk/client-bedrock-runtime";
const REGION = process.env.AWS_REGION ?? "us-east-1";
const MODEL_ID = process.env.BEDROCK_MODEL_ID ??
"us.anthropic.claude-3-5-sonnet-20241022-v2:0";
const bedrockClient = new BedrockClient({ region: REGION });
const runtimeClient = new BedrockRuntimeClient({ region: REGION });
// ── Startup validation ────────────────────────────────────────────
export async function validateInferenceProfile(): Promise<void> {
try {
const profile = await bedrockClient.send(new GetInferenceProfileCommand({
inferenceProfileIdentifier: MODEL_ID,
}));
if (profile.status !== "ACTIVE") {
throw new Error(`Profile "${MODEL_ID}" status "${profile.status}" — expected ACTIVE`);
}
const regions = (profile.models ?? []).map(m => m.modelArn?.split(":")[3]).filter(Boolean);
console.log(`[bedrock] Profile OK: "${MODEL_ID}" ACTIVE. Routes to: ${regions.join(", ")}`);
} catch (err: any) {
if (err.name === "ResourceNotFoundException") {
throw new Error(
`Profile "${MODEL_ID}" not found in "${REGION}". ` +
`System profiles: "us.anthropic.claude-...". Application profiles: full ARN.`
);
}
if (err.name === "AccessDeniedException") {
throw new Error(`AccessDeniedException on GetInferenceProfile — add bedrock:GetInferenceProfile to IAM role`);
}
throw err;
}
}
// ── Retry with Retry-After header ────────────────────────────────
async function withBedrockRetry<T>(fn: () => Promise<T>, maxAttempts = 4): Promise<T> {
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
return await fn();
} catch (err: any) {
const isThrottling = err.name === "ThrottlingException" ||
err.name === "ServiceUnavailableException" ||
err.$metadata?.httpStatusCode === 429 || err.$metadata?.httpStatusCode === 503;
if (!isThrottling || attempt === maxAttempts) throw err;
const retryAfter = err.$response?.headers?.["retry-after"];
let ms = retryAfter
? parseInt(retryAfter, 10) * 1000
: Math.min(1000 * Math.pow(2, attempt - 1), 30_000);
ms += ms * 0.2 * (Math.random() * 2 - 1); // ±20% jitter
console.warn(`[bedrock] ${err.name} attempt ${attempt}/${maxAttempts}, retry in ${Math.round(ms)}ms`);
await new Promise(r => setTimeout(r, Math.max(0, ms)));
}
}
throw new Error("[bedrock] maxAttempts exceeded");
}
// ── Non-streaming invocation ──────────────────────────────────────
export async function invokeModel(params: {
messages: Message[];
system?: SystemContentBlock[];
maxTokens?: number;
temperature?: number;
}): Promise<{ text: string; stopReason: string; inputTokens: number; outputTokens: number }> {
return withBedrockRetry(async () => {
const response = await runtimeClient.send(new ConverseCommand({
modelId: MODEL_ID,
system: params.system,
messages: params.messages,
inferenceConfig: { maxTokens: params.maxTokens ?? 4096, temperature: params.temperature ?? 0.0 },
}));
const text = (response.output?.message?.content ?? [])
.filter((b): b is { text: string } => "text" in b && typeof b.text === "string")
.map(b => b.text).join("");
return {
text,
stopReason: response.stopReason ?? "end_turn",
inputTokens: response.usage?.inputTokens ?? 0,
outputTokens: response.usage?.outputTokens ?? 0,
};
});
}
// ── Streaming invocation ──────────────────────────────────────────
export async function* streamModel(params: {
messages: Message[];
system?: SystemContentBlock[];
maxTokens?: number;
}): AsyncGenerator<string> {
const response = await withBedrockRetry(() =>
runtimeClient.send(new ConverseStreamCommand({
modelId: MODEL_ID,
system: params.system,
messages: params.messages,
inferenceConfig: { maxTokens: params.maxTokens ?? 4096 },
}))
);
for await (const event of response.stream ?? []) {
if (event.contentBlockDelta?.delta?.text) yield event.contentBlockDelta.delta.text;
if (event.messageStop?.stopReason) {
console.log(`[bedrock] stream complete: ${event.messageStop.stopReason}`);
}
}
}
Wire it into an MCP server with startup validation before accepting connections:
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { validateInferenceProfile, invokeModel } from "./bedrock-client.js";
import { z } from "zod";
const server = new McpServer({ name: "my-mcp-server", version: "1.0.0" });
server.tool(
"summarize",
"Summarize a document using Claude",
{ text: z.string().describe("The text to summarize") },
async ({ text }) => {
const result = await invokeModel({
messages: [{ role: "user", content: [{ text }] }],
system: [{ text: "Summarize the input concisely." }],
maxTokens: 512,
});
return { content: [{ type: "text", text: result.text }], isError: false };
}
);
async function main() {
await validateInferenceProfile(); // fail fast before accepting tool calls
await server.connect(new StdioServerTransport());
console.log("[mcp] Server started");
}
main().catch(err => { console.error("[mcp] Fatal:", err.message); process.exit(1); });
CloudWatch monitoring for cross-region inference
Bedrock emits CloudWatch metrics for every invocation. For cross-region inference profiles, the key metrics to watch:
| Metric | Namespace | What it shows |
|---|---|---|
InvocationLatency | AWS/Bedrock | End-to-end latency; use P99 to detect cross-region routing overhead (+50–200ms on cross-region hop) |
InputTokenCount | AWS/Bedrock | Input tokens consumed; correlates with cost |
OutputTokenCount | AWS/Bedrock | Output tokens generated; primary cost driver for Claude |
InvocationClientErrors | AWS/Bedrock | 4xx errors; spikes indicate ThrottlingException or malformed requests |
InvocationServerErrors | AWS/Bedrock | 5xx errors; indicate Bedrock service issues in target regions |
The metrics are dimensioned by ModelId. For system inference profiles the dimension value is the profile ID string; for application inference profiles it is the full profile ARN. Create a CloudWatch alarm on InvocationClientErrors to alert on sustained throttling:
// CDK: alarm on sustained ThrottlingException
const throttlingAlarm = new cloudwatch.Alarm(this, "BedrockThrottlingAlarm", {
metric: new cloudwatch.Metric({
namespace: "AWS/Bedrock",
metricName: "InvocationClientErrors",
dimensionsMap: { ModelId: process.env.BEDROCK_MODEL_ID! },
statistic: "Sum",
period: Duration.minutes(1),
}),
threshold: 5,
evaluationPeriods: 3,
comparisonOperator: cloudwatch.ComparisonOperator.GREATER_THAN_THRESHOLD,
treatMissingData: cloudwatch.TreatMissingData.NOT_BREACHING,
alarmDescription: "Bedrock cross-region inference sustained throttling",
});
AliveMCP monitors the external uptime and response latency of your MCP server endpoints. When ThrottlingException-driven failures inflate tool call latency or cause tool timeout errors, AliveMCP detects the degradation from outside your AWS infrastructure — complementing internal CloudWatch metrics with an external view that reflects the actual experience of AI agents calling your tools.
When cross-region inference is not the right choice
Three scenarios where you should use a single-region model ID instead of a cross-region profile:
- Data residency requirements. If your MCP server processes PHI, PII under GDPR, or other regulated data with a strict single-country residency requirement, cross-region inference may route to a region outside the permitted boundary. Use a single-region model ID, or the
eu.profile only if EU-wide data residency is acceptable for your compliance regime. - VPC-only Bedrock access via PrivateLink. If your MCP server reaches Bedrock through a VPC interface endpoint, the outbound request still goes to your home region's endpoint, but Bedrock's internal routing may not be compatible with all PrivateLink configurations. Verify with your network team before switching production workloads.
- Models without cross-region profiles. Some foundation models — particularly third-party marketplace models and older Claude versions — do not have system inference profiles. Use
ListInferenceProfilesCommand({typeEquals:"SYSTEM_DEFINED"})to check whether a cross-region profile exists for the model you need before updating your code.
If cross-region inference still produces persistent throttling after enabling model access in all pool regions and implementing Retry-After-aware backoff, the escalation path is: (1) provisioned throughput for reserved capacity with a 1-month minimum commitment, (2) Service Quotas increase request for Requests per minute for Anthropic Claude 3.5 Sonnet v2 on-demand throughput, or (3) Bedrock Batch Inference for large asynchronous workloads with higher throughput limits than on-demand.
Model version upgrade path with application profiles
When Anthropic releases a new Claude version and you want to upgrade, application inference profiles make the upgrade a configuration change rather than a code deployment:
- Enable model access in all three US regions for the new model (e.g.,
anthropic.claude-sonnet-4-6-20251101-v1:0). - Create a new application profile copying from the new system profile ID
us.anthropic.claude-sonnet-4-6-20251101-v1:0, with the same tags as the old profile. - Update the
BEDROCK_PROFILE_ARNenvironment variable in your ECS task definition or Lambda to the new profile ARN. - Deploy. Verify in CloudWatch that invocations are routing through the new profile.
- Delete the old application profile after a few days of stable operation.
If you need a canary rollout — routing a fraction of traffic to the new model — create both profiles simultaneously and use an environment variable toggle to switch a percentage of tool call instances to the new profile ARN before full cutover.
All ten gotchas consolidated
| # | Gotcha | Symptom | Fix |
|---|---|---|---|
| 1 | Model access not enabled in all pool regions | ThrottlingException that never clears on retry | Enable model access in every region of the cross-region pool via console or CLI |
| 2 | System profiles not in ListFoundationModels | Can't find cross-region profile IDs | Use ListInferenceProfilesCommand({typeEquals:"SYSTEM_DEFINED"}) |
| 3 | IAM ARN missing geographic prefix | AccessDeniedException on every invocation | Update IAM Resource to arn:aws:bedrock:{region}::foundation-model/us.anthropic.claude-... |
| 4 | CreateInferenceProfileCommand.copyFrom takes plain model ID | ValidationException on profile creation | Pass system profile ID with prefix: "us.anthropic.claude-..." not "anthropic.claude-..." |
| 5 | Duplicate profile name | ConflictException on second create | Check for existing profile with GetInferenceProfileCommand before creating |
| 6 | Application profile IAM uses wrong ARN format | AccessDeniedException when switching from system to application profile | Add arn:aws:bedrock:{region}:{account}:application-inference-profile/* to IAM Resource |
| 7 | Ignoring Retry-After header | Throttle storm worsens on retry; config problems masked | Read err.$response?.headers?.["retry-after"], sleep that many seconds before retry |
| 8 | No startup validation | Runtime failures mid-agent-execution | Call validateInferenceProfile() before server.connect() |
| 9 | Using system profiles for cost attribution | Undifferentiated Bedrock spend in Cost Explorer | Create application inference profiles per service with environment/service/cost-center tags |
| 10 | Wrapping stream iteration in retry | Cannot retry mid-stream; partial responses silently discarded | Wrap ConverseStreamCommand connection in retry; let stream iteration errors propagate |
Pages in this arc
- Cross-Region Inference Overview — routing mechanics, model access per-region gotcha, latency tradeoffs, quick start code
- System Inference Profiles — ListInferenceProfilesCommand, available model IDs, IAM ARN format, startup validation
- Application Inference Profiles — CreateInferenceProfileCommand, cost-allocation tags, managing profile lifecycle, 100-profile quota
- MCP Tool Handler Pattern — full TypeScript with ThrottlingException retry, exponential backoff, and CloudWatch monitoring
For the core Bedrock ConverseCommand without cross-region inference, see Bedrock Converse API for MCP Servers. For Bedrock Guardrails layered on top of inference profiles, see Bedrock Guardrails. For Bedrock Batch Inference as an escalation path when on-demand throttling persists, see Bedrock Batch Inference.