◉CLAUDE LABJP
●2.1.301 — Adds the vim % motion, LaTeX math rendering in the VS Code panel, and a retry-watchdog limit for usage-limit waits (10/15)●2.1.299 — Conversations over 200K tokens left idle about 54 minutes get compacted; MCP allow rules now match only the server they name●SONNET 4.5 — Retires on the Claude API on 11/30, 45 days left. Migrate to Sonnet 5.5●WINDOWS — Reports say hooks break silently only on Japanese-locale Windows; check the character encoding first●FAST MODE — Opus 5.5 fast mode is out of research preview and no longer needs the beta header (10/15)●NEW — I Put a Ten-Line Promise File at the To…●2.1.301 — Adds the vim % motion, LaTeX math rendering in the VS Code panel, and a retry-watchdog limit for usage-limit waits (10/15)●2.1.299 — Conversations over 200K tokens left idle about 54 minutes get compacted; MCP allow rules now match only the server they name●SONNET 4.5 — Retires on the Claude API on 11/30, 45 days left. Migrate to Sonnet 5.5●WINDOWS — Reports say hooks break silently only on Japanese-locale Windows; check the character encoding first●FAST MODE — Opus 5.5 fast mode is out of research preview and no longer needs the beta header (10/15)●NEW — I Put a Ten-Line Promise File at the To…
Articles/API & SDK
⬡ API & SDK/2026-04-26Advanced

Building a Scalable Real-Time AI Chat Server with Claude API × WebSocket × Redis Pub/Sub — Node.js Production Architecture, Multi-User Management, and Cost Control

Running a real-time AI chat server on Claude API, WebSocket, and Redis Pub/Sub in production. SSE trade-offs, multi-instance routing, and how stop latency quietly corrupts per-user budgets — with the instrumentation code to measure it.

websocketredisnodejsstreaming22realtime3production111api39

✦ Premium Article

When users press send in a chat UI and watch an AI response stream in word by word, that experience is often implemented with SSE (Server-Sent Events). But the moment requirements expand to "let users interrupt mid-generation," "manage multiple turns without reconnecting," or "show bidirectional typing indicators," SSE hits a hard wall.

SSE is an HTTP response extension — one-way, server to client only. Any client-to-server signal still needs a separate REST API call. Session state has to live somewhere. The moment you scale horizontally across multiple instances, routing messages to the right server becomes non-trivial.

I ran into exactly this when building the backend for a mobile app. The single-instance prototype worked fine, but the first time I tried to add "stop generation" functionality, I realized the architecture needed rethinking from the ground up.

WebSocket was designed for bidirectional communication. One persistent connection handles sending and receiving, which makes conversation state management much simpler. Add Redis Pub/Sub and you can route messages correctly regardless of how many server instances you're running.

This guide builds a production-quality real-time AI chat server using Claude API streaming + WebSocket + Redis Pub/Sub. Every section includes working code you can run.

SSE vs WebSocket: The Decision Framework

Getting this choice wrong early means a significant refactor later. Here's how to think through it.

SSE is sufficient when:

  • Users send a message and wait passively for a complete response
  • You need server-to-client push only (news feeds, progress indicators, notifications)
  • Your backend runs on Cloudflare Workers, Lambda, or another environment where WebSocket is awkward to manage
  • HTTP/2 is available and connection limits aren't a concern

WebSocket becomes necessary when:

  • Users need to interrupt AI generation mid-stream (the "stop" button that actually works)
  • You want to send "user is typing" signals from the client to influence AI behavior
  • You need to manage multi-turn conversations over a single connection to reduce reconnect overhead
  • Multiple users share a session for collaboration features
  • You're building for mobile, where connection lifecycle management benefits from explicit control

This guide targets the second set of use cases. If your requirements are firmly in the first group, SSE is simpler — don't add complexity you don't need.

System Architecture Overview

Here's the full picture of what we're building:

[Mobile/Web Client]
       |  WebSocket (wss://)
       |
[Node.js WebSocket Server (horizontally scaled)]
       |  Claude API Streaming (HTTPS/SSE)
       |  Redis Pub/Sub (cross-instance message routing)
       |  Redis String/Hash (per-user token budget + history TTL)
       |
[Redis Cluster] --- [Anthropic Claude API]

Each component has a single responsibility:

  • Node.js WebSocket Server: Accepts connections, validates JWT tokens, forwards user messages to Claude API as streaming requests, and pipes response deltas back to the client in real time
  • Redis Pub/Sub: When running multiple server instances, acts as a message bus so any instance can deliver to any user regardless of which instance they're connected to
  • Redis Key/Value: Stores per-user monthly token usage counters with TTL, and optionally short-term conversation history for reconnect resumption

Install the required packages:

npm install ws @anthropic-ai/sdk ioredis jsonwebtoken dotenv
npm install -D typescript @types/ws @types/node tsx
✦

Thank you for reading this far.

Continue Reading

What follows includes implementation code, benchmarks, and practical content we hope you'll find useful. This site runs without ads — server and development costs are supported entirely by members like you. If it's been helpful, we'd be truly grateful for your support.

WHAT YOU'LL LEARN
✦Instrumentation for measuring post-stop billing, and what 100ms vs 500ms vs 2,000ms of stop latency costs across 3,000 interruptions a month
✦Why a stop signal sent only over Redis Pub/Sub disappears during instance restarts, and the local-first fix
✦Two holes I found by actually running the code against a mock SSE server and Redis: aborts that never surface as AbortError, and a monthly cap that never fires — plus a reserve-then-settle fix
✦Complete implementation: WebSocket server, Claude API stream bridging, Redis routing, and JWT budget control (Node.js / TypeScript)
Secure payment via Stripe · Cancel anytime
✦

Unlock This Article

Get full access to the rest of this article. Buy once, read anytime. This site is ad-free — your support goes directly toward keeping it running.

or
Unlock all articles with Membership →
Share

Thank You for Reading

Claude Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.

  • ✦Copy-paste ready implementation code
  • ✦New advanced guides published daily
  • ✦$5/mo or $10 for lifetime access
View Membership →

Related Articles

⬡ API & SDK2026-04-26
Shipping Generative UI on Claude API: A Production Pattern for Streaming Dynamic Components with Tool Use and JSON Schema
Combine Claude's Tool Use, JSON Schema, and partial JSON streaming to render AI-assembled UI components safely. We cover registry design, type-safety, fallback, and the pitfalls you only learn after running this in production.
⬡ API & SDK2026-04-23
Using tool_choice to Cut Wasted Inference: Four Modes and Cost Patterns for Production
tool_choice is one of the most underused parameters in the Claude API. The four modes — auto, any, tool, and none — each change both behavior and token cost. Here are the patterns I reach for in production, with runnable code.
⬡ API & SDK2026-03-27
Claude API Production Resilience Patterns — Model Routing, Circuit Breakers, and Fallback Strategies for Indie Teams
Production resilience patterns for Claude API: circuit breakers, intelligent model routing, fallback chains, exponential backoff with jitter, and disaster recovery — with TypeScript implementations and operational notes from an indie developer.