← Blog

Claude API AWS Lambda Integration Tutorial

2026-11-22 · 5 min read · SubToAPI Team

If you want to call Claude from a serverless backend, AWS Lambda is a natural fit: event-driven, pay-per-invocation, and easy to wire up behind API Gateway or a Lambda Function URL. This tutorial covers the full setup — function code, environment configuration, IAM permissions, timeout tuning, and the specific gotchas that trip people up when running an LLM call inside a Lambda execution environment.

The short version: you write a Node.js (or Python) handler that makes an HTTPS POST request to the Claude API, store your key securely (env var or Secrets Manager, never hardcoded), set the Lambda timeout high enough for long completions, and decide early whether you need streaming — because standard Lambda invocations don't stream by default, and that changes your architecture.

Why run Claude behind Lambda

Common reasons teams do this:

Lambda is a good match for short-to-medium Claude calls (a few seconds to ~30s). For long streaming conversations or chat UIs, you'll want either Lambda response streaming (via Function URLs) or a different compute model entirely — more on that below.

Step 1: Create the Lambda function

Create a new Node.js 20.x function in the console or via your IaC tool of choice (SAM, CDK, Terraform). The handler itself is simple:

// index.mjs
export const handler = async (event) => {
  const body = JSON.parse(event.body || "{}");
  const userMessage = body.message || "Hello";

  const response = await fetch("https://api.anthropic.com/v1/messages", {
    method: "POST",
    headers: {
      "content-type": "application/json",
      "x-api-key": process.env.CLAUDE_API_KEY,
      "anthropic-version": "2023-06-01",
    },
    body: JSON.stringify({
      model: "claude-3-5-sonnet-latest",
      max_tokens: 1024,
      messages: [{ role: "user", content: userMessage }],
    }),
  });

  const data = await response.json();

  return {
    statusCode: 200,
    body: JSON.stringify(data),
  };
};

This works, but it ties you directly to Anthropic's native API shape and key format. If you'd rather expose a stable HTTPS endpoint with its own application-scoped key, streaming support, and usage metadata without re-implementing retries and auth yourself, you can swap the endpoint for SubToAPI and call it the same way — the request/response shape stays close to the Messages API, documented at /docs/messages.

Step 2: Store the API key properly

Never hardcode the key. Two solid options:

Environment variable (simplest):

aws lambda update-function-configuration \
  --function-name claude-handler \
  --environment "Variables={CLAUDE_API_KEY=sk-ant-xxxxx}"

AWS Secrets Manager (better for teams with rotation policies):

import { SecretsManagerClient, GetSecretValueCommand } from "@aws-sdk/client-secrets-manager";

const client = new SecretsManagerClient();

async function getApiKey() {
  const secret = await client.send(
    new GetSecretValueCommand({ SecretId: "claude-api-key" })
  );
  return JSON.parse(secret.SecretString).apiKey;
}

If you're using SubToAPI keys (sub_live_...), the same pattern applies — store it as SUBTOAPI_KEY and reference it in the Authorization header instead of x-api-key.

Step 3: IAM permissions

The Lambda execution role needs, at minimum:

That VPC+NAT detail is the single most common cause of "Lambda hangs then times out" when calling any external API, including Claude.

Step 4: Timeouts and memory

Claude completions can take several seconds depending on max_tokens and model choice. Set your Lambda timeout accordingly:

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

30 seconds is a reasonable floor for short responses; bump to 60–120s if you're generating long completions or using larger max_tokens values. Memory above 512MB rarely helps here since the function is mostly I/O-bound waiting on the HTTP response.

Step 5: Handling streaming

Standard Lambda invocations (via API Gateway REST/HTTP APIs) buffer the entire response — no token-by-token streaming. If you need streaming output:

For most webhook-driven or batch use cases, non-streaming is fine and dramatically simplifies the Lambda setup.

Step 6: Error handling and retries

Wrap the call with basic retry logic for rate limits and transient network errors:

async function callClaudeWithRetry(payload, retries = 2) {
  for (let i = 0; i <= retries; i++) {
    const res = await fetch("https://api.anthropic.com/v1/messages", {
      method: "POST",
      headers: {
        "content-type": "application/json",
        "x-api-key": process.env.CLAUDE_API_KEY,
        "anthropic-version": "2023-06-01",
      },
      body: JSON.stringify(payload),
    });
    if (res.status !== 429 && res.status < 500) return res;
    await new Promise((r) => setTimeout(r, 500 * (i + 1)));
  }
  throw new Error("Claude API call failed after retries");
}

Log status codes and latency to CloudWatch so you can spot throttling or slow responses before they become production incidents.

Step 7: Testing locally

Use AWS SAM CLI or simply invoke the handler function directly with a mock event in Node before deploying:

node -e "import('./index.mjs').then(m => m.handler({ body: JSON.stringify({ message: 'test' }) }).then(console.log))"

This catches obvious bugs (missing env vars, JSON parsing errors) before you burn a deploy cycle.

Managing keys across multiple functions

If you have several Lambda functions calling Claude — one for chat, one for summarization, one for a cron job — tracking usage and spend per function with raw Anthropic keys means building your own metering. A tool like SubToAPI gives each function its own scoped sub_live_... key, with usage and cost visible per key in one dashboard, rather than one shared key across every function. Setup is the same curl/fetch pattern shown above — just a different base URL and header, detailed in /docs/quickstart. Plans start at €9/month on the Solo tier, with team seats on the Team and Scale plans; see /pricing.

questions

Does Lambda support streaming Claude responses natively? Not through standard API Gateway integrations. Use a Lambda Function URL with RESPONSE_STREAM invoke mode, or run a persistent server for streaming use cases.

What timeout should I set for a Claude-calling Lambda? Start at 30–60 seconds for typical completions and increase if you use large max_tokens values or slower models. Always leave margin above your observed p99 latency.

Why does my Lambda hang when calling the Claude API? Usually a VPC without outbound internet access (missing NAT gateway or VPC endpoint). Functions outside a VPC, or with proper NAT/egress configured, won't have this issue.

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 →