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.
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.
| Criterion | Server-Sent Events (SSE / Fetch Stream) | WebSockets (wss://) | gRPC-Web / ConnectRPC Proxy |
|---|---|---|---|
| Streaming Modes in Browser | Server -> 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 Format | UTF-8 text (data: {...}\n\n or NDJSON) | Binary ArrayBuffer or UTF-8 frames | Typed Protobuf (application/grpc-web+proto or connect+json) |
| CDN / Reverse-Proxy Traversal | Effortless over HTTP/2 + X-Accel-Buffering: no | Requires Upgrade headers + stateful LB timeouts | Requires Envoy grpc_web HTTP filter (or Connect-native handler!) |
| Native Backpressure | TCP / 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!
typescriptexport 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 lightweightPOSTrequests 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-webfilter) or ConnectRPC: Preserves single.protosource of truth from Go/Python backend microservices straight into React TypeScript hooks (bufgenerated 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
- Assuming gRPC-Web Gives Full Bi-Directional Browser Streaming Out of the Box: Attempting client-streaming (
stream AudioChunk -> stream Transcript) directly from Chromefetchusing plain gRPC-Web fails against protocol constraints (ReadableStreamupload restrictions + HTTP proxy buffering). Use WebSockets for bi-directional streaming instead. - Unbounded Per-Socket
send()Buffers Causing Server OOM Under Slow Consumers: Pushing5,000 events/sontowebsocket.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. - Zero Event Replay on Reconnection ("Missed Events During Wi-Fi Switch"): Plain Redis
PUBLISH/SUBSCRIBEis fire-and-forget—any event emitted during a3-secondtunnel-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 acceptLast-Event-ID/ sequence cursor on reconnect so clients replay missed deltas seamlessly. - In-Memory Single-Pod Subscriber Maps With Load-Balanced Multi-Pod APIs: Local
connections[user_id]breaks silently as soon as Kubernetes scales replicas to2+pods unless backed by distributed Pub/Sub routing or sticky routing + graceful drain.
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 (
fetchstreaming), WebSockets, and gRPC-Web / ConnectRPC by directionality, schema strictness, and proxy constraints. - Explain why browser W3C
Fetchlimits 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.