Guide · Amazon Bedrock Flows
Bedrock Flows deployment — versioning, aliases, tracing, error handling for MCP servers
Deploying Bedrock Flows to production requires understanding three systems that interact: the flow version/alias lifecycle, the streaming response error model, and the CI/CD integration points. Unlike Lambda where deployment is a single update-function-code call, promoting a Bedrock Flow change to production involves four steps: edit the flow, prepare it (async validation + snapshot), create a version (immutable integer), and update your alias to point to the new version. If you skip any step — particularly if you edit without re-preparing — the production alias continues serving the previously prepared state without error. This guide covers the full deployment lifecycle, how to read trace events from InvokeFlowCommand to diagnose node-level failures, structured error handling patterns for MCP tool handlers that wrap flows, and traffic splitting for safe rollouts.
TL;DR
The deployment sequence is: UpdateFlow → PrepareFlow → poll until status === 'Prepared' → CreateFlowVersion → UpdateFlowAlias. Never update a production alias to point to DRAFT — it uses the magic alias ID TSTALIASID internally. Enable enableTrace: true in InvokeFlowCommand for development; log flowTraceEvent events that contain trace.node.nodeName to know exactly which node was executing when an error occurred. MCP tool handlers should convert the streaming error events (accessDeniedException, throttlingException, internalServerException) into structured MCP error responses rather than letting them propagate as unhandled exceptions.
Flow deployment lifecycle
A Bedrock Flow goes through the following states during its lifecycle. Understanding which state corresponds to which API call prevents silent failures where your edits don't take effect:
| State | Meaning | Triggered by |
|---|---|---|
NotPrepared | Flow was created or edited but never prepared | CreateFlow, UpdateFlow |
Preparing | Validation and compilation in progress | PrepareFlow |
Prepared | Valid and invocable via DRAFT alias | PrepareFlow completing |
Failed | Validation found errors — check validations[] | PrepareFlow failing |
The state machine only applies to the DRAFT (working copy). Versioned snapshots are created from a Prepared flow and are always in the equivalent of Prepared state — they cannot fail or be re-prepared.
import {
BedrockAgentClient,
UpdateFlowCommand,
PrepareFlowCommand,
GetFlowCommand,
CreateFlowVersionCommand,
UpdateFlowAliasCommand,
} from '@aws-sdk/client-bedrock-agent';
const mgmt = new BedrockAgentClient({ region: 'us-east-1' });
async function deployFlowUpdate(
flowId: string,
aliasId: string,
newDefinition: FlowDefinition,
): Promise { // returns new version number
// Step 1: Edit
await mgmt.send(new UpdateFlowCommand({
flowIdentifier: flowId,
definition: newDefinition,
}));
// Step 2: Prepare (async)
await mgmt.send(new PrepareFlowCommand({ flowIdentifier: flowId }));
// Step 3: Poll until prepared
const versionReady = await pollUntilPrepared(flowId, mgmt);
if (!versionReady) throw new Error('Flow preparation failed');
// Step 4: Create immutable version snapshot
const versionResponse = await mgmt.send(new CreateFlowVersionCommand({
flowIdentifier: flowId,
description: `Deploy ${new Date().toISOString()}`,
}));
const newVersion = versionResponse.version!;
// Step 5: Update alias to new version
await mgmt.send(new UpdateFlowAliasCommand({
flowIdentifier: flowId,
aliasIdentifier: aliasId,
routingConfiguration: [
{ flowVersion: newVersion, flowVersionWeight: 1.0 },
],
}));
console.log(`Flow ${flowId} deployed to version ${newVersion} on alias ${aliasId}`);
return newVersion;
}
async function pollUntilPrepared(
flowId: string,
client: BedrockAgentClient,
timeoutMs = 120_000,
): Promise {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
const flow = await client.send(new GetFlowCommand({ flowIdentifier: flowId }));
if (flow.status === 'Prepared') return true;
if (flow.status === 'Failed') {
console.error('Flow validation errors:', flow.validations);
return false;
}
await new Promise(r => setTimeout(r, 3000));
}
throw new Error(`Flow preparation timed out after ${timeoutMs}ms`);
}
Alias traffic splitting for safe rollouts
When rolling out a significant flow change, use alias traffic splitting to route a small percentage of requests to the new version before fully promoting it. This is the same A/B testing capability available on Lambda aliases and Bedrock Agent aliases:
// Canary: send 5% to new version, 95% to current
await mgmt.send(new UpdateFlowAliasCommand({
flowIdentifier: flowId,
aliasIdentifier: productionAliasId,
routingConfiguration: [
{ flowVersion: currentVersion, flowVersionWeight: 0.95 },
{ flowVersion: newVersion, flowVersionWeight: 0.05 },
],
}));
// Monitor outputs for quality degradation...
// (use CloudWatch metrics on flow invocations, or log flowOutputEvents with version tag)
// Promote: move all traffic to new version
await mgmt.send(new UpdateFlowAliasCommand({
flowIdentifier: flowId,
aliasIdentifier: productionAliasId,
routingConfiguration: [
{ flowVersion: newVersion, flowVersionWeight: 1.0 },
],
}));
// Rollback: revert to previous version instantly
await mgmt.send(new UpdateFlowAliasCommand({
flowIdentifier: flowId,
aliasIdentifier: productionAliasId,
routingConfiguration: [
{ flowVersion: previousVersion, flowVersionWeight: 1.0 },
],
}));
Traffic weights must sum to 1.0. You can split between at most two versions — Bedrock Flows does not support multi-way splits. The routing is probabilistic per request (not per session), so a user may see different flow behavior on consecutive requests during a split deployment. For MCP servers where consistency within a session matters, avoid splits on conversational flows.
Trace events: debugging node-level failures
Enabling trace in InvokeFlowCommand causes the streaming response to include flowTraceEvent events for each node execution. These events contain the node name, its inputs, and its outputs — letting you see exactly what data was flowing through the graph when an error occurred or when the output was unexpected.
const response = await runtime.send(new InvokeFlowCommand({
flowIdentifier: flowId,
flowAliasIdentifier: aliasId,
inputs: [{ content: { document: inputData }, nodeName: 'FlowInputNode', nodeOutputName: 'document' }],
enableTrace: true, // adds flowTraceEvent events to the stream
}));
interface FlowTrace {
nodeType: string;
nodeName: string;
event: {
nodeInput?: {
fields: Array<{ name: string; value: { content?: { document: unknown } } }>;
};
nodeOutput?: {
fields: Array<{ name: string; value: { content?: { document: unknown } } }>;
};
};
}
for await (const event of response.responseStream!) {
if ('flowTraceEvent' in event) {
const trace = event.flowTraceEvent?.trace as FlowTrace | undefined;
if (trace) {
console.debug(`[TRACE] ${trace.nodeName} (${trace.nodeType})`);
if (trace.event.nodeInput) {
for (const field of trace.event.nodeInput.fields) {
console.debug(` Input ${field.name}:`, field.value.content?.document);
}
}
if (trace.event.nodeOutput) {
for (const field of trace.event.nodeOutput.fields) {
console.debug(` Output ${field.name}:`, field.value.content?.document);
}
}
}
} else if ('flowOutputEvent' in event) {
// ... collect output
} else if ('flowCompletionEvent' in event) {
// ... check completion reason
}
}
Trace events are emitted after each node completes. If the flow fails mid-execution, the last trace event shows which node was running. If a node's trace shows the correct input but no output event follows, the error occurred inside that node (Lambda error, model error, KB query error) — check CloudWatch Logs for that specific resource.
Trace adds overhead to every flow invocation. Keep it enabled in development (via environment variable check) and disabled in production, or selectively enable it for sampled requests:
const enableTrace = process.env.NODE_ENV !== 'production'
|| Math.random() < 0.01; // 1% sample in production
const response = await runtime.send(new InvokeFlowCommand({
flowIdentifier: flowId,
flowAliasIdentifier: aliasId,
inputs: [...],
enableTrace,
}));
Structured error handling in MCP tool handlers
The streaming response from InvokeFlowCommand can contain error events that are part of the stream rather than thrown exceptions. A robust MCP tool handler must handle both thrown exceptions (network errors, pre-flight validation) and in-stream error events:
import {
BedrockAgentRuntimeClient,
InvokeFlowCommand,
} from '@aws-sdk/client-bedrock-agent-runtime';
import {
AccessDeniedException,
ThrottlingException,
ValidationException,
InternalServerException,
} from '@aws-sdk/client-bedrock-agent-runtime';
type FlowResult =
| { ok: true; output: string }
| { ok: false; error: string; retryable: boolean };
async function invokeFlowSafe(
flowId: string,
aliasId: string,
input: unknown,
client: BedrockAgentRuntimeClient,
): Promise {
try {
const response = await client.send(new InvokeFlowCommand({
flowIdentifier: flowId,
flowAliasIdentifier: aliasId,
inputs: [
{ content: { document: input }, nodeName: 'FlowInputNode', nodeOutputName: 'document' },
],
}));
if (!response.responseStream) {
return { ok: false, error: 'No response stream from flow', retryable: false };
}
let output = '';
for await (const event of response.responseStream) {
if ('flowOutputEvent' in event) {
output = String(event.flowOutputEvent?.content?.document ?? '');
} else if ('flowCompletionEvent' in event) {
const reason = event.flowCompletionEvent?.completionReason;
if (reason !== 'SUCCESS') {
return {
ok: false,
error: `Flow completed with reason: ${reason}`,
retryable: false,
};
}
} else if ('accessDeniedException' in event) {
return {
ok: false,
error: `Permission denied: ${event.accessDeniedException?.message}`,
retryable: false,
};
} else if ('throttlingException' in event) {
return {
ok: false,
error: 'Request throttled — retry with backoff',
retryable: true,
};
} else if ('internalServerException' in event) {
return {
ok: false,
error: `Internal flow error: ${event.internalServerException?.message}`,
retryable: true,
};
} else if ('validationException' in event) {
return {
ok: false,
error: `Input validation error: ${event.validationException?.message}`,
retryable: false,
};
}
}
return { ok: true, output };
} catch (err) {
// Thrown exceptions: network errors, pre-flight validation, auth
if (err instanceof ThrottlingException) {
return { ok: false, error: 'Throttled', retryable: true };
}
if (err instanceof ValidationException) {
return { ok: false, error: `Validation: ${err.message}`, retryable: false };
}
if (err instanceof AccessDeniedException) {
return { ok: false, error: `Access denied: ${err.message}`, retryable: false };
}
return { ok: false, error: `Unexpected error: ${String(err)}`, retryable: false };
}
}
// In the MCP tool handler:
server.tool('run_flow', 'Run the AI analysis pipeline', { text: z.string() }, async ({ text }) => {
const result = await invokeFlowSafe(
process.env.FLOW_ID!,
process.env.FLOW_ALIAS_ID!,
text,
runtime,
);
if (!result.ok) {
return {
content: [{ type: 'text', text: `Error: ${result.error}` }],
isError: true,
};
}
return { content: [{ type: 'text', text: result.output }] };
});
CI/CD integration
Bedrock Flows can be managed via IaC (Terraform, CloudFormation) or the AWS CLI. Here is a minimal deploy script suitable for a GitHub Actions workflow that deploys flow changes on merge to main:
#!/bin/bash
# deploy-flow.sh — called from CI after main branch merge
set -euo pipefail
FLOW_ID="${BEDROCK_FLOW_ID:?must be set}"
ALIAS_ID="${BEDROCK_FLOW_ALIAS_ID:?must be set}"
REGION="${AWS_REGION:-us-east-1}"
echo "Preparing flow $FLOW_ID..."
aws bedrock-agent prepare-flow \
--flow-identifier "$FLOW_ID" \
--region "$REGION"
# Poll for completion
for i in $(seq 1 40); do
STATUS=$(aws bedrock-agent get-flow \
--flow-identifier "$FLOW_ID" \
--region "$REGION" \
--query 'status' \
--output text)
echo " status: $STATUS (attempt $i)"
if [[ "$STATUS" == "Prepared" ]]; then break; fi
if [[ "$STATUS" == "Failed" ]]; then
echo "Flow preparation FAILED. Check validations:"
aws bedrock-agent get-flow \
--flow-identifier "$FLOW_ID" \
--region "$REGION" \
--query 'validations'
exit 1
fi
sleep 5
done
if [[ "$STATUS" != "Prepared" ]]; then
echo "Timed out waiting for preparation"
exit 1
fi
# Create immutable version
VERSION=$(aws bedrock-agent create-flow-version \
--flow-identifier "$FLOW_ID" \
--description "CI deploy $(git rev-parse --short HEAD)" \
--region "$REGION" \
--query 'version' \
--output text)
echo "Created version $VERSION"
# Update alias to new version
aws bedrock-agent update-flow-alias \
--flow-identifier "$FLOW_ID" \
--alias-identifier "$ALIAS_ID" \
--routing-configuration "[{\"flowVersion\":\"$VERSION\",\"flowVersionWeight\":1.0}]" \
--region "$REGION"
echo "Alias $ALIAS_ID now points to version $VERSION"
The BEDROCK_FLOW_ID and BEDROCK_FLOW_ALIAS_ID should be stored as CI secrets and also included in your MCP server's environment config. The flow definition itself (the nodes and connections JSON) should be version-controlled — maintain it as a JSON file in your repo and use update-flow to sync it to AWS before preparing.
Flow version cleanup
Flow versions accumulate over time and each version counts against service quotas. Delete old versions that are no longer referenced by any alias:
import {
ListFlowVersionsCommand,
ListFlowAliasesCommand,
DeleteFlowVersionCommand,
} from '@aws-sdk/client-bedrock-agent';
async function deleteUnusedFlowVersions(flowId: string): Promise {
// Get all versions
const versionsResponse = await mgmt.send(new ListFlowVersionsCommand({
flowIdentifier: flowId,
}));
const allVersions = versionsResponse.flowVersionSummaries ?? [];
// Get versions in use by aliases
const aliasesResponse = await mgmt.send(new ListFlowAliasesCommand({
flowIdentifier: flowId,
}));
const versionsInUse = new Set();
for (const alias of aliasesResponse.flowAliasSummaries ?? []) {
for (const route of alias.routingConfiguration ?? []) {
if (route.flowVersion) versionsInUse.add(route.flowVersion);
}
}
// Delete versions not in use, keeping the 3 most recent regardless
const sortedVersions = allVersions.sort((a, b) =>
parseInt(b.version ?? '0') - parseInt(a.version ?? '0')
);
const toKeep = new Set(sortedVersions.slice(0, 3).map(v => v.version));
for (const version of sortedVersions) {
if (!versionsInUse.has(version.version!) && !toKeep.has(version.version!)) {
console.log(`Deleting unused version ${version.version}`);
await mgmt.send(new DeleteFlowVersionCommand({
flowIdentifier: flowId,
flowVersion: version.version!,
}));
}
}
}
Run this cleanup script as part of your deploy pipeline or as a scheduled Lambda. Attempting to delete a version that an alias currently points to will fail with ConflictException — the cleanup function above prevents this by checking aliases first.
Monitoring flow invocations
Bedrock Flows emits CloudWatch metrics automatically for each invocation. The key metrics for MCP server monitoring:
| Metric | Namespace | Use for |
|---|---|---|
InvocationCount | AWS/Bedrock/Flows | Request volume, usage trends |
InvocationLatency | AWS/Bedrock/Flows | End-to-end flow latency; alarm on p99 > SLA |
InvocationErrors | AWS/Bedrock/Flows | Error rate; alarm when > 1% of invocations fail |
InputTokenCount | AWS/Bedrock/Flows | Cost tracking — PromptNode inputs to foundation models |
OutputTokenCount | AWS/Bedrock/Flows | Cost tracking — model completions |
Metrics are dimensioned by FlowId, AliasId, and NodeName — allowing you to identify which specific node in a multi-node flow is contributing most to latency or errors. Set up CloudWatch alarms on InvocationErrors per alias so you are notified if a deployment causes a spike in error rate before it affects all users.
Flow deployment checklist
| Check | Command |
|---|---|
Flow status is Prepared before creating version |
GetFlowCommand → flow.status === 'Prepared' |
| No validation errors | GetFlowCommand → flow.validations[] is empty or all PASSED |
| New version exists before updating alias | GetFlowVersionCommand returns the version |
| Alias routing points to new version at correct weight | GetFlowAliasCommand → routingConfiguration[].flowVersion |
| Test invocation via DRAFT alias passes before version creation | Call InvokeFlowCommand with TSTALIASID and known test input |
| MCP server config updated with new flow IDs (if flow was recreated) | Update env vars / secrets; redeploy MCP server |
| CloudWatch error rate stable after alias update | Watch InvocationErrors metric for 5 minutes post-deploy |