FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Real-Time Streaming Architecture

Comparative evaluation of WebSockets, gRPC-Web, and SSE for production streaming applications.

Freshness: current•15 min read•Software and Web Engineering

Key Learning Outcomes

  • ✓Select optimal real-time streaming protocols based on client requirements
  • ✓Build fallback mechanisms for web browser environments
Full Technical Reference Document

Mental model

Choosing a real-time browser streaming architecture comes down to matching directionality (server-push only vs full-duplex chat/audio), wire schema needs (JSON text vs strongly typed Protobuf contracts), browser transport constraints (why standard fetch doesn't universally unlock half-closed/full-duplex gRPC client streams everywhere), and horizontal state distribution. Moving real-time streams into multi-replica production breaks immediately if engineers connect clients blindly to local server memory without a Redis Pub/Sub / NATS fan-out backplane, explicit slow-consumer backpressure bounds, and reconnect cursor replay.

Select Protocol by Direction & Schema
Edge Proxy (Envoy Translation / HTTP2 / WS)
API Pod Subscribes to Redis/NATS Topic
Enforce Slow-Client Backpressure Queue
Resume Disconnects Cleanly via Cursor ID
Conceptual teaching model synthesized from:grpc-docs,sse-html5-spec,envoy-proxy-repo

Theory

Browser JavaScript exposes fundamentally narrower network primitives than native C++/Go TCP sockets: W3C Fetch streaming imposes strict HTTP/1.1/HTTP/2 half-duplex semantics (especially across proxies and legacy browser/CORS configurations) that prevent standard gRPC-Web over HTTP POST from supporting true bi-directional RPC streaming (stream Req -> returns stream Resp). Instead, bi-directional browser communication falls cleanly to WebSockets (wss://) or WebTransport (HTTP/3), while server-streaming gRPC-Web or ConnectRPC routes through an Envoy/HTTP edge bridge.

CriterionServer-Sent Events (SSE / Fetch Stream)WebSockets (wss://)gRPC-Web / ConnectRPC Proxy
Streaming Modes in BrowserServer -> Client chunks (POST via fetch + ReadableStream)True Full-Duplex (send + receive simultaneously)Unary & Server Streaming cleanly (no native HTTP client+server bi-di without WS tunnel)
Wire FormatUTF-8 text (data: {...}\n\n or NDJSON)Binary ArrayBuffer or UTF-8 framesTyped Protobuf (application/grpc-web+proto or connect+json)
CDN / Reverse-Proxy TraversalEffortless over HTTP/2 + X-Accel-Buffering: noRequires Upgrade headers + stateful LB timeoutsRequires Envoy grpc_web HTTP filter (or Connect-native handler!)
Native BackpressureTCP / ReadableStream await reader.read()Requires explicit app ACK windows (TCP pause lags across frames)Stream HTTP/2 flow control to proxy (Envoy), then HTTP chunk backpressure

Horizontal Pub/Sub Backplanes and Bounded Client Output Queues

The moment you scale an API behind a load balancer from 1 replica to 4 replicas (Pod A..D), Client 1 holds an open socket on Pod A while an upstream agent worker emits status events on Pod C. Keeping open streams in an isolated in-memory Python dict silently drops events across pods! Bridge sockets cleanly via an ephemeral pub/sub Backplane (Redis Pub/Sub, Redis Streams for replayable resumes, or NATS): producers publish scoped channel messages (stream:run_9812), while whichever pod owns the live socket subscribes and drains bounded per-connection asyncio.Queue(maxsize=256) buffers. If a client sits on flaky 3G mobile and refuses to read, never buffer infinite messages in server RAM—either shed stale frames (queue.get_nowait() drop-oldest for telemetry gauges) or close the stuck socket cleanly (1008 Policy Violation / timeout) so one stalled phone never OOM-kills an entire API pod!

typescript
export type StreamRequirements = {
needsFullDuplexClientStream: boolean;
needsBinaryProtobufContracts: boolean;
tolerantOfHttpTextOverhead: boolean;
};
​
export type RecommendedTransport =
| "websocket-binary-or-json"
| "grpc-web-or-connect-via-envoy"
| "sse-fetch-readable-stream";
​
export function selectBrowserStreamingProtocol(req: StreamRequirements): RecommendedTransport {
// Browsers cannot run full-duplex client+server gRPC streams reliably over plain Fetch;
// WebSockets handles true simultaneous up/down streams directly.
if (req.needsFullDuplexClientStream) {
return "websocket-binary-or-json";
}
if (req.needsBinaryProtobufContracts && !req.tolerantOfHttpTextOverhead) {
return "grpc-web-or-connect-via-envoy";
}
return "sse-fetch-readable-stream";
}

Note also gRPC-Web wire overhead: HTTP servers behind strict proxies that reject raw binary streams sometimes force application/grpc-web-text (base64 encoding every Protobuf payload, adding +33% wire bloat!), whereas Envoy forwarding native application/grpc-web+proto over HTTPS preserves binary compactness—and ConnectRPC supports browser fetch() streaming directly without needing an Envoy translation layer at all.

Alternatives and trade-offs

  • SSE (fetch + ReadableStream) + Separate REST Control Endpoints (POST /cancel): Cleanest universal HTTP/2 solution for AI chat, multi-agent workflow logs, and live notifications; handles bearer auth effortlessly while letting lightweight POST requests cancel or steer background workflows asynchronously.
  • WebSockets + Redis Pub/Sub Backplane: Unmatched when upstream and downstream message cadence is continuous (collaborative canvas sync, live dictation audio, bidirectional game state); demands custom heartbeat pings, disconnect cleanup, and cross-pod Pub/Sub fan-out engineering.
  • gRPC-Web Behind Envoy (grpc-web filter) or ConnectRPC: Preserves single .proto source of truth from Go/Python backend microservices straight into React TypeScript hooks (buf generated clients) without maintaining dual REST/JSON DTO definitions, at the expense of adding Envoy proxy translation (or Connect protocol wrappers) and still relying on WebSockets if bi-directional client streaming arises later.

Failure modes and misconceptions

  1. Assuming gRPC-Web Gives Full Bi-Directional Browser Streaming Out of the Box: Attempting client-streaming (stream AudioChunk -> stream Transcript) directly from Chrome fetch using plain gRPC-Web fails against protocol constraints (ReadableStream upload restrictions + HTTP proxy buffering). Use WebSockets for bi-directional streaming instead.
  2. Unbounded Per-Socket send() Buffers Causing Server OOM Under Slow Consumers: Pushing 5,000 events/s onto websocket.send() for a throttled background mobile tab fills server kernel/asyncio send buffers until RSS crashes the container. Bound per-connection queues (maxsize), track drain timeouts, and drop/disconnect slow lagging sockets safely.
  3. Zero Event Replay on Reconnection ("Missed Events During Wi-Fi Switch"): Plain Redis PUBLISH/SUBSCRIBE is fire-and-forget—any event emitted during a 3-second tunnel-to-5G network blip disappears permanently! For critical workflow telemetry or chat tokens, write recent chunks to a short-TTL Redis Stream (XADD + MAXLEN) and accept Last-Event-ID / sequence cursor on reconnect so clients replay missed deltas seamlessly.
  4. In-Memory Single-Pod Subscriber Maps With Load-Balanced Multi-Pod APIs: Local connections[user_id] breaks silently as soon as Kubernetes scales replicas to 2+ pods unless backed by distributed Pub/Sub routing or sticky routing + graceful drain.
Reflect before revealing the guide

Decision scenario

Your multi-tenant AI platform needs two real-time views in the browser: (A) an observability console rendering typed Protobuf execution metrics streamed at 50 updates/sec from backend Go services (read-only server stream); and (B) a live agent workspace where users upload streaming voice interruptions while tokens stream back concurrently. Serve (A) via Envoy + gRPC-Web (application/grpc-web+proto) (or ConnectRPC) so Go/TS stay synchronized on one .proto schema without client JSON parsing; serve (B) over WebSockets (wss://) wired into a Redis Streams backplane using bounded asyncio.Queue(maxsize=128) per client, explicit sequence cursors for Wi-Fi-to-5G session recovery, and automatic slow-consumer pruning.

Learning outcomes

  • Select cleanly among SSE (fetch streaming), WebSockets, and gRPC-Web / ConnectRPC by directionality, schema strictness, and proxy constraints.
  • Explain why browser W3C Fetch limits prevent standard gRPC-Web from delivering true HTTP bi-directional streaming without WebSockets.
  • Scale multi-pod real-time connections horizontally across API replicas via Redis Pub/Sub and Redis Streams cursor replay.
  • Protect server RAM from slow-client amplification using bounded send queues and graceful disconnect timeouts.

Trade-offs

Unifying backend Protobuf streams via gRPC-Web or scaling WebSockets over distributed Pub/Sub backplanes unlocks instant responsive UX across distributed workers, yet raises infrastructure complexity around proxy buffering, connection memory caps, and cursor-based gap recovery.

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-201Production LLM Engineer

Design an observable full-stack LLM product from capability validation through interfaces retrieval evaluation security and operations.

37 concepts~35h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next