← Blog

Claude API Serverless Function Deployment Guide

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

Deploying Claude API calls inside a serverless function means handling three problems that don't exist in a long-running server: cold starts adding latency to every request, platform timeouts cutting off long completions, and API keys needing to be stored securely without a persistent process to hold them in memory. This guide walks through deploying Claude on AWS Lambda, Vercel Functions, and Cloudflare Workers, with the configuration choices that actually matter for each.

If you just want a working endpoint without managing any of this yourself, that's the exact gap SubToAPI fills — it turns your Claude access into a hosted HTTPS API with streaming, usage metadata, and key management built in, so your serverless function makes one fetch call instead of owning the integration. The rest of this article covers how to do it yourself when you need that control.

Picking a Platform

AWS Lambda gives you the most configuration control — memory, timeout up to 15 minutes, provisioned concurrency to kill cold starts — but needs the most setup (IAM roles, API Gateway or Lambda Function URLs, deployment packaging).

Vercel Functions are the fastest path if your frontend already lives on Vercel. Edge Functions have a 25-second execution limit by default; Node.js Serverless Functions can go longer on paid plans. For Claude calls that involve streaming or long generations, check your plan's timeout before committing.

Cloudflare Workers run on V8 isolates, not containers, so cold starts are near-zero. The tradeoff is the runtime is stricter — no native Node APIs unless you opt into nodejs_compat, and CPU time (not wall time) is what's metered, which matters less for I/O-bound API calls but still caps how much JSON parsing or transformation you can do per request.

For most teams building a chat feature or an internal tool, Vercel or Cloudflare Workers are simpler to ship and debug than raw Lambda.

Core Deployment Pattern

Regardless of platform, the function itself follows the same shape: receive a request, call the model, return the response. Keep the handler thin — don't put retry logic, prompt templating, and response parsing all in one function if you can avoid it; it makes cold starts slower to initialize and failures harder to isolate.

// api/chat.js — works as a Vercel serverless function
export default async function handler(req, res) {
  const { messages } = req.body;

  const response = await fetch('https://api.subtoapi.app/v1/messages', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${process.env.SUBTOAPI_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      model: 'claude-opus-4',
      max_tokens: 1024,
      messages
    })
  });

  const data = await response.json();
  res.status(200).json(data);
}

The same pattern on Cloudflare Workers uses the fetch event instead of a Node req/res object, but the HTTP call is identical since Workers ship with a native fetch implementation.

Handling Timeouts and Streaming

This is where most serverless Claude deployments break in production. Long completions (think multi-paragraph responses or tool-calling chains) can exceed function timeouts before they finish, especially on free or hobby tiers where limits are 10 seconds or less.

Two fixes:

  1. Stream the response instead of waiting for the full completion, so the client starts receiving tokens immediately and the function doesn't need to hold the connection open until generation completes. See /docs/streaming for the event format if you're building this against SubToAPI.
  2. Cap max_tokens to a value that fits comfortably inside your platform's timeout window. A 4096-token response at typical generation speed can take well over 20 seconds — test this against your actual timeout, not an assumption.

Streaming through serverless functions has platform-specific quirks. Vercel Edge Functions support streaming responses natively via ReadableStream. Lambda requires either Lambda Function URLs with InvokeMode: RESPONSE_STREAM or a workaround through API Gateway, which doesn't support streaming at all for standard REST APIs. If streaming is a hard requirement, check this before choosing Lambda.

Managing API Keys Securely

Never hardcode an API key in the function source or commit it to the repo. Every serverless platform has an environment variable mechanism — use it, and scope secrets per environment (development, preview, production) so a staging key never touches production traffic.

# Vercel CLI
vercel env add SUBTOAPI_KEY production

# Cloudflare Workers via wrangler
wrangler secret put SUBTOAPI_KEY

If multiple functions or team members need access, don't share one key across every deployment. Issue separate keys per environment or per service so you can revoke one without rotating everything else — this is simpler to manage from a dashboard than through raw environment variable sprawl. SubToAPI's dashboard handles key issuance and usage tracking per key, which is useful once you have more than one or two serverless functions calling Claude. See /docs/quickstart for setup.

Cold Starts and Keeping Latency Down

Cold starts matter most on Lambda and Node-based serverless functions; they're close to a non-issue on Cloudflare Workers due to the isolate model. If cold starts are hurting your Lambda-based Claude integration:

Error Handling for Rate Limits and Retries

Serverless functions should handle 429s and 5xxs explicitly rather than letting them propagate as unhandled errors to the client. A simple retry with backoff, capped at two or three attempts, is enough for most transient failures without risking a timeout on its own:

async function callClaude(body, retries = 2) {
  const res = await fetch('https://api.subtoapi.app/v1/messages', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${process.env.SUBTOAPI_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(body)
  });

  if (res.status === 429 && retries > 0) {
    await new Promise(r => setTimeout(r, 500));
    return callClaude(body, retries - 1);
  }

  return res.json();
}

Full request/response schema is in /docs/messages if you're constructing the body manually.

FAQ

Can I stream Claude responses from AWS Lambda? Yes, but only through Lambda Function URLs with response streaming enabled or a container-based Lambda behind an ALB — standard API Gateway REST APIs don't support streaming responses.

Which serverless platform has the best cold start performance for Claude calls? Cloudflare Workers, because it uses V8 isolates instead of spinning up a full runtime per invocation, which keeps cold starts in the low milliseconds even under infrequent traffic.

Do I need a backend server if I'm calling Claude from serverless functions? No — a serverless function is a complete backend for API calls like this. Tools like SubToAPI (see /pricing) let you skip even the integration work by giving you a hosted endpoint your function calls directly.

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 →