All posts

Lambda Web Functions: pay for the work, not the wait

Run a normal web app on Lambda without an adapter, and learn when active-CPU billing makes it cheaper than an Event Function.

  • AWS
  • Lambda
  • Serverless
  • Bedrock
  • Cost optimization

Introduction

This post is my contribution to the AWS Advent Calendar 2026: 25 Days of AWS Skills, where someone from the AWS community shares one practical AWS skill each day until Christmas.

Putting a web app on Lambda has always needed a translation layer. A request arrived as an API Gateway or function URL event, something turned it into a request your framework understood, and the response went back the same way. serverless-http and the Lambda Web Adapter exist for exactly this job.

On 12 October 2026, AWS launched Lambda Web Functions and removed that layer. You deploy the Express, Hono, FastAPI or Next.js app you already have, and Lambda puts an HTTPS endpoint in front of it.

The billing model changed as well. If you build anything that calls an LLM, that change matters more than the convenience, and most of this post is about it.

What is it?

A Web Function is a Lambda function that speaks HTTP directly. There is no handler signature and no event object. Requests reach your app as plain HTTP/1.1, and responses stream back by default.

Lambda now comes in three forms. The functions you already know are now called Event Functions. Only the name changed, so there is nothing to migrate.

Event Functions Web Functions MicroVMs
You write A handler that receives an event A web app Anything; you get a sandbox
Built for Queues, S3 events, schedules, async work Web apps, APIs, SSR, LLM streaming Running untrusted or user-generated code

The differences between Event Functions and Web Functions are bigger than the programming model:

Event Function Web Function
Concurrency per environment One request at a time Up to 128 (ceiling defaults to 64)
Compute billing Duration × configured memory Active CPU time
Memory billing Included in the duration price Memory consumed, for as long as the environment exists
Request price (us-east-1) $0.20 per million $0.30 per million
Size of an environment 128 MB to 10 GB, you choose 2 vCPUs and 2 GB, fixed
Architecture x86 or Arm Arm only
Invoked by AWS services, SDK, function URL HTTPS only
Response streaming Opt-in On by default
Deployment units Versions and aliases Revisions and endpoints
Request timeout Up to 30 minutes 3 seconds to 30 minutes, 30 seconds by default

Revisions, endpoints and environments

How an endpoint routes traffic to revisions and execution environments

  • A revision is an immutable snapshot of your code and configuration.
  • An endpoint is the HTTPS URL. It sends traffic to one revision, or splits it between two by weight.
  • An execution environment is one running copy of your app. Lambda adds and removes them with traffic, down to zero.

Runtimes

Runtime Status How your app starts
Node.js 24, Node.js 26 Supported Your code starts a server on the address in AWS_LAMBDA_HTTP_ENDPOINT
Python 3.15 Public preview Lambda runs the server and loads your ASGI or WSGI app from main:app

In Node.js, the only Lambda-specific line is the one that reads the listen address:

import express from "express";

const app = express();
app.get("/", (req, res) => res.json({ message: "Hello from a Web Function" }));

const [host, port] = (
  process.env.AWS_LAMBDA_HTTP_ENDPOINT ?? "localhost:3000"
).split(":");
app.listen(port, host);

In Python there isn’t even that. You put the app in main.py, call it app, and Lambda works out whether it is ASGI (FastAPI, Starlette) or WSGI (Flask). Django works with either.

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def hello():
    return {"message": "Hello from a Web Function"}

Python is still in preview, so it isn’t covered by the Lambda SLA yet. Keep production workloads on Node.js for now.

Other languages, unofficially

The Node.js runtime will also start something that isn’t Node. Aidan Steele showed that a one-line index.js can replace the Node process with a compiled binary from your zip file:

process.execve("/var/task/server", ["/var/task/server"], process.env);

The binary then has to do two things Node would normally do: listen on AWS_LAMBDA_HTTP_ENDPOINT, and tell the Lambda runtime API that it is ready. He did it with Go, and it should work for anything you can compile for Linux on Arm64. It relies on an undocumented endpoint, so treat it as a weekend experiment until AWS ships more runtimes.

Deploying

One command creates the Web Function, its first revision and an endpoint, and prints the URL:

aws lambda-web deploy --name my-app --code ./my-app

Run the same command again and it publishes a new revision and moves the endpoint to it. Add --regions us-east-1,eu-west-1,ap-northeast-1 and Lambda replicates the code and routes each caller to the closest Region through one global URL.

Infrastructure as code

The CLI is the quickest way to try Web Functions. For anything you keep, define them in code like the rest of your infrastructure. CloudFormation, the AWS CDK and Terraform all support them:

Tool Resources
CloudFormation AWS::Lambda::WebFunction, AWS::Lambda::WebFunctionRevision, AWS::Lambda::WebFunctionEndpoint
AWS CDK The lambda.WebFunction construct in aws-cdk-lib, which creates the function, its revision and an endpoint
Terraform aws_lambdaweb_function, aws_lambdaweb_function_revision, aws_lambdaweb_function_endpoint and aws_lambdaweb_resource_policy, from AWS provider 6.72.0

In the CDK, a Web Function with an IAM-protected endpoint looks like this:

import { Duration } from "aws-cdk-lib";
import * as lambda from "aws-cdk-lib/aws-lambda";

const api = new lambda.WebFunction(this, "ChatApi", {
  code: lambda.WebFunctionCode.fromBucket(codeBucket, "chat.zip", codeVersionId),
  runtime: lambda.WebFunctionRuntime.NODEJS_24_X,
  defaultEndpointAuth: lambda.WebFunctionAuthType.IAM_AUTH,
  timeout: Duration.minutes(2),
});

The construct has no default for defaultEndpointAuth, so you have to decide whether the endpoint is public. The CLI’s deploy command is less careful: it creates a public ApplicationManaged endpoint unless you pass --auth-type IamAuth.

Why you should learn it

You pay for work, not for waiting

Web functions, similar to AgentCore Runtime, do not charge for I/O wait. An Event Function bills every millisecond a request is open. A Web Function bills the CPU time your code actually uses, plus the memory the environment holds.

What one 3-second streaming request is billed for on each model

A request that waits three seconds for a model to finish streaming is expensive on the first model and cheap on the second.

Price (us-east-1, Arm) Event Function Web Function
Requests $0.20 per million $0.30 per million
Compute $0.0000133334 per GB-second of duration $0.0000276944 per vCPU-second of active CPU
Memory Included in compute $0.0000036667 per GB-second while the environment exists

To see what that means in practice, I priced four workloads under both models. These are estimates from the price list, not measurements. The request volumes, durations and CPU times are my assumptions. I also assumed the Web Function runs one environment all month and consumes as much memory as the Event Function is configured with.

Workload Requests / month Open for Active CPU Event Function Web Function
Agent API 1M 20 s 400 ms (2%) $133.53 $16.13
Chat endpoint (streaming) 2M 4 s 150 ms (4%) $53.73 $13.66
CRUD API on DynamoDB 20M 80 ms 15 ms (19%) $14.67 $19.06
PDF rendering 3M 400 ms 300 ms (75%) $16.60 $35.33

Monthly cost of four workloads on Event Functions and Web Functions

The two workloads that wait on a model get four to eight times cheaper. The two that don’t wait get more expensive. A vCPU-second costs about twice as much as a GB-second, and requests cost 50% more, so a Web Function only wins when your code is idle for most of each request.

Agents and chat endpoints are idle for almost all of it.

One environment serves many requests

An Event Function environment handles one request at a time, so 64 simultaneous requests need 64 environments. A Web Function environment can take all 64.

64 concurrent requests need 64 Event Function environments or one Web Function environment

That means fewer cold starts, because a burst of traffic lands on environments that are already warm. Lambda also keeps some spare capacity ahead of demand. You can’t reserve environments, though, so the first request after a quiet period still waits for a cold start.

The rest

  • Your app stays portable. The same code runs on a laptop, in a container or on Lambda.
  • Streaming needs no setup. You call res.write() and the client receives the bytes.
  • Canary releases are built in. An endpoint can split traffic between two revisions by weight, for example 90/10.
  • Multi-Region is one flag on the deploy command.

Hands-on: a streaming Bedrock endpoint

This is the workload Web Functions suit best, so it makes a good first project. The endpoint takes a prompt and streams the model’s answer back.

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

const app = express();
app.use(express.json());

// Created once per environment and shared by every concurrent request
const bedrock = new BedrockRuntimeClient({});
const MODEL_ID = process.env.MODEL_ID ?? "eu.amazon.nova-2-lite-v1:0";

app.post("/chat", async (req, res) => {
  const prompt = req.body?.prompt;
  if (!prompt) return res.status(400).json({ error: 'Missing "prompt"' });

  // Stop paying for tokens nobody is reading
  const abort = new AbortController();
  res.on("close", () => abort.abort());

  try {
    const { stream } = await bedrock.send(
      new ConverseStreamCommand({
        modelId: MODEL_ID,
        messages: [{ role: "user", content: [{ text: prompt }] }],
        inferenceConfig: { maxTokens: 512 },
      }),
      { abortSignal: abort.signal },
    );

    res.setHeader("Content-Type", "text/plain; charset=utf-8");
    for await (const chunk of stream ?? []) {
      const text = chunk.contentBlockDelta?.delta?.text;
      if (text) res.write(text);
    }
    res.end();
  } catch (error) {
    if (abort.signal.aborted) return;
    console.error(error);
    if (res.headersSent) return res.end();
    res.status(502).json({ error: "Model call failed" });
  }
});

const [host, port] = (
  process.env.AWS_LAMBDA_HTTP_ENDPOINT ?? "localhost:3000"
).split(":");
app.listen(port, host);

To run it:

  1. Create the project and save the code above as index.js:
     mkdir chat-demo && cd chat-demo
     npm init -y && npm pkg set type=module
     npm install express @aws-sdk/client-bedrock-runtime
  2. Try it locally with node index.js, then in another terminal:
     curl -N -X POST localhost:3000/chat -H 'content-type: application/json' -d '{"prompt":"Explain cold starts in two sentences"}'
  3. Deploy it: aws lambda-web deploy --name chat-demo --code .
  4. The deploy creates an execution role called awscli-lambdaweb-chat-demo. Give it permission to call bedrock:InvokeModelWithResponseStream on your model and its inference profile.
  5. Send the same curl request to the URL the deploy printed.
  6. Delete it when you’re done: aws lambda-web delete-web-function --function-name chat-demo

The deploy command creates a public endpoint by default. Anyone who finds the URL can spend your Bedrock budget, so don’t leave this one running. For anything that stays up, add --auth-type IamAuth.

What to put around it

A Web Function endpoint does one job: it accepts HTTPS requests and runs your app. A custom domain, a firewall, caching and private networking come from services you probably already use.

A production setup: users reach CloudFront with AWS WAF and an ACM certificate, Route 53 resolves the domain, CloudFront serves static assets from S3 and sends signed requests to an IamAuth endpoint, and the Web Function calls AWS APIs and resources in your VPC

In front of the endpoint:

Service What it adds How to set it up
CloudFront Custom domain, caching, HTTP/2 and HTTP/3 for viewers, compression Use an IamAuth endpoint and origin access control, so only your distribution can call it
AWS WAF Managed rules, rate limits, IP and bot rules Attach the web ACL to the CloudFront distribution. The endpoint can’t take one directly
Route 53 Your domain name An alias record that points at the distribution
ACM The TLS certificate for your domain CloudFront only uses certificates from us-east-1
S3 Static files that never need to reach your function A second CloudFront origin with its own origin access control
API Gateway Another option for a front door The endpoint stays reachable directly, so your app has to check a shared secret or token

Behind it:

Service What it’s for Worth knowing
Amazon VPC (egress network connector) Reaching RDS, ElastiCache, internal APIs, on-premises HomeRegion endpoints only. Add a NAT gateway or Elastic IPs if you need a stable outbound IP
Secrets Manager, Parameter Store Database passwords and API keys Load them at runtime instead of putting them in environment variables or the package
KMS A customer managed key for environment variables Optional. Lambda uses an AWS managed key by default
CloudWatch Logs, metrics and custom metrics Lambda’s own metrics are free. Multi-Region logs and request metrics are collected in the home Region
X-Ray Traces Not automatic. Send traces from your code, for example with the AWS Distro for OpenTelemetry
CloudTrail An audit trail Records management calls, and invocations if you turn on data events
Event Functions, SQS, EventBridge Background and queued work Web Functions only take HTTP. Hand slow work to a queue and process it with an Event Function

IAM ties it together: an execution role for what your app may call, a resource policy for who may call the endpoint, and, across an organization, a service control policy with the lambda:Request/WebFunctionAuthType condition key that blocks public endpoints entirely.

Tips and personal insights

Check the CPU share before you migrate

The cost table above comes down to one number: the share of each request your code spends on the CPU. This table shows the share below which a Web Function is cheaper, counting compute and request charges.

Request length 256 MB 512 MB 1 GB
50 ms 5% 17% 41%
200 ms 10% 22% 46%
1 s 12% 24% 48%
5 s 12% 24% 48%

The columns are the memory your Event Function is configured with. A function with more memory pays more per second of waiting, so it has more to gain. Short requests have less to gain, because the higher request price takes a bigger share of the bill.

The memory charge for the environment comes on top. At real volumes it is small, as the chart for the chat endpoint shows:

Monthly cost of the chat endpoint as the CPU share of each request grows

My rule of thumb for a 512 MB function: if your code is on the CPU for less than a fifth of each request, a Web Function is probably cheaper. Above a quarter, it probably isn’t. In between, measure. You can find the real number in your Event Function’s logs by comparing billed duration with the time spent in downstream calls.

Things that behave differently

Per-request data can’t live in global variables. One process serves many requests at once, so a module-level currentUser will leak between customers. Keep request data in the request object. For loggers and request IDs that need to reach deep into your code, use AsyncLocalStorage in Node.js.

A blocked event loop blocks everyone. Synchronous CPU work in one request delays every other request in that environment. Use async I/O, move heavy work to worker_threads, or lower maxConcurrencyPerEnvironment. In FastAPI, a plain def endpoint runs in a thread pool, which helps with blocking libraries.

Raise the timeout for model calls. The default request timeout is 30 seconds, and it covers the whole stream. When a stream hits it, Lambda cuts the response off and the client still sees a 200 with a truncated body.

“Active” doesn’t mean it works. Lambda doesn’t check that your server starts when it creates a revision. A revision and its endpoint can both show Active while every request fails. Send a real request after each deploy.

Run load tests twice. Lambda learns how many concurrent requests your app can handle and starts with a cautious limit. The first load test on a new function uses more environments than later ones.

Two CloudFront details. Don’t forward the viewer’s Host header, or the endpoint answers 404; the AllViewerExceptHostHeader origin request policy handles that. And consider removing the lambda-web-logstream response header with a response headers policy, since it names the log stream that handled the request.

Shutdown is short. Lambda drains in-flight requests, sends SIGTERM and gives you one second. Anything that must be saved belongs in the request path.

Limits worth knowing

Limit Value
Environment size 2 vCPUs, 2 GB memory, 512 MB /tmp, shared by all concurrent requests
Concurrent requests per environment 1 to 128, default ceiling 64
Environments per endpoint (maxEnvironments) Optional, 2 to 10,000 per Region
Rate limit per endpoint (rateLimit) Optional, up to 10,000 requests per second per Region
Account quota per Region 100,000 requests per second and 2,000 vCPUs, which is 1,000 environments
Startup The server must be listening within 10 seconds
Request timeout 3 seconds to 30 minutes, default 30 seconds
Request line and headers 128 KiB
Protocol HTTP/1.1 over HTTPS, no WebSockets

What the status codes mean

Lambda answers some requests before they reach your app. The lambda-web-error-type response header tells you why.

Status What happened What to do
403 Unsigned or unauthorised request to an IamAuth endpoint Sign with SigV4 and include the X-Amz-Content-SHA256 header
404 The Host header isn’t the endpoint’s domain Stop forwarding the viewer’s Host header from CloudFront
429 Rate limit, maxEnvironments or the account vCPU quota was reached Retry with backoff and jitter; these requests are not queued
503 rateLimit is 0, or Lambda is shedding load Retry, unless the error type is Platform.EndpointDisabled
504 The request ran past timeoutSeconds Raise the timeout, or make the request faster

Where to learn

Hands-on

Documentation

Wrapping up

Lambda Web Functions run the web app you already have and bill you for the CPU it uses. That makes them a good home for anything that spends its time waiting on a model, a database or another API, and a poor one for CPU-heavy work.

If you want to try one thing today, deploy the starter app, then replace it with the Bedrock endpoint above and watch the tokens stream in.

Thanks to Ihor Sasovets for organising the AWS Advent Calendar. The other days are worth reading too.