Claude API Serverless Setup on AWS Lambda
Running the Claude API inside AWS Lambda is straightforward as long as you account for three things Lambda handles differently than a normal server: execution timeouts, streaming support, and secrets management. This guide walks through a working Node.js handler, the IAM and environment setup you need, and the specific limitations (timeouts, response streaming, cold starts) that trip people up when they move a Claude integration from a long-running server to a serverless function.
If you just want a quick answer: deploy a Lambda function behind API Gateway or a Lambda Function URL, store your API key in Secrets Manager or as an encrypted environment variable, set the function timeout to at least 60–300 seconds depending on your prompts, and either disable streaming (buffer the full response) or use a Lambda response stream with RESPONSE_STREAM invoke mode if you're on Node.js 18+ runtimes. Below is the full setup.
Why Lambda needs special handling for Claude
A typical Claude API call can take anywhere from one second (short completions) to over a minute (long generations, large context, tool use loops). Lambda's default timeout is 3 seconds — far too short. You also pay for the full Lambda execution duration, so a 45-second Claude call means 45 seconds of billed compute time, which adds up fast under load.
The other constraint is streaming. Lambda functions invoked through API Gateway REST APIs buffer the entire response before returning it — no server-sent events, no token-by-token output. If you need real token streaming, you have two realistic options: Lambda Function URLs with response streaming (Node.js/Python runtimes support this natively via awslambda.streamifyResponse), or move the streaming endpoint to a different compute target (ECS, Fargate, or a small always-on service) and keep Lambda for non-streaming batch jobs.
Basic setup: non-streaming Lambda function
This is the simplest and most reliable pattern — good for background jobs, webhooks, and API endpoints where you don't need token-by-token output.
1. Set the function timeout and memory
In the Lambda console or your IaC template, set:
- Timeout: 60–300 seconds (match your longest expected Claude call)
- Memory: 256–512 MB is usually enough; Claude calls are I/O bound, not CPU bound
2. Store your API key safely
Don't hardcode keys. Use Lambda environment variables encrypted with KMS, or pull from Secrets Manager at cold start:
import { SecretsManagerClient, GetSecretValueCommand } from "@aws-sdk/client-secrets-manager";
const client = new SecretsManagerClient({ region: process.env.AWS_REGION });
let cachedKey;
async function getApiKey() {
if (cachedKey) return cachedKey;
const result = await client.send(
new GetSecretValueCommand({ SecretId: "claude-api-key" })
);
cachedKey = JSON.parse(result.SecretString).apiKey;
return cachedKey;
}
Caching the key outside the handler avoids re-fetching it on every warm invocation.
3. The handler itself
export const handler = async (event) => {
const apiKey = await getApiKey();
const body = JSON.parse(event.body || "{}");
const response = await fetch("https://api.anthropic.com/v1/messages", {
method: "POST",
headers: {
"x-api-key": apiKey,
"anthropic-version": "2023-06-01",
"content-type": "application/json",
},
body: JSON.stringify({
model: "claude-sonnet-4-5",
max_tokens: 1024,
messages: body.messages,
}),
});
const data = await response.json();
return {
statusCode: 200,
headers: { "content-type": "application/json" },
body: JSON.stringify(data),
};
};
This works fine behind API Gateway, an ALB, or a plain Lambda Function URL.
Streaming responses from Lambda
If you need real streaming, use a Lambda Function URL with InvokeMode: RESPONSE_STREAM. Node.js runtimes expose awslambda.streamifyResponse:
export const handler = awslambda.streamifyResponse(async (event, responseStream) => {
const apiKey = await getApiKey();
const body = JSON.parse(event.body || "{}");
const upstream = await fetch("https://api.anthropic.com/v1/messages", {
method: "POST",
headers: {
"x-api-key": apiKey,
"anthropic-version": "2023-06-01",
"content-type": "application/json",
},
body: JSON.stringify({ ...body, stream: true }),
});
for await (const chunk of upstream.body) {
responseStream.write(chunk);
}
responseStream.end();
});
This only works via Function URLs, not API Gateway REST APIs (HTTP APIs and REST APIs still buffer). It also doesn't support arbitrary custom domains as cleanly as API Gateway does, so weigh that tradeoff.
Cold starts and connection reuse
Cold starts add 100–400ms for Node.js Lambdas, which is negligible next to a multi-second Claude call — don't over-optimize for this. What matters more:
- Reuse HTTP connections across invocations by initializing your fetch/HTTP client outside the handler, not inside it.
- Set
AWS_NODEJS_CONNECTION_REUSE_ENABLED=1if you're using the AWS SDK alongside raw fetch calls. - Provisioned concurrency is rarely worth the cost here — Claude's own latency dwarfs cold start time for anything but ultra-high-frequency, low-latency use cases.
Retry and timeout strategy
Lambda's hard ceiling is 15 minutes, but you should set your function timeout much lower (60–180s) and handle retries explicitly rather than letting Lambda kill the invocation mid-request. A dropped Lambda invocation due to timeout doesn't cleanly cancel the upstream Claude call — you just lose the response. Add your own timeout inside the handler using AbortController so you control the failure mode and can return a proper error to the caller instead of a generic 504.
Simplifying the setup with SubToAPI
A lot of the complexity above — key rotation, usage tracking, per-team access, request/response shaping — is infrastructure you end up building regardless of which cloud provider you're on. If you'd rather skip managing secrets rotation and usage metering yourself, SubToAPI turns your existing Claude access into a standard HTTPS API with sub_live_... application keys, so your Lambda function just calls one stable endpoint with a bearer token instead of juggling Anthropic credentials, retries, and billing logic across functions. See the quickstart for the request format, or check the streaming docs if you're deciding between buffered and streamed responses in your Lambda setup. Plans start at €9/month with a free trial — see pricing.
Minimal deployment checklist
- Timeout set to cover your longest expected Claude response (60–300s)
- API key in Secrets Manager or encrypted env vars, cached outside the handler
- Function URL with
RESPONSE_STREAMif you need token streaming, API Gateway otherwise - Internal
AbortControllertimeout shorter than the Lambda timeout itself - CloudWatch alarms on duration and error rate, since silent timeouts are the most common failure mode
FAQs
Can AWS Lambda stream Claude API responses token by token? Yes, but only through Lambda Function URLs with RESPONSE_STREAM invoke mode on supported runtimes. API Gateway (REST or HTTP APIs) always buffers the full response before returning it.
What timeout should I set for a Claude API Lambda function? Start at 60 seconds for short completions and go up to 300 seconds if you expect long generations or multi-step tool use. Always add an internal AbortController timeout slightly shorter than the Lambda timeout so you control error handling.
Is Lambda cold start a real problem for Claude API calls? Not usually. Cold starts add roughly 100–400ms, which is small compared to typical multi-second Claude response times. Focus instead on reusing HTTP connections and caching your API key outside the handler.