{"slug": "build-a-serverless-streaming-llm-chat-app-on-aws-with-bedrock-websockets-lambda", "title": "Build a Serverless Streaming LLM Chat App on AWS with Bedrock, WebSockets & Lambda", "summary": "A developer published a step-by-step guide for building a serverless streaming LLM chat app on AWS using API Gateway WebSocket APIs, Lambda functions written in Python 3.12, DynamoDB for connection tracking, and Amazon Bedrock's ConverseStream API with the amazon.nova-micro-v1:0 model. The architecture pushes token-by-token responses from Bedrock through Lambda and API Gateway to a static S3/CloudFront frontend, avoiding managed servers and scaling to zero when idle. The guide includes CLI commands for provisioning the DynamoDB connections table with TTL, IAM permissions for bedrock:InvokeModelWithResponseStream and execute-api:ManageConnections, and notes the stack fits largely within AWS Free Tier limits.", "body_md": "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.\n\n**You don't need any of that.**\n\nCombining 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.\n\nIn this step-by-step guide, you'll build and deploy a complete serverless streaming AI chat app on AWS using:\n\n`wss://` connections\nBefore writing a single line of code, let's clear up a common misconception about AWS AI pricing:\n\n`amazon.nova-micro-v1:0`), AWS's fastest and most economical text model, even uncredited testing costs 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.\n\nStandard 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.\n\nWith **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.\n\n`index.html` from Amazon S3 (fronted by CloudFront).`$connect` Lambda saves the user's `connectionId` to DynamoDB.`\"action\": \"sendMessage\"`. API Gateway routes it to the `ws-send-message` Lambda.`bedrock-runtime.converse_stream()` using `contentBlockDelta` event from Bedrock, Lambda calls `apigatewaymanagementapi.post_to_connection()` to push the text chunk straight to the browser, finishing with a `{\"type\": \"done\"}` event.`$disconnect` deletes the | Service | Purpose | Cost Profile | \n|---|---|---|\n| **Amazon S3 + CloudFront** | Hosts static `index.html` over HTTPS | AWS Free Tier eligible | \n| **API Gateway (WebSocket)** | Manages persistent `wss://` connections | 1M messages & 750K connection-mins/mo (Free Tier) | \n| **AWS Lambda (Python 3.12)** | Runs `$connect` ,`$disconnect` , and streaming logic | 1M requests/mo always free | \n| **Amazon DynamoDB** | Stores active `connectionId` records + TTL | 25 GB storage + generous on-demand Free Tier | \n| **Amazon Bedrock** | Serverless LLM inference ( `amazon.nova-micro-v1:0` ) | Pay-per-token (covered by new-account AWS credits) | \n| **IAM & CloudWatch Logs** | Least-privilege security & execution logs | Free IAM / 5 GB CloudWatch Free Tier | \n\n`aws configure`)` us-east-1`\nCreate a working folder on your machine so everything stays organized:\n\n```\nmkdir aws-serverless-llm-chat\ncd aws-serverless-llm-chat\n```\n\nYou can quickly verify access from your terminal:\n\n```\naws bedrock list-foundation-models \\\n  --region us-east-1 \\\n  --by-provider Amazon \\\n  --query \"modelSummaries[?contains(modelId, 'nova-micro')].modelId\"\n```\n\nYou should see `\"amazon.nova-micro-v1:0\"` in the output.\n\nCreate an on-demand DynamoDB table called `WebSocketConnections` to store each client's `connectionId`:\n\n```\naws dynamodb create-table \\\n  --table-name WebSocketConnections \\\n  --attribute-definitions AttributeName=connectionId,AttributeType=S \\\n  --key-schema AttributeName=connectionId,KeyType=HASH \\\n  --billing-mode PAY_PER_REQUEST \\\n  --region us-east-1\n```\n\nEnable **TTL (Time to Live)** on the `ttl` attribute so abandoned connections clean themselves up automatically:\n\n```\naws dynamodb update-time-to-live \\\n  --table-name WebSocketConnections \\\n  --time-to-live-specification \"Enabled=true, AttributeName=ttl\" \\\n  --region us-east-1\n```\n\nOur Lambda functions need permission to:\n\n`bedrock:InvokeModelWithResponseStream`` execute-api:ManageConnections`\nFirst, grab your 12-digit AWS Account ID:\n\n```\nACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)\necho $ACCOUNT_ID\n```\n\nCreate `trust-policy.json`:\n\n```\n{\n  \"Version\": \"2012-10-17\",\n  \"Statement\": [\n    {\n      \"Effect\": \"Allow\",\n      \"Principal\": { \"Service\": \"lambda.amazonaws.com\" },\n      \"Action\": \"sts:AssumeRole\"\n    }\n  ]\n}\n```\n\nCreate the role and attach the basic CloudWatch logging policy:\n\n```\naws iam create-role \\\n  --role-name ServerlessLLMWebSocketRole \\\n  --assume-role-policy-document file://trust-policy.json\n\naws iam attach-role-policy \\\n  --role-name ServerlessLLMWebSocketRole \\\n  --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole\n```\n\nNow create `lambda-permissions.json` (replace `<ACCOUNT_ID>` with your Account ID):\n\n```\n{\n  \"Version\": \"2012-10-17\",\n  \"Statement\": [\n    {\n      \"Sid\": \"DynamoDBConnectionsAccess\",\n      \"Effect\": \"Allow\",\n      \"Action\": [\n        \"dynamodb:PutItem\",\n        \"dynamodb:DeleteItem\"\n      ],\n      \"Resource\": \"arn:aws:dynamodb:us-east-1:<ACCOUNT_ID>:table/WebSocketConnections\"\n    },\n    {\n      \"Sid\": \"BedrockNovaMicroStream\",\n      \"Effect\": \"Allow\",\n      \"Action\": [\n        \"bedrock:InvokeModelWithResponseStream\"\n      ],\n      \"Resource\": \"arn:aws:bedrock:us-east-1::foundation-model/amazon.nova-micro-v1:0\"\n    },\n    {\n      \"Sid\": \"ApiGatewayManageConnections\",\n      \"Effect\": \"Allow\",\n      \"Action\": [\n        \"execute-api:ManageConnections\"\n      ],\n      \"Resource\": \"arn:aws:execute-api:us-east-1:<ACCOUNT_ID>:*/prod/POST/@connections/*\"\n    }\n  ]\n}\n```\n\n**Security Tip:** After Step 5 gives you your exact `<API_ID>`, tighten the `ApiGatewayManageConnections` resource ARN by replacing `*` with your `<API_ID>`.\n\nAttach the inline policy:\n\n```\naws iam put-role-policy \\\n  --role-name ServerlessLLMWebSocketRole \\\n  --policy-name ServerlessLLMInlinePolicy \\\n  --policy-document file://lambda-permissions.json\n```\n\nWe'll create three small, focused Python 3.12 Lambda functions.\n\n`connect.py` (\nRuns whenever a user opens the chat page and establishes a WebSocket connection.\n\n``` python\nimport os\nimport time\nimport boto3\n\ndynamodb = boto3.resource(\"dynamodb\")\ntable = dynamodb.Table(os.environ[\"CONNECTIONS_TABLE\"])\n\ndef lambda_handler(event, context):\n    connection_id = event[\"requestContext\"][\"connectionId\"]\n\n    table.put_item(\n        Item={\n            \"connectionId\": connection_id,\n            \"ttl\": int(time.time()) + 7200,  # Auto-expire after 2 hours\n        }\n    )\n\n    return {\"statusCode\": 200, \"body\": \"Connected\"}\n```\n\n`disconnect.py` (\nRuns when the browser closes or drops the connection.\n\n``` python\nimport os\nimport boto3\n\ndynamodb = boto3.resource(\"dynamodb\")\ntable = dynamodb.Table(os.environ[\"CONNECTIONS_TABLE\"])\n\ndef lambda_handler(event, context):\n    connection_id = event[\"requestContext\"][\"connectionId\"]\n    table.delete_item(Key={\"connectionId\": connection_id})\n    return {\"statusCode\": 200, \"body\": \"Disconnected\"}\n```\n\n`send_message.py` (`sendMessage` route)\nThis 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`.\n\n``` python\nimport json\nimport os\nimport boto3\nfrom botocore.exceptions import ClientError\n\nREGION = os.environ.get(\"AWS_REGION\", \"us-east-1\")\nMODEL_ID = os.environ.get(\"MODEL_ID\", \"amazon.nova-micro-v1:0\")\n\nbedrock = boto3.client(\"bedrock-runtime\", region_name=REGION)\n\ndef post_json(apigw_client, connection_id, payload):\n    \"\"\"Push a JSON frame back to the connected WebSocket client.\"\"\"\n    apigw_client.post_to_connection(\n        ConnectionId=connection_id,\n        Data=json.dumps(payload).encode(\"utf-8\"),\n    )\n\ndef lambda_handler(event, context):\n    connection_id = event[\"requestContext\"][\"connectionId\"]\n    domain = event[\"requestContext\"][\"domainName\"]\n    stage = event[\"requestContext\"][\"stage\"]\n\n    # Build the Management API client dynamically from the WebSocket request context\n    apigw = boto3.client(\n        \"apigatewaymanagementapi\",\n        endpoint_url=f\"https://{domain}/{stage}\",\n    )\n\n    try:\n        body = json.loads(event.get(\"body\") or \"{}\")\n        messages = body.get(\"messages\")\n\n        # Support either a multi-turn \"messages\" array or a single \"prompt\" string\n        if not messages:\n            prompt = (body.get(\"prompt\") or \"\").strip()\n            if not prompt:\n                post_json(apigw, connection_id, {\"type\": \"error\", \"message\": \"Prompt cannot be empty.\"})\n                return {\"statusCode\": 400, \"body\": \"Empty prompt\"}\n            messages = [{\"role\": \"user\", \"content\": [{\"text\": prompt}]}]\n\n        # Call Amazon Bedrock's unified ConverseStream API\n        response = bedrock.converse_stream(\n            modelId=MODEL_ID,\n            system=[{\"text\": \"You are a helpful, concise technical assistant.\"}],\n            messages=messages,\n            inferenceConfig={\n                \"maxTokens\": 1024,\n                \"temperature\": 0.7,\n            },\n        )\n\n        # Forward every token chunk to the browser immediately as it arrives\n        for event_chunk in response.get(\"stream\", []):\n            if \"contentBlockDelta\" in event_chunk:\n                text = event_chunk[\"contentBlockDelta\"][\"delta\"].get(\"text\", \"\")\n                if text:\n                    post_json(apigw, connection_id, {\"type\": \"chunk\", \"text\": text})\n\n        # Signal that the stream has finished\n        post_json(apigw, connection_id, {\"type\": \"done\"})\n        return {\"statusCode\": 200, \"body\": \"Stream complete\"}\n\n    except apigw.exceptions.GoneException:\n        # User closed their browser tab mid-stream — exit cleanly\n        return {\"statusCode\": 410, \"body\": \"Client disconnected\"}\n    except ClientError as exc:\n        err_msg = exc.response[\"Error\"][\"Message\"]\n        post_json(apigw, connection_id, {\"type\": \"error\", \"message\": err_msg})\n        return {\"statusCode\": 500, \"body\": err_msg}\n```\n\nPackage and deploy all three functions with the AWS CLI (or paste the code directly into the AWS Lambda Console):\n\n```\nROLE_ARN=\"arn:aws:iam::${ACCOUNT_ID}:role/ServerlessLLMWebSocketRole\"\n\nzip connect.zip connect.py\nzip disconnect.zip disconnect.py\nzip send_message.zip send_message.py\n\naws lambda create-function \\\n  --function-name ws-connect \\\n  --runtime python3.12 \\\n  --role \"$ROLE_ARN\" \\\n  --handler connect.lambda_handler \\\n  --zip-file fileb://connect.zip \\\n  --environment \"Variables={CONNECTIONS_TABLE=WebSocketConnections}\" \\\n  --region us-east-1\n\naws lambda create-function \\\n  --function-name ws-disconnect \\\n  --runtime python3.12 \\\n  --role \"$ROLE_ARN\" \\\n  --handler disconnect.lambda_handler \\\n  --zip-file fileb://disconnect.zip \\\n  --environment \"Variables={CONNECTIONS_TABLE=WebSocketConnections}\" \\\n  --region us-east-1\n\naws lambda create-function \\\n  --function-name ws-send-message \\\n  --runtime python3.12 \\\n  --role \"$ROLE_ARN\" \\\n  --handler send_message.lambda_handler \\\n  --zip-file fileb://send_message.zip \\\n  --timeout 30 \\\n  --memory-size 256 \\\n  --environment \"Variables={MODEL_ID=amazon.nova-micro-v1:0}\" \\\n  --region us-east-1\n```\n\n**Important:** Notice `--timeout 30` on `ws-send-message`. Lambda's default 3-second timeout will cut off LLM responses mid-sentence!\n\nThe quickest way to wire up the routes (and automatically grant API Gateway permission to invoke your Lambdas) is in the AWS Console:\n\n`ServerlessLLMChatAPI`\n`$request.body.action`\n`ws-connect`\n`ws-disconnect`\n`prod`\n\n```\nwss://<your-api-id>.execute-api.us-east-1.amazonaws.com/prod\n```\n\nNow 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.\n\nReplace `YOUR_WEBSOCKET_URL` with the `wss://...` URL from Step 5:\n\n```\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n  <meta charset=\"UTF-8\" />\n  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n  <title>Serverless AWS Streaming LLM Chat</title>\n  <style>\n    :root {\n      --bg: #0f172a;\n      --panel: #1e293b;\n      --text: #f8fafc;\n      --muted: #94a3b8;\n      --user: #2563eb;\n      --bot: #334155;\n      --border: #475569;\n      --ok: #22c55e;\n      --warn: #f59e0b;\n    }\n    * { box-sizing: border-box; }\n    body {\n      margin: 0;\n      font-family: system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif;\n      background: var(--bg);\n      color: var(--text);\n      display: flex;\n      flex-direction: column;\n      height: 100vh;\n    }\n    header {\n      padding: 1rem 1.5rem;\n      background: var(--panel);\n      border-bottom: 1px solid var(--border);\n      display: flex;\n      justify-content: space-between;\n      align-items: center;\n    }\n    header h1 { margin: 0; font-size: 1.05rem; }\n    #status {\n      font-size: 0.85rem;\n      color: var(--muted);\n      display: flex;\n      align-items: center;\n      gap: 0.45rem;\n    }\n    .dot {\n      width: 9px;\n      height: 9px;\n      border-radius: 50%;\n      background: var(--warn);\n      display: inline-block;\n    }\n    .dot.connected { background: var(--ok); }\n    #chat {\n      flex: 1;\n      overflow-y: auto;\n      padding: 1.5rem;\n      display: flex;\n      flex-direction: column;\n      gap: 1rem;\n      max-width: 820px;\n      width: 100%;\n      margin: 0 auto;\n    }\n    .msg {\n      padding: 0.85rem 1.05rem;\n      border-radius: 0.8rem;\n      max-width: 85%;\n      white-space: pre-wrap;\n      line-height: 1.55;\n    }\n    .user { align-self: flex-end; background: var(--user); }\n    .assistant { align-self: flex-start; background: var(--bot); }\n    .error { align-self: center; background: #7f1d1d; font-size: 0.9rem; }\n    form {\n      display: flex;\n      gap: 0.75rem;\n      padding: 1rem 1.5rem;\n      background: var(--panel);\n      border-top: 1px solid var(--border);\n      justify-content: center;\n    }\n    input {\n      flex: 1;\n      max-width: 700px;\n      padding: 0.75rem 1rem;\n      border-radius: 0.5rem;\n      border: 1px solid var(--border);\n      background: var(--bg);\n      color: var(--text);\n      font-size: 1rem;\n    }\n    button {\n      padding: 0.75rem 1.35rem;\n      border: none;\n      border-radius: 0.5rem;\n      background: var(--user);\n      color: #fff;\n      font-weight: 600;\n      cursor: pointer;\n    }\n    button:disabled { opacity: 0.5; cursor: not-allowed; }\n  </style>\n</head>\n<body>\n  <header>\n    <h1>Serverless Streaming AI Chat (Amazon Nova Micro)</h1>\n    <span id=\"status\"><span class=\"dot\" id=\"dot\"></span><span id=\"status-text\">Connecting...</span></span>\n  </header>\n\n  <main id=\"chat\"></main>\n\n  <form id=\"chat-form\">\n    <input id=\"prompt\" type=\"text\" placeholder=\"Ask anything...\" autocomplete=\"off\" required />\n    <button id=\"send-btn\" type=\"submit\" disabled>Send</button>\n  </form>\n\n  <script>\n    const WS_URL = \"YOUR_WEBSOCKET_URL\"; // e.g. wss://abc123.execute-api.us-east-1.amazonaws.com/prod\n    const chatEl = document.getElementById(\"chat\");\n    const dotEl = document.getElementById(\"dot\");\n    const statusTextEl = document.getElementById(\"status-text\");\n    const formEl = document.getElementById(\"chat-form\");\n    const inputEl = document.getElementById(\"prompt\");\n    const sendBtn = document.getElementById(\"send-btn\");\n\n    let socket;\n    let currentBotEl = null;\n    let currentBotText = \"\";\n    const history = [];\n\n    function appendMessage(role, text = \"\") {\n      const div = document.createElement(\"div\");\n      div.className = `msg ${role}`;\n      div.textContent = text;\n      chatEl.appendChild(div);\n      chatEl.scrollTop = chatEl.scrollHeight;\n      return div;\n    }\n\n    function connect() {\n      socket = new WebSocket(WS_URL);\n\n      socket.onopen = () => {\n        dotEl.classList.add(\"connected\");\n        statusTextEl.textContent = \"Connected\";\n        sendBtn.disabled = false;\n      };\n\n      socket.onclose = () => {\n        dotEl.classList.remove(\"connected\");\n        statusTextEl.textContent = \"Reconnecting...\";\n        sendBtn.disabled = true;\n        setTimeout(connect, 2000);\n      };\n\n      socket.onerror = () => {\n        statusTextEl.textContent = \"Connection error\";\n      };\n\n      socket.onmessage = (event) => {\n        const data = JSON.parse(event.data);\n\n        if (data.type === \"chunk\") {\n          if (!currentBotEl) {\n            currentBotEl = appendMessage(\"assistant\", \"\");\n            currentBotText = \"\";\n          }\n          currentBotText += data.text;\n          currentBotEl.textContent = currentBotText;\n          chatEl.scrollTop = chatEl.scrollHeight;\n        } else if (data.type === \"done\") {\n          if (currentBotText) {\n            history.push({ role: \"assistant\", content: [{ text: currentBotText }] });\n          }\n          currentBotEl = null;\n          currentBotText = \"\";\n          sendBtn.disabled = false;\n          inputEl.focus();\n        } else if (data.type === \"error\") {\n          appendMessage(\"error\", `Error: ${data.message}`);\n          currentBotEl = null;\n          sendBtn.disabled = false;\n        }\n      };\n    }\n\n    formEl.addEventListener(\"submit\", (e) => {\n      e.preventDefault();\n      const text = inputEl.value.trim();\n      if (!text || socket.readyState !== WebSocket.OPEN) return;\n\n      appendMessage(\"user\", text);\n      history.push({ role: \"user\", content: [{ text }] });\n\n      // Send the last 10 turns to preserve context while keeping token usage low\n      socket.send(\n        JSON.stringify({\n          action: \"sendMessage\",\n          messages: history.slice(-10),\n        })\n      );\n\n      inputEl.value = \"\";\n      sendBtn.disabled = true;\n    });\n\n    connect();\n  </script>\n</body>\n</html>\naws s3 mb s3://my-serverless-llm-chat-ui --region us-east-1\naws s3 cp index.html s3://my-serverless-llm-chat-ui/index.html\n```\n\nOpen 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.\n\n| Error | Likely Cause | Fix | \n|---|---|---|\n| `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. | \n| `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` ). | \n| `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). | \n| Connection closes immediately | `$connect` Lambda failed | Inspect `/aws/lambda/ws-connect` in CloudWatch Logs; verify`CONNECTIONS_TABLE` env var. | \n\nWhen you're done experimenting, delete your resources to ensure \\$0 ongoing cost:\n\n`WebSocketConnections` `ServerlessLLMWebSocketRole` **What are you building with serverless AI?** Drop a comment below", "url": "https://wpnews.pro/news/build-a-serverless-streaming-llm-chat-app-on-aws-with-bedrock-websockets-lambda", "canonical_source": "https://dev.to/damdev95/build-a-serverless-streaming-llm-chat-app-on-aws-with-bedrock-websockets-lambda-4fh2", "published_at": "2026-12-02 10:06:27+00:00", "updated_at": "2026-12-02 10:14:34.687473+00:00", "lang": "en", "topics": ["large-language-models", "ai-infrastructure", "ai-tools", "developer-tools", "mlops"], "entities": ["AWS", "Amazon Bedrock", "AWS Lambda", "Amazon API Gateway", "Amazon DynamoDB", "Amazon S3", "Amazon CloudFront", "Amazon Nova Micro"], "also_reported_by": [], "takeaway": "Combining API Gateway WebSocket connections with Lambda and Bedrock's ConverseStream API streams tokens to the browser without REST timeouts, and swapping models is a one-line environment variable change.", "recommendation": {"advice": "Use API Gateway WebSockets with Lambda and Bedrock ConverseStream to stream tokens to clients, storing connectionIds in DynamoDB with TTL so idle connections clean themselves up.", "playbook": "agent-architecture", "playbook_url": "https://wpnews.pro/playbooks/agent-architecture"}, "alternates": {"html": "https://wpnews.pro/news/build-a-serverless-streaming-llm-chat-app-on-aws-with-bedrock-websockets-lambda", "markdown": "https://wpnews.pro/news/build-a-serverless-streaming-llm-chat-app-on-aws-with-bedrock-websockets-lambda.md", "text": "https://wpnews.pro/news/build-a-serverless-streaming-llm-chat-app-on-aws-with-bedrock-websockets-lambda.txt", "jsonld": "https://wpnews.pro/news/build-a-serverless-streaming-llm-chat-app-on-aws-with-bedrock-websockets-lambda.jsonld"}}