Most tutorials for building an AI chat app start by spinning up a Node.js or Python backend server, configuring Docker, and babysitting an EC2 instance or container service.
You don't need any of that.
Combining a static HTML frontend with an Amazon API Gateway WebSocket API and AWS Lambda gives you real-time, bidirectional user interaction and token-by-token LLM streaming—with zero servers to manage, automatic scaling to zero when idle, and near-\$0 running costs.
In this step-by-step guide, you'll build and deploy a complete serverless streaming AI chat app on AWS using:
- Amazon S3 + CloudFront for static HTML hosting
-
Amazon API Gateway (WebSocket API) for persistent bidirectional
wss://connections - AWS Lambda (Python 3.12) for connection lifecycle and token streaming
- Amazon DynamoDB for tracking active WebSocket connections
- Amazon Bedrock (Amazon Nova Micro) for ultra-fast, low-cost LLM inference
The Honest Truth About Using a "Free" LLM on AWS
Before writing a single line of code, let's clear up a common misconception about AWS AI pricing:
- Your infrastructure is Free Tier eligible: S3, CloudFront, API Gateway WebSockets, AWS Lambda, and DynamoDB all offer generous AWS Free Tier allowances. For side projects, demos, and low-traffic apps, your infrastructure bill is typically \$0/month.
-
Amazon Bedrock has no permanently free token tier: Unlike some third-party playgrounds, Bedrock bills per input/output token from your first call. However:
- New AWS accounts receive promotional Free Tier credits (typically \$100–\$200 usable for up to 6 months), which can cover Bedrock testing at \$0 out of pocket.
- By choosing Amazon Nova Micro (
amazon.nova-micro-v1:0), AWS's fastest and most economical text model, even uncredited testing costs fractions of a cent per conversation.
Best of all, we'll use Bedrock's unified ConverseStream API—so if you ever want to switch to Meta Llama or Anthropic Claude, it's a one-line environment variable change.
Architecture Overview
Standard REST APIs force users to stare at a loading spinner until the LLM finishes generating its entire answer—and long responses easily hit gateway timeouts.
With API Gateway WebSockets, the browser keeps a persistent connection open. As Amazon Bedrock streams tokens to AWS Lambda, Lambda immediately pushes each chunk back through API Gateway to the browser in real time.
How a Message Flows End-to-End
-
Static Load (HTTPS): The user's browser loads
index.htmlfrom Amazon S3 (fronted by CloudFront). -
WebSocket Handshake (
wss://): The browser opens a persistent WebSocket connection to API Gateway. The$connectLambda saves the user'sconnectionIdto DynamoDB. -
Send Prompt: When the user submits a message, the browser sends a JSON frame with
"action": "sendMessage". API Gateway routes it to thews-send-messageLambda. -
Stream Tokens from Bedrock: Lambda calls
bedrock-runtime.converse_stream()using Amazon Nova Micro. -
Push Chunks Live: For every
contentBlockDeltaevent from Bedrock, Lambda callsapigatewaymanagementapi.post_to_connection()to push the text chunk straight to the browser, finishing with a{"type": "done"}event. -
Cleanup on Exit: When the user closes the tab,
$disconnectdeletes theconnectionIdfrom DynamoDB.
AWS Services at a Glance
| Service | Purpose | Cost Profile |
|---|---|---|
| Amazon S3 + CloudFront | Hosts static index.html over HTTPS |
AWS Free Tier eligible |
| API Gateway (WebSocket) | Manages persistent wss:// connections |
1M messages & 750K connection-mins/mo (Free Tier) |
| AWS Lambda (Python 3.12) | Runs $connect, $disconnect, and streaming logic |
1M requests/mo always free |
| Amazon DynamoDB | Stores active connectionId records + TTL |
25 GB storage + generous on-demand Free Tier |
| Amazon Bedrock | Serverless LLM inference (amazon.nova-micro-v1:0) |
Pay-per-token (covered by new-account AWS credits) |
| IAM & CloudWatch Logs | Least-privilege security & execution logs | Free IAM / 5 GB CloudWatch Free Tier |
Prerequisites
- An AWS account
-
AWS CLI v2 installed and configured (
aws configure) - Python 3.12 (only needed locally if you want to test; Lambda runs Python 3.12 natively)
- We'll use
us-east-1throughout this tutorial (Amazon Nova Micro is available there).
Create a working folder on your machine so everything stays organized:
mkdir aws-serverless-llm-chat
cd aws-serverless-llm-chat
Step 1: Verify Amazon Nova Micro Access in Amazon Bedrock
- Open the Amazon Bedrock console in
us-east-1. - Go to Model catalog (or Model access) in the left sidebar.
- Confirm Amazon Nova Micro (
amazon.nova-micro-v1:0) is available in your account. First-party Amazon Nova models generally have instant access.
You can quickly verify access from your terminal:
aws bedrock list-foundation-models \
--region us-east-1 \
--by-provider Amazon \
--query "modelSummaries[?contains(modelId, 'nova-micro')].modelId"
You should see "amazon.nova-micro-v1:0" in the output.
Step 2: Create the DynamoDB Table for Active Connections
Create an on-demand DynamoDB table called WebSocketConnections to store each client's connectionId:
aws dynamodb create-table \
--table-name WebSocketConnections \
--attribute-definitions AttributeName=connectionId,AttributeType=S \
--key-schema AttributeName=connectionId,KeyType=HASH \
--billing-mode PAY_PER_REQUEST \
--region us-east-1
Enable TTL (Time to Live) on the ttl attribute so abandoned connections clean themselves up automatically:
aws dynamodb update-time-to-live \
--table-name WebSocketConnections \
--time-to-live-specification "Enabled=true, AttributeName=ttl" \
--region us-east-1
Step 3: Create a Least-Privilege IAM Role for Lambda
Our Lambda functions need permission to:
- Write execution logs to CloudWatch Logs
- Read/write connection IDs in DynamoDB
- Call
bedrock:InvokeModelWithResponseStreamon Amazon Nova Micro - Push messages back to connected browsers via
execute-api:ManageConnections
First, grab your 12-digit AWS Account ID:
ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
echo $ACCOUNT_ID
Create trust-policy.json:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": { "Service": "lambda.amazonaws.com" },
"Action": "sts:AssumeRole"
}
]
}
Create the role and attach the basic CloudWatch logging policy:
aws iam create-role \
--role-name ServerlessLLMWebSocketRole \
--assume-role-policy-document file://trust-policy.json
aws iam attach-role-policy \
--role-name ServerlessLLMWebSocketRole \
--policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
Now create lambda-permissions.json (replace <ACCOUNT_ID> with your Account ID):
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "DynamoDBConnectionsAccess",
"Effect": "Allow",
"Action": [
"dynamodb:PutItem",
"dynamodb:DeleteItem"
],
"Resource": "arn:aws:dynamodb:us-east-1:<ACCOUNT_ID>:table/WebSocketConnections"
},
{
"Sid": "BedrockNovaMicroStream",
"Effect": "Allow",
"Action": [
"bedrock:InvokeModelWithResponseStream"
],
"Resource": "arn:aws:bedrock:us-east-1::foundation-model/amazon.nova-micro-v1:0"
},
{
"Sid": "ApiGatewayManageConnections",
"Effect": "Allow",
"Action": [
"execute-api:ManageConnections"
],
"Resource": "arn:aws:execute-api:us-east-1:<ACCOUNT_ID>:*/prod/POST/@connections/*"
}
]
}
Security Tip: After Step 5 gives you your exact
<API_ID>, tighten theApiGatewayManageConnectionsresource ARN by replacing*with your<API_ID>.
Attach the inline policy:
aws iam put-role-policy \
--role-name ServerlessLLMWebSocketRole \
--policy-name ServerlessLLMInlinePolicy \
--policy-document file://lambda-permissions.json
Step 4: Write and Deploy the 3 AWS Lambda Functions
We'll create three small, focused Python 3.12 Lambda functions.
4.1 connect.py ($connect route)
Runs whenever a user opens the chat page and establishes a WebSocket connection.
import os
import time
import boto3
dynamodb = boto3.resource("dynamodb")
table = dynamodb.Table(os.environ["CONNECTIONS_TABLE"])
def lambda_handler(event, context):
connection_id = event["requestContext"]["connectionId"]
table.put_item(
Item={
"connectionId": connection_id,
"ttl": int(time.time()) + 7200, # Auto-expire after 2 hours
}
)
return {"statusCode": 200, "body": "Connected"}
4.2 disconnect.py ($disconnect route)
Runs when the browser closes or drops the connection.
import os
import boto3
dynamodb = boto3.resource("dynamodb")
table = dynamodb.Table(os.environ["CONNECTIONS_TABLE"])
def lambda_handler(event, context):
connection_id = event["requestContext"]["connectionId"]
table.delete_item(Key={"connectionId": connection_id})
return {"statusCode": 200, "body": "Disconnected"}
4.3 send_message.py (sendMessage route)
This is the core of the application. It parses the incoming chat history, invokes Amazon Bedrock converse_stream, and streams every token delta back to the browser via post_to_connection.
import json
import os
import boto3
from botocore.exceptions import ClientError
REGION = os.environ.get("AWS_REGION", "us-east-1")
MODEL_ID = os.environ.get("MODEL_ID", "amazon.nova-micro-v1:0")
bedrock = boto3.client("bedrock-runtime", region_name=REGION)
def post_json(apigw_client, connection_id, payload):
"""Push a JSON frame back to the connected WebSocket client."""
apigw_client.post_to_connection(
ConnectionId=connection_id,
Data=json.dumps(payload).encode("utf-8"),
)
def lambda_handler(event, context):
connection_id = event["requestContext"]["connectionId"]
domain = event["requestContext"]["domainName"]
stage = event["requestContext"]["stage"]
# Build the Management API client dynamically from the WebSocket request context
apigw = boto3.client(
"apigatewaymanagementapi",
endpoint_url=f"https://{domain}/{stage}",
)
try:
body = json.loads(event.get("body") or "{}")
messages = body.get("messages")
# Support either a multi-turn "messages" array or a single "prompt" string
if not messages:
prompt = (body.get("prompt") or "").strip()
if not prompt:
post_json(apigw, connection_id, {"type": "error", "message": "Prompt cannot be empty."})
return {"statusCode": 400, "body": "Empty prompt"}
messages = [{"role": "user", "content": [{"text": prompt}]}]
# Call Amazon Bedrock's unified ConverseStream API
response = bedrock.converse_stream(
modelId=MODEL_ID,
system=[{"text": "You are a helpful, concise technical assistant."}],
messages=messages,
inferenceConfig={
"maxTokens": 1024,
"temperature": 0.7,
},
)
# Forward every token chunk to the browser immediately as it arrives
for event_chunk in response.get("stream", []):
if "contentBlockDelta" in event_chunk:
text = event_chunk["contentBlockDelta"]["delta"].get("text", "")
if text:
post_json(apigw, connection_id, {"type": "chunk", "text": text})
# Signal that the stream has finished
post_json(apigw, connection_id, {"type": "done"})
return {"statusCode": 200, "body": "Stream complete"}
except apigw.exceptions.GoneException:
# User closed their browser tab mid-stream — exit cleanly
return {"statusCode": 410, "body": "Client disconnected"}
except ClientError as exc:
err_msg = exc.response["Error"]["Message"]
post_json(apigw, connection_id, {"type": "error", "message": err_msg})
return {"statusCode": 500, "body": err_msg}
Deploy the Lambda Functions
Package and deploy all three functions with the AWS CLI (or paste the code directly into the AWS Lambda Console):
ROLE_ARN="arn:aws:iam::${ACCOUNT_ID}:role/ServerlessLLMWebSocketRole"
zip connect.zip connect.py
zip disconnect.zip disconnect.py
zip send_message.zip send_message.py
aws lambda create-function \
--function-name ws-connect \
--runtime python3.12 \
--role "$ROLE_ARN" \
--handler connect.lambda_handler \
--zip-file fileb://connect.zip \
--environment "Variables={CONNECTIONS_TABLE=WebSocketConnections}" \
--region us-east-1
aws lambda create-function \
--function-name ws-disconnect \
--runtime python3.12 \
--role "$ROLE_ARN" \
--handler disconnect.lambda_handler \
--zip-file fileb://disconnect.zip \
--environment "Variables={CONNECTIONS_TABLE=WebSocketConnections}" \
--region us-east-1
aws lambda create-function \
--function-name ws-send-message \
--runtime python3.12 \
--role "$ROLE_ARN" \
--handler send_message.lambda_handler \
--zip-file fileb://send_message.zip \
--timeout 30 \
--memory-size 256 \
--environment "Variables={MODEL_ID=amazon.nova-micro-v1:0}" \
--region us-east-1
Important: Notice
--timeout 30onws-send-message. Lambda's default 3-second timeout will cut off LLM responses mid-sentence!
Step 5: Create the Amazon API Gateway WebSocket API
The quickest way to wire up the routes (and automatically grant API Gateway permission to invoke your Lambdas) is in the AWS Console:
- Open Amazon API Gateway → Create API → WebSocket API → Build.
- Set:
-
API name:
ServerlessLLMChatAPI -
Route selection expression:
$request.body.action
-
API name:
- Under Add routes:
- Add
$connectand$disconnect. - Click Add custom route and enter
sendMessage.
- Add
- Under Attach integrations, choose Lambda for each route:
-
$connect→ws-connect -
$disconnect→ws-disconnect -
sendMessage→ws-send-message
-
- Set the stage name to
prodand click Create and deploy. - On the Stages → prod page, copy your WebSocket URL:
wss://<your-api-id>.execute-api.us-east-1.amazonaws.com/prod
Step 6: Build and Host the Static HTML Frontend
Now let's build a sleek, dependency-free index.html file. No React, no bundler, no node_modules—just clean HTML, CSS, and the browser's built-in WebSocket API.
Replace YOUR_WEBSOCKET_URL with the wss://... URL from Step 5:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Serverless AWS Streaming LLM Chat</title>
<style>
:root {
--bg: #0f172a;
--panel: #1e293b;
--text: #f8fafc;
--muted: #94a3b8;
--user: #2563eb;
--bot: #334155;
--border: #475569;
--ok: #22c55e;
--warn: #f59e0b;
}
* { box-sizing: border-box; }
body {
margin: 0;
font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
background: var(--bg);
color: var(--text);
display: flex;
flex-direction: column;
height: 100vh;
}
header {
padding: 1rem 1.5rem;
background: var(--panel);
border-bottom: 1px solid var(--border);
display: flex;
justify-content: space-between;
align-items: center;
}
header h1 { margin: 0; font-size: 1.05rem; }
#status {
font-size: 0.85rem;
color: var(--muted);
display: flex;
align-items: center;
gap: 0.45rem;
}
.dot {
width: 9px;
height: 9px;
border-radius: 50%;
background: var(--warn);
display: inline-block;
}
.dot.connected { background: var(--ok); }
#chat {
flex: 1;
overflow-y: auto;
padding: 1.5rem;
display: flex;
flex-direction: column;
gap: 1rem;
max-width: 820px;
width: 100%;
margin: 0 auto;
}
.msg {
padding: 0.85rem 1.05rem;
border-radius: 0.8rem;
max-width: 85%;
white-space: pre-wrap;
line-height: 1.55;
}
.user { align-self: flex-end; background: var(--user); }
.assistant { align-self: flex-start; background: var(--bot); }
.error { align-self: center; background: #7f1d1d; font-size: 0.9rem; }
form {
display: flex;
gap: 0.75rem;
padding: 1rem 1.5rem;
background: var(--panel);
border-top: 1px solid var(--border);
justify-content: center;
}
input {
flex: 1;
max-width: 700px;
padding: 0.75rem 1rem;
border-radius: 0.5rem;
border: 1px solid var(--border);
background: var(--bg);
color: var(--text);
font-size: 1rem;
}
button {
padding: 0.75rem 1.35rem;
border: none;
border-radius: 0.5rem;
background: var(--user);
color: #fff;
font-weight: 600;
cursor: pointer;
}
button:disabled { opacity: 0.5; cursor: not-allowed; }
</style>
</head>
<body>
<header>
<h1>Serverless Streaming AI Chat (Amazon Nova Micro)</h1>
<span id="status"><span class="dot" id="dot"></span><span id="status-text">Connecting...</span></span>
</header>
<main id="chat"></main>
<form id="chat-form">
<input id="prompt" type="text" placeholder="Ask anything..." autocomplete="off" required />
<button id="send-btn" type="submit" disabled>Send</button>
</form>
<script>
const WS_URL = "YOUR_WEBSOCKET_URL"; // e.g. wss://abc123.execute-api.us-east-1.amazonaws.com/prod
const chatEl = document.getElementById("chat");
const dotEl = document.getElementById("dot");
const statusTextEl = document.getElementById("status-text");
const formEl = document.getElementById("chat-form");
const inputEl = document.getElementById("prompt");
const sendBtn = document.getElementById("send-btn");
let socket;
let currentBotEl = null;
let currentBotText = "";
const history = [];
function appendMessage(role, text = "") {
const div = document.createElement("div");
div.className = `msg ${role}`;
div.textContent = text;
chatEl.appendChild(div);
chatEl.scrollTop = chatEl.scrollHeight;
return div;
}
function connect() {
socket = new WebSocket(WS_URL);
socket.onopen = () => {
dotEl.classList.add("connected");
statusTextEl.textContent = "Connected";
sendBtn.disabled = false;
};
socket.onclose = () => {
dotEl.classList.remove("connected");
statusTextEl.textContent = "Reconnecting...";
sendBtn.disabled = true;
setTimeout(connect, 2000);
};
socket.onerror = () => {
statusTextEl.textContent = "Connection error";
};
socket.onmessage = (event) => {
const data = JSON.parse(event.data);
if (data.type === "chunk") {
if (!currentBotEl) {
currentBotEl = appendMessage("assistant", "");
currentBotText = "";
}
currentBotText += data.text;
currentBotEl.textContent = currentBotText;
chatEl.scrollTop = chatEl.scrollHeight;
} else if (data.type === "done") {
if (currentBotText) {
history.push({ role: "assistant", content: [{ text: currentBotText }] });
}
currentBotEl = null;
currentBotText = "";
sendBtn.disabled = false;
inputEl.focus();
} else if (data.type === "error") {
appendMessage("error", `Error: ${data.message}`);
currentBotEl = null;
sendBtn.disabled = false;
}
};
}
formEl.addEventListener("submit", (e) => {
e.preventDefault();
const text = inputEl.value.trim();
if (!text || socket.readyState !== WebSocket.OPEN) return;
appendMessage("user", text);
history.push({ role: "user", content: [{ text }] });
// Send the last 10 turns to preserve context while keeping token usage low
socket.send(
JSON.stringify({
action: "sendMessage",
messages: history.slice(-10),
})
);
inputEl.value = "";
sendBtn.disabled = true;
});
connect();
</script>
</body>
</html>
Host It on Amazon S3 + CloudFront
- Create a private S3 bucket and upload
index.html:
aws s3 mb s3://my-serverless-llm-chat-ui --region us-east-1
aws s3 cp index.html s3://my-serverless-llm-chat-ui/index.html
- Create an Amazon CloudFront distribution pointing to your S3 bucket with Origin Access Control (OAC) and set the Default root object to
index.html.
Step 7: Test & Troubleshoot
Open your CloudFront URL (or local index.html), wait for the green Connected indicator, and ask a question like "Explain AWS Lambda cold starts in 3 bullet points." You'll see tokens stream into the chat bubble in real time.
Common Errors & Quick Fixes
| Error | Likely Cause | Fix |
|---|---|---|
AccessDeniedException (Bedrock) |
Model not enabled or wrong IAM ARN | Confirm amazon.nova-micro-v1:0 in us-east-1 and verify bedrock:InvokeModelWithResponseStream in IAM. |
ForbiddenException on post_to_connection
|
Missing execute-api:ManageConnections permission |
Check the IAM resource ARN matches your region, account ID, API ID, and stage (prod). |
Endpoint request timed out |
Lambda timeout too low or >29s generation | Increase Lambda timeout to 30s (or use the async worker pattern below for >29s responses). |
| Connection closes immediately |
$connect Lambda failed |
Inspect /aws/lambda/ws-connect in CloudWatch Logs; verify CONNECTIONS_TABLE env var. |
Cleanup
When you're done experimenting, delete your resources to ensure \$0 ongoing cost:
- Delete the CloudFront distribution and empty/delete the S3 bucket
- Delete the API Gateway WebSocket API
- Delete the three Lambda functions (
ws-connect,ws-disconnect,ws-send-message) and their CloudWatch log groups - Delete the
WebSocketConnectionsDynamoDB table andServerlessLLMWebSocketRoleIAM role
What are you building with serverless AI? Drop a comment below



Top comments (0)