← Blog

Claude API Lambda Integration Example (AWS Guide)

2026-10-10 · 5 min read · SubToAPI Team

Running Claude behind an AWS Lambda function is a common pattern for serverless apps, webhooks, and event-driven pipelines — you get on-demand compute without managing servers, and Claude handles the reasoning. The core integration is simple: your Lambda handler makes an HTTPS POST request to a messages endpoint, waits for the response, and returns it to whatever triggered the function (API Gateway, EventBridge, S3 events, etc.).

This article walks through a complete, working example: packaging the function, handling secrets safely, avoiding the two most common Lambda-specific failures (timeouts and cold-start latency), and a note on why a lot of teams put a thin API layer in front of Claude instead of calling it directly from inside the function.

Why Lambda + Claude is a good fit — and where it gets tricky

Lambda is stateless and short-lived, which matches well with request/response LLM calls: invoke, call Claude, return. The friction points are specific to the Lambda execution model:

None of these are blockers, but they shape how you structure the handler.

Basic setup

You need three things: the Lambda function, an API key stored in a secrets manager, and (if it's user-facing) an API Gateway or Lambda function URL in front of it.

1. Store the key securely

Don't put the key in an environment variable in plaintext for anything beyond a quick prototype. Use AWS Secrets Manager or Parameter Store:

aws secretsmanager create-secret \
  --name claude-api-key \
  --secret-string '{"CLAUDE_API_KEY":"your-key-here"}'

Grant the Lambda execution role secretsmanager:GetSecretValue on that specific secret ARN only.

2. Write the handler

Here's a minimal Node.js 20.x handler that calls a Claude-compatible messages endpoint, fetches the key from Secrets Manager on cold start, and caches it for warm invocations:

const { SecretsManagerClient, GetSecretValueCommand } =
  require("@aws-sdk/client-secrets-manager");

let cachedKey;

async function getApiKey() {
  if (cachedKey) return cachedKey;
  const client = new SecretsManagerClient({ region: process.env.AWS_REGION });
  const resp = await client.send(
    new GetSecretValueCommand({ SecretId: "claude-api-key" })
  );
  cachedKey = JSON.parse(resp.SecretString).CLAUDE_API_KEY;
  return cachedKey;
}

exports.handler = async (event) => {
  const apiKey = await getApiKey();
  const body = JSON.parse(event.body || "{}");

  const response = await fetch("https://api.subtoapi.app/v1/messages", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${apiKey}`,
    },
    body: JSON.stringify({
      model: "claude-sonnet-4-5",
      max_tokens: 1024,
      messages: [{ role: "user", content: body.prompt || "Hello" }],
    }),
  });

  if (!response.ok) {
    const errText = await response.text();
    return { statusCode: response.status, body: errText };
  }

  const data = await response.json();
  return {
    statusCode: 200,
    body: JSON.stringify({ reply: data.content }),
  };
};

The cachedKey variable lives outside the handler function so it persists across warm invocations in the same execution environment, which saves a Secrets Manager call on every request — this matters for both latency and cost.

3. Set the timeout and memory correctly

Lambda defaults to a 3-second timeout, which is too short for most LLM calls. Set it explicitly:

aws lambda update-function-configuration \
  --function-name claude-handler \
  --timeout 30 \
  --memory-size 512

If you expect longer completions (large summaries, multi-step tool use), raise the timeout to 60–90 seconds and switch your trigger from API Gateway REST to a Lambda function URL, which doesn't have the 29-second cap.

Handling streaming from Lambda

Token-by-token streaming over API Gateway REST isn't supported. If you need streaming responses in a browser or CLI client, use one of:

  1. Lambda response streaming via a function URL with InvokeMode: RESPONSE_STREAM, which supports chunked HTTP responses.
  2. Non-streaming inside Lambda, streaming outside it — have Lambda call Claude without streaming, then let a separate always-on service (not Lambda) relay a stream to the client.

Option 1 is cleaner if you're committed to serverless. Full details on request/response shapes for streaming endpoints are in the streaming docs if you're building this against SubToAPI.

Why route through an API layer instead of calling Anthropic directly

A direct call from Lambda to a raw LLM provider works, but you lose a few things that matter in production: per-application API keys (so you're not sharing one root key across every Lambda function and team member), usage breakdowns by key, and the ability to rotate a single function's access without touching every other service.

SubToAPI sits in front of your Claude access and gives each Lambda function its own sub_live_... key, with usage metadata and streaming support, while keeping the request/response shape compatible with the example above — you're changing one URL and one key, not rewriting your integration. Setup takes a few minutes; see the quickstart and messages endpoint docs for the exact request format. Plans start at €9/month on the pricing page, with a free trial at signup.

Packaging and deployment checklist

questions

Can Lambda stream Claude's response token-by-token? Not over standard API Gateway REST. Use a Lambda function URL with response streaming enabled, or handle streaming in a separate long-running service outside Lambda.

What timeout should I set for a Claude call in Lambda? Start at 30 seconds for short completions; raise to 60–90 seconds for long generations or tool use, and switch to a function URL if you exceed API Gateway's 29-second limit.

Should I store the API key as a Lambda environment variable? Avoid plaintext environment variables for production. Use AWS Secrets Manager or Parameter Store and cache the fetched value outside the handler to avoid repeated lookups on warm invocations.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →