Skip to content

Building Production Strands Agents on Lambda: Custom Tools, MCP, Streaming & CDK

14 minute read
Content level: Advanced
0

Hands-on guide to deploying a production Strands Agents SDK agent on AWS Lambda: custom tools (Amazon DynamoDB, Amazon S3, external APIs), Model Context Protocol (MCP) integration, response streaming, cross-Region inference, prompt caching, and AWS Cloud Development Kit (AWS CDK) infrastructure. Includes production patterns for cost control, cold starts, memory sizing, timeouts, and concurrency. Target audience: builders taking a Strands agent from prototype to production.

The Strands Agents SDK lets you build an agent in a few lines of Python: define tools with a decorator, point the agent at a model, and it runs the reason-act loop for you. The gap most teams hit isn't building the agent. It's running it in production. Where does it live? How do you give it real tools with security boundaries? How do you stream responses, control cost, and keep cold starts sane?

This guide answers those questions by deploying a multi-tool Strands agent on AWS Lambda, then hardening it with the patterns you need in production.

SDK version: The code in this guide targets strands-agents 1.55 or later (verified against 1.63.0). If you use the official Lambda layer, which bundles 1.40.0, see the Prompt Caching section below.

What You'll Build

A multi-tool Strands agent deployed on Lambda that:

  1. Looks up customer data from Amazon DynamoDB
  2. Retrieves and analyzes documents from Amazon Simple Storage Service (Amazon S3)
  3. Calls an external REST API with security guardrails
  4. Integrates Model Context Protocol (MCP) tools for extensibility

Then we'll harden it with production patterns: cross-Region inference, prompt caching, cold-start tuning, memory sizing, timeouts, and concurrency controls.

Architecture

Architecture Diagram: Client → API Gateway → Lambda (Strands Agent with tools) → Bedrock + DynamoDB + S3 + External API

The architecture is straightforward:

Client → Amazon API Gateway → Lambda (Python 3.12, ARM64) → Amazon Bedrock (large language model)

Inside the Lambda function, the Strands agent has access to:

  • customer_lookup tool → DynamoDB
  • get_document tool → S3
  • http_api_call tool → External REST API
  • MCP tools (optional) → Any MCP-compatible server

For streaming responses, a separate Node.js Lambda function with a function URL uses awslambda.streamifyResponse() to push tokens to the client as they arrive from Bedrock.

Build It: Tools → Handler → Infrastructure

Custom Tools with the @tool Decorator

Strands tools use the @tool decorator. Type hints become the JSON schema, and docstrings become the description. There's no OpenAPI spec and no separate Lambda function per tool.

Tool 1: DynamoDB Customer Lookup

import os
import boto3
from strands import tool

dynamodb = boto3.resource("dynamodb")
table = dynamodb.Table(os.environ.get("CUSTOMERS_TABLE", "Customers"))

@tool
def customer_lookup(customer_id: str, include_orders: bool = True) -> str:
    """Look up customer details by ID from the database.

    Args:
        customer_id: The unique customer identifier (e.g., 'C-001').
        include_orders: Whether to include recent order history.
    """
    response = table.get_item(Key={"customer_id": customer_id})
    item = response.get("Item")

    if not item:
        return f"No customer found with ID: {customer_id}"

    if not include_orders:
        item.pop("recent_orders", None)

    return str(item)

That's it. The decorator handles schema generation, input validation, and response formatting, with no separate spec or config to maintain.

Tool 2: S3 Document Retriever with Cost Control

import os
import boto3
from strands import tool

s3 = boto3.client("s3")
_default_bucket = os.environ.get("DOCUMENTS_BUCKET", "agent-documents")

@tool
def get_document(key: str, bucket: str = "", max_chars: int = 4000) -> str:
    """Retrieve a document from S3 for analysis.

    Args:
        key: S3 object key (path to the file).
        bucket: S3 bucket name. Uses default documents bucket if empty.
        max_chars: Maximum characters to return (default: 4000). Prevents token explosion.
    """
    target_bucket = bucket or _default_bucket

    response = s3.get_object(Bucket=target_bucket, Key=key)
    content = response["Body"].read().decode("utf-8", errors="replace")

    # Cost control pattern: truncate large files
    if len(content) > max_chars:
        return (
            f"[Truncated to {max_chars} chars. Full size: {len(content)}]\n\n"
            + content[:max_chars]
        )

    return content

The max_chars parameter with truncation is a production cost-control pattern. Without it, a single 50 KB CSV would consume your entire token budget. It's a guardrail you own directly; the companion cost guide covers the full set.

Tool 3: External API with Security Guardrails

import os
import json
import urllib.request
from strands import tool

_base_url = os.environ.get("EXTERNAL_API_BASE_URL", "https://api.example.com/v1")
_api_key = os.environ.get("EXTERNAL_API_KEY", "")  # In production, load from AWS Secrets Manager

# Security: allowlist prevents the LLM from calling arbitrary endpoints
_ALLOWED_ENDPOINTS = frozenset([
    "/pricing/current",
    "/inventory/check",
    "/shipping/track",
])

@tool
def http_api_call(endpoint: str, method: str = "GET", params: str = "") -> str:
    """Call an external REST API for real-time data.

    Args:
        endpoint: API path. Allowed: /pricing/current, /inventory/check, /shipping/track.
        method: HTTP method (GET or POST).
        params: JSON-encoded query parameters or request body.
    """
    if endpoint not in _ALLOWED_ENDPOINTS:
        return f"Endpoint '{endpoint}' not allowed."

    url = f"{_base_url}{endpoint}"
    headers = {"Authorization": f"Bearer {_api_key}"}

    request = urllib.request.Request(url, headers=headers, method=method)
    with urllib.request.urlopen(request, timeout=10) as response:
        return f"[HTTP {response.status}] {response.read().decode()}"

The endpoint allowlist is a security pattern that prevents the large language model (LLM) from calling arbitrary URLs. The allowlist is enforced in your own code, so the model can never reach a URL you didn't sanction.

Lambda Handler with Cost Controls

import os
import time
from strands import Agent
from strands.models import BedrockModel
from tools import customer_lookup, get_document, http_api_call

SYSTEM_PROMPT = """You are a customer support agent. You can:
1. Look up customer information
2. Retrieve and analyze documents
3. Call external APIs for real-time data

Rules:
- Never make more than 5 tool calls per request (cost control)
- If you cannot answer in 3 steps, ask the user for clarification
- Always cite which tool provided the data
"""

# Model at module level: reused across warm invocations
model = BedrockModel(
    model_id="us.anthropic.claude-sonnet-4-6",
    max_tokens=1024,  # Cap output tokens (cost control)
)

def handler(event, context):
    start = time.time()

    agent = Agent(
        model=model,
        system_prompt=SYSTEM_PROMPT,
        tools=[customer_lookup, get_document, http_api_call],
    )

    response = agent(event.get("prompt", ""))

    return {
        "response": str(response),
        "latency_ms": int((time.time() - start) * 1000),
        "remaining_time_ms": context.get_remaining_time_in_millis(),
    }

A note on the model ID: us.anthropic.claude-sonnet-4-6 is a cross-Region inference profile, not a single-Region model. The us. prefix lets Bedrock route each request across the US Regions in the profile to maximize throughput and availability during demand spikes. To see the exact destination Regions, check the Regional availability section of the model's card in the Bedrock documentation. There's no extra routing charge: you're billed at the rate of the Region you call from, and all traffic stays on the AWS network. Use it as your default for production. Requests are logged in AWS CloudTrail under additionalEventData.inferenceRegion if you need to see where they ran.

Production patterns in this handler:

PatternWhat it does
Model at module levelReused across warm Lambda invocations, so the Bedrock client isn't re-created on every request
max_tokens=1024Hard cap on output tokens per call (prevents runaway generation)
Tool call limits in system promptSoft guardrail against agent loops
Latency tracking in responseEnables monitoring and alerting

MCP Integration on Lambda

If you have MCP servers (for database access, documentation search, and so on), Strands integrates them with proper Lambda lifecycle management:

from mcp.client.streamable_http import streamablehttp_client
from strands import Agent
from strands.tools.mcp import MCPClient

def handler(event, context):
    mcp_client = MCPClient(
        lambda: streamablehttp_client("https://your-mcp-server.example.com/mcp")
    )

    # Context manager = clean connection per invocation
    with mcp_client:
        mcp_tools = mcp_client.list_tools_sync()
        agent = Agent(
            model=model,  # Same module-level BedrockModel as the handler above
            tools=[customer_lookup, get_document, http_api_call] + mcp_tools,
        )
        response = agent(event["prompt"])

    return {"response": str(response)}

The with block ensures the MCP connection is opened and closed per invocation. This matters because Lambda execution environments are reused: without proper cleanup, you'd leak connections across unrelated requests. Pass model=model explicitly. Without it, the agent falls back to the Strands default model instead of the one you configured.

CDK Infrastructure

import * as cdk from "aws-cdk-lib";
import * as lambda from "aws-cdk-lib/aws-lambda";
import * as iam from "aws-cdk-lib/aws-iam";
import * as dynamodb from "aws-cdk-lib/aws-dynamodb";
import * as s3 from "aws-cdk-lib/aws-s3";
import { Construct } from "constructs";

export class AgentStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    const table = new dynamodb.Table(this, "Customers", {
      tableName: "Customers",
      partitionKey: { name: "customer_id", type: dynamodb.AttributeType.STRING },
      billingMode: dynamodb.BillingMode.PAY_PER_REQUEST,
    });

    const documents = new s3.Bucket(this, "AgentDocuments", {
      blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
      enforceSSL: true,
    });

    // Official Strands Lambda layer (version 2 bundles strands-agents 1.40.0)
    const strandsLayer = lambda.LayerVersion.fromLayerVersionArn(
      this, "StrandsLayer",
      `arn:aws:lambda:${this.region}:856699698935:layer:strands-agents-py3_12-aarch64:2`
    );

    const agentFn = new lambda.Function(this, "AgentFn", {
      runtime: lambda.Runtime.PYTHON_3_12,
      architecture: lambda.Architecture.ARM_64,  // 20% cheaper than x86_64
      handler: "agent_handler.handler",
      code: lambda.Code.fromAsset("../packaging/app.zip"),
      layers: [strandsLayer],
      memorySize: 1024,                  // Sweet spot for agent workloads
      timeout: cdk.Duration.seconds(60), // Agents need time to think
      environment: {
        CUSTOMERS_TABLE: table.tableName,
        DOCUMENTS_BUCKET: documents.bucketName,
      },
    });

    // Least-privilege Bedrock access: the inference profile, plus the
    // foundation model in any Region, but only when called through that profile
    const profileArn =
      `arn:aws:bedrock:${this.region}:${this.account}:inference-profile/us.anthropic.claude-sonnet-4-6`;
    const bedrockActions = ["bedrock:InvokeModel", "bedrock:InvokeModelWithResponseStream"];

    agentFn.addToRolePolicy(new iam.PolicyStatement({
      actions: bedrockActions,
      resources: [profileArn],
    }));
    agentFn.addToRolePolicy(new iam.PolicyStatement({
      actions: bedrockActions,
      resources: ["arn:aws:bedrock:*::foundation-model/anthropic.claude-sonnet-4-6"],
      conditions: { StringEquals: { "bedrock:InferenceProfileArn": profileArn } },
    }));

    table.grantReadData(agentFn);
    documents.grantRead(agentFn);
    agentFn.addFunctionUrl({ authType: lambda.FunctionUrlAuthType.AWS_IAM });
  }
}

Key infrastructure decisions:

  • ARM64 (AWS Graviton): 20% cheaper than x86_64, with comparable performance for Python
  • 1024 MB memory: the sweet spot (more vCPU helps tool execution; Bedrock latency dominates beyond this)
  • 60 s timeout: agents chain 3–5 tool calls, each taking 1–3 seconds plus LLM thinking time
  • Official Strands layer: pre-built and the fastest way to start (see the SDK version note under Prompt Caching)
  • Scoped AWS Identity and Access Management (IAM) policy: the role can invoke only this model, and only through the us. inference profile. A cross-Region profile needs permission on the profile ARN and on the foundation model in each destination Region, which the condition handles without hardcoding Regions.
  • Function URL with AWS_IAM auth: callers must sign requests with SigV4, so the URL isn't open to the internet

Streaming Responses

Lambda response streaming (Node.js) pushes tokens to the client in real time:

import { BedrockRuntimeClient, InvokeModelWithResponseStreamCommand }
  from "@aws-sdk/client-bedrock-runtime";

const bedrock = new BedrockRuntimeClient({ region: "us-east-1" });

export const handler = awslambda.streamifyResponse(
  async (event, responseStream, context) => {
    const { prompt } = JSON.parse(event.body);

    const command = new InvokeModelWithResponseStreamCommand({
      modelId: "us.anthropic.claude-sonnet-4-6",
      body: JSON.stringify({
        anthropic_version: "bedrock-2023-05-31",
        max_tokens: 4096,
        messages: [{ role: "user", content: prompt }],
      }),
    });

    const response = await bedrock.send(command);

    for await (const event of response.body) {
      if (event.chunk) {
        const chunk = JSON.parse(new TextDecoder().decode(event.chunk.bytes));
        if (chunk.type === "content_block_delta" && chunk.delta?.text) {
          responseStream.write(chunk.delta.text);
        }
      }
    }

    responseStream.end();
  }
);

Deploy this function with a function URL configured for RESPONSE_STREAM invoke mode, and give its role the same two Bedrock policy statements as agentFn. Without streaming, users stare at a blank screen for 5–30 seconds while the agent thinks.

Note: this streaming snippet calls Bedrock's InvokeModelWithResponseStream directly. That's a lower-level path than the Strands agent loop, used to stream raw tokens for a chat UI. Use it for the final user-facing response, and keep the Strands agent for the tool-calling logic.

Production Concerns

Cold Starts

Cold Start Comparison Bar Chart: Official Layer ~3-5s, Custom Layer ~4-6s, Container Image ~6-10s

Deployment MethodCold Start (1024 MB, indicative)Notes
Official Strands Layer~3–5 sFastest iteration; base SDK only
Custom Layer + App ZIP~4–6 sFull control; watch the 250 MB unzipped limit
Container Image (Amazon ECR)~6–10 sUnlimited deps; use for large packages

These ranges are indicative. Your numbers depend on package size and what you import at module load. Measure your own from the Init Duration field in the Lambda REPORT log line.

Recommendation: Start with the official layer. Move to a custom layer when you need a newer SDK version or extra packages, and to a container image (stored in Amazon Elastic Container Registry, Amazon ECR) when your dependency tree exceeds 250 MB unzipped.

Memory Sizing

Memory vs Latency Chart: Line chart showing 1024MB as the sweet spot where latency flattens but cost keeps rising

MemoryIndicative Agent LatencyCost per second (ARM64)Verdict
512 MB8–15 s$0.0000067Too slow for multi-tool chains
1024 MB4–8 s$0.0000133Default. Best price/performance.
2048 MB3–6 s$0.0000267Diminishing returns (Bedrock is the bottleneck)

The latency difference between 1024 MB and 2048 MB is mostly in tool execution (boto3 calls, HTTP requests), not in the Bedrock API call. Because Bedrock latency dominates total execution time, going above 1024 MB offers diminishing returns. Use AWS Lambda Power Tuning to find the right setting for your own workload.

Timeout Strategies

StrategyTimeout LimitBest For
API Gateway REST API → Lambda29 s by default (configurable from 50 ms to 29 s). For Regional and private REST APIs you can request a quota increase above 29 s, which may lower your account-level throttle quota.Simple, single-turn queries
Lambda function URLUp to the function timeout (max 15 min)Multi-step agent workflows
Async (Amazon SQS → Lambda)Up to the function timeout (max 15 min)Complex background processing
Response streaming (function URL)Up to the function timeout (max 15 min). Streaming removes the wait for a buffered response, not the timeout itself.Chat interfaces

For production chat, use a Lambda function URL with response streaming. Users see tokens as soon as they're generated, and you aren't bound by API Gateway's default 29-second integration timeout. The function's own timeout (up to 15 minutes) still applies.

Concurrency

StrategyCold StartsCostUse When
On-demandYesLowest baselineDev, low traffic
Reserved (10)Yes, boundedSame per-invokeProtect downstream services
Provisioned (5)EliminatedHigher baselineSLA-bound production

Start with reserved concurrency of 10. This keeps your agent from overwhelming your DynamoDB table or external API during traffic spikes.

Prompt Caching for Repeated Context

Agents resend the same system prompt and tool definitions on every turn. Bedrock prompt caching lets you cache that static prefix, so repeated calls read it at a reduced token rate instead of reprocessing it. Strands wires this in through CacheConfig:

from strands import Agent
from strands.models import BedrockModel, CacheConfig
from tools import customer_lookup, get_document, http_api_call

model = BedrockModel(
    model_id="us.anthropic.claude-sonnet-4-6",
    max_tokens=1024,
    # "auto" caches the system prompt by default; tools_ttl=True also caches tool definitions
    cache_config=CacheConfig(strategy="auto", tools_ttl=True),
)

def handler(event, context):
    agent = Agent(
        model=model,
        system_prompt=SYSTEM_PROMPT,
        tools=[customer_lookup, get_document, http_api_call],
    )
    response = agent(event["prompt"])

    # Inspect cache activity
    usage = response.metrics.accumulated_usage
    print(usage.get("cacheReadInputTokens", 0), usage.get("cacheWriteInputTokens", 0))

    return {"response": str(response)}

SDK version note: tools_ttl and automatic system-prompt caching were added in strands-agents 1.55. Version 2 of the official Strands Lambda layer bundles 1.40.0, which predates them. Passing tools_ttl there raises a TypeError. To use the code above, package strands-agents>=1.55 in your own dependencies layer or container image. If you stay on the official layer, use CacheConfig(strategy="auto") on its own; in 1.40 that caches the conversation history rather than the system prompt. See Strands: Amazon Bedrock prompt caching for the full option set.

What to know: Caching applies per model. Claude Sonnet 4.6 needs at least 1,024 tokens per checkpoint, and Claude Haiku 4.5 at least 4,096. Cached entries expire after 5 minutes without a hit by default (some models also offer a 1-hour TTL at a higher write rate). Cache reads are much cheaper than standard input tokens, and cache writes cost slightly more, so caching pays off only when the same prefix is reused within the TTL. Check the cache fields in the model response to confirm you're getting hits. Caching also works with cross-Region inference, although at times of high demand it can cause more cache writes. See the Bedrock prompt caching documentation for per-model limits.

Wrapping Up

You now have a Strands agent running on Lambda with real tools, MCP extensibility, streaming, and the production controls that keep it fast and predictable at scale: cross-Region inference, prompt caching, cold-start and memory tuning, timeouts, and concurrency.

Agentic workloads have one failure mode that deserves its own treatment: cost. A single prompt can fan out into many model calls and tool executions. For the formulas, anti-patterns, and guardrails to keep that under control, see the companion guide: The Hidden Cost of Agentic AI on Serverless: A Cost Engineering Guide.

References