WebSockets & gRPC
Plain HTTP is request → response: the client asks, the server answers, done. Two widely used protocols stretch that model. WebSockets turn an HTTP connection into a long-lived, two-way channel, so the server can push data whenever it wants. gRPC uses HTTP/2's streams to make remote procedure calls between services, with compact binary messages and streaming in both directions. Both matter as much to operators as to developers, because they change what proxies and load balancers have to do.
WebSockets: the upgrade handshake
A WebSocket starts life as an ordinary HTTP/1.1 GET that asks to switch protocols (RFC 6455):
GET /chat HTTP/1.1
Host: chat.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
Origin: https://chat.example.comIf the server agrees, it answers 101 Switching Protocols, and from then on the TCP (or TLS) connection carries WebSocket frames instead of HTTP:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=Sec-WebSocket-Key is 16 random bytes in base64. The server proves that it really speaks WebSocket (and isn't a confused HTTP server or cache replaying an old response) by appending a fixed GUID from the RFC, hashing with SHA-1 and base64-encoding the result:
import base64
import hashlib
GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" # fixed by RFC 6455
def accept_for(key):
digest = hashlib.sha1((key + GUID).encode("ascii")).digest()
return base64.b64encode(digest).decode("ascii")
rfc_key = "dGhlIHNhbXBsZSBub25jZQ==" # the example key from RFC 6455
print("decoded key:", base64.b64decode(rfc_key))
print("Sec-WebSocket-Accept:", accept_for(rfc_key))
# A real client sends 16 new bytes on every connection; the check works the same way.
key = base64.b64encode(bytes(range(16))).decode() # fixed here so the output is stable
print(key, "->", accept_for(key))
print("key length:", len(key), "characters for 16 bytes")decoded key: b'the sample nonce'
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
AAECAwQFBgcICQoLDA0ODw== -> Bz3qJYTGdOe8gUSpLosEdiLKDrk=
key length: 24 characters for 16 bytes
This is not security: anyone can compute the answer. Authentication happens the normal HTTP way (a cookie or token on the upgrade request), and the server should check the Origin header, because browsers send cookies on cross-site WebSocket requests. Use wss:// (WebSocket over TLS) just as you would use https://.
WebSocket frames
After the upgrade, each message travels in one or more small frames:
| FIN(1) RSV(3) opcode(4) | MASK(1) len(7) | [ext. len 16/64] | [masking key 32] | payload ... || Field | Meaning |
|---|---|
FIN |
1 on the last frame of a message (big messages can be fragmented) |
| opcode | 0x1 text (UTF-8), 0x2 binary, 0x0 continuation, 0x8 close, 0x9 ping, 0xA pong |
MASK + key |
Frames from client to server must be masked: the payload is XORed with a 4-byte random key. This stops a malicious page from making the bytes on the wire look like a request to a naive proxy cache. |
| length | 0–125 directly; 126 means "a 16-bit length follows", 127 "a 64-bit length follows" |
The model builds and parses the masked "Hello" frame from RFC 6455's examples, then the server's unmasked reply:
import struct
OPCODES = {0x0: "continuation", 0x1: "text", 0x2: "binary", 0x8: "close", 0x9: "ping", 0xA: "pong"}
def build(opcode, payload, mask_key=None):
header = bytes([0x80 | opcode]) # FIN=1
mask_bit = 0x80 if mask_key else 0
n = len(payload)
if n < 126:
header += bytes([mask_bit | n])
elif n < 65536:
header += bytes([mask_bit | 126]) + struct.pack("!H", n)
else:
header += bytes([mask_bit | 127]) + struct.pack("!Q", n)
if mask_key:
payload = bytes(b ^ mask_key[i % 4] for i, b in enumerate(payload))
header += mask_key
return header + payload
def parse(frame):
fin, opcode = frame[0] >> 7, frame[0] & 0x0F
masked, n = frame[1] >> 7, frame[1] & 0x7F
pos = 2
if n == 126:
n, pos = struct.unpack("!H", frame[2:4])[0], 4
elif n == 127:
n, pos = struct.unpack("!Q", frame[2:10])[0], 10
key = frame[pos:pos + 4] if masked else None
pos += 4 if masked else 0
data = frame[pos:pos + n]
if key:
data = bytes(b ^ key[i % 4] for i, b in enumerate(data))
return f"FIN={fin} {OPCODES[opcode]} masked={bool(masked)} len={n} payload={data!r}"
client = build(0x1, b"Hello", mask_key=bytes([0x37, 0xFA, 0x21, 0x3D]))
server = build(0x1, b"Hello")
print("client -> server:", client.hex(" "))
print(" ", parse(client))
print("server -> client:", server.hex(" "))
print(" ", parse(server))
print("ping:", build(0x9, b"").hex(" "), " 1000-byte binary header:", build(0x2, bytes(1000))[:4].hex(" "))client -> server: 81 85 37 fa 21 3d 7f 9f 4d 51 58
FIN=1 text masked=True len=5 payload=b'Hello'
server -> client: 81 05 48 65 6c 6c 6f
FIN=1 text masked=False len=5 payload=b'Hello'
ping: 89 00 1000-byte binary header: 82 7e 03 e8
A frame costs only 2–14 bytes of overhead, compared with hundreds of bytes of headers for an HTTP request. Ping/pong frames keep the connection alive through NAT gateways and proxies and detect dead peers; a close frame carries a status code (1000 = normal) for a clean shutdown.
When to use WebSockets
| Need | Good fit |
|---|---|
| Two-way, low-latency messages: chat, multiplayer games, collaborative editing, live trading screens | WebSockets |
| Server → browser updates only: notifications, live scores, LLM token streams | Server-Sent Events (text/event-stream): plain HTTP, automatic reconnect, simpler to operate |
| Occasional updates, very restrictive networks | Polling or long polling |
| Service-to-service calls | Not WebSockets: use HTTP APIs or gRPC |
Operationally, a WebSocket is a long-lived connection pinned to one server. That means: proxies must pass the Upgrade header through, idle timeouts must be longer than your ping interval, deploys must drain connections gracefully (clients should reconnect with backoff), and a message for user X may need to reach whichever server holds X's socket, usually through a pub/sub layer such as Redis or NATS. In nginx, upgrading must be enabled explicitly, because Upgrade and Connection are hop-by-hop headers that a proxy doesn't forward by default:
location /chat/ {
proxy_pass http://chat_backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 1h; # default 60s would cut idle sockets
}gRPC: RPC over HTTP/2
gRPC (created at Google, now a CNCF project) lets a service call a method on another service as if it were local. You describe the API in a .proto file with Protocol Buffers (protobuf), and code generators produce typed clients and servers for Go, Java, Python, C#, Rust and many more languages:
syntax = "proto3";
package shop.v1;
message GetItemRequest { string sku = 1; }
message Item { string sku = 1; string name = 2; int32 price_cents = 3; bool in_stock = 4; }
message StockUpdate { string sku = 1; int32 quantity = 2; }
service Inventory {
rpc GetItem(GetItemRequest) returns (Item); // unary
rpc WatchStock(GetItemRequest) returns (stream StockUpdate); // server streaming
rpc UploadCounts(stream StockUpdate) returns (Item); // client streaming
rpc Sync(stream StockUpdate) returns (stream StockUpdate); // bidirectional
}| Kind | Shape | Example |
|---|---|---|
| Unary | one request, one response | look up an item |
| Server streaming | one request, a stream of responses | watch stock levels, tail logs |
| Client streaming | a stream of requests, one response | upload many readings, get a summary |
| Bidirectional | both sides stream independently | chat, sync, interactive sessions |
On the wire, each call is one HTTP/2 stream (see HTTP/2 & HTTP/3): a POST to /shop.v1.Inventory/GetItem with content-type: application/grpc and te: trailers. Request and response bodies are a sequence of messages, each prefixed with 5 bytes (a compression flag and a 4-byte big-endian length). The result is not the HTTP status (that is 200 even for failures) but trailers at the end of the stream: grpc-status (0 = OK, 5 = NOT_FOUND, 14 = UNAVAILABLE, …) and grpc-message.
Protobuf encoding
Protobuf is compact because field names never travel: each field is a tag (field number × 8 + wire type) followed by its value, and integers use varints (7 bits per byte, high bit = "more bytes follow"). This model encodes an Item by hand, wraps it in gRPC's 5-byte prefix and compares it with JSON:
import json
import struct
def varint(n):
out = bytearray()
while True:
byte, n = n & 0x7F, n >> 7
out.append(byte | (0x80 if n else 0))
if not n:
return bytes(out)
def field(number, value):
if isinstance(value, bool) or isinstance(value, int):
return varint(number << 3 | 0) + varint(int(value)) # wire type 0: varint
data = value.encode("utf-8")
return varint(number << 3 | 2) + varint(len(data)) + data # wire type 2: length-delimited
print("150 as a varint:", varint(150).hex(" "))
item = {"sku": "MUG-01", "name": "Coffee mug", "price_cents": 1299, "in_stock": True}
message = b"".join(field(n, item[k]) for n, k in enumerate(["sku", "name", "price_cents", "in_stock"], start=1))
grpc_frame = struct.pack("!BI", 0, len(message)) + message # flag 0 = not compressed
print("protobuf:", message.hex(" "))
print("gRPC frame prefix:", grpc_frame[:5].hex(" "))
as_json = json.dumps(item, separators=(",", ":"))
print(f"{len(message)} bytes as protobuf vs {len(as_json)} bytes as JSON: {as_json}")150 as a varint: 96 01
protobuf: 0a 06 4d 55 47 2d 30 31 12 0a 43 6f 66 66 65 65 20 6d 75 67 18 93 0a 20 01
gRPC frame prefix: 00 00 00 00 19
25 bytes as protobuf vs 71 bytes as JSON: {"sku":"MUG-01","name":"Coffee mug","price_cents":1299,"in_stock":true}
0a is field 1, wire type 2 (1 << 3 | 2); 18 is field 3, varint; 20 01 is field 4 = true. Because fields are identified by number, you can add new fields without breaking old clients, as long as you never reuse or renumber an existing one.
gRPC vs REST
| REST + JSON | gRPC | |
|---|---|---|
| Contract | Conventions, optionally OpenAPI | .proto file is the contract, with generated code |
| Payload | Text JSON, human-readable | Binary protobuf, smaller and faster to parse |
| Transport | HTTP/1.1, 2 or 3 | HTTP/2 (HTTP/3 support is emerging) |
| Streaming | Awkward (SSE, WebSockets) | Built in, both directions |
| Browsers | Native | Not directly: needs gRPC-Web or Connect through a proxy |
| Debugging | curl, any browser |
grpcurl, Postman; needs the .proto or server reflection |
| Typical use | Public APIs, web front ends | Internal service-to-service calls, mobile backends, streaming |
A sample session with grpcurl against a server that has reflection enabled (not run here):
grpcurl -plaintext localhost:50051 list
grpcurl -plaintext -d '{"sku": "MUG-01"}' localhost:50051 shop.v1.Inventory/GetItemgrpc.health.v1.Health
grpc.reflection.v1.ServerReflection
grpc.reflection.v1alpha.ServerReflection
shop.v1.Inventory
{
"sku": "MUG-01",
"name": "Coffee mug",
"priceCents": 1299,
"inStock": true
}What this means for proxies and load balancers
gRPC clients open one long-lived HTTP/2 connection and multiplex every call over it. A load balancer that works per connection (layer 4: an AWS NLB, a Kubernetes ClusterIP Service through kube-proxy) picks a backend once, when the connection opens, and then sends every call from that client to the same backend. Scale up from 3 to 6 Pods and the new ones may sit idle. A load balancer that works per request (layer 7: Envoy, NGINX with grpc_pass, a service mesh, a Gateway API implementation with GRPCRoute) spreads individual calls:
clients = {"checkout": 150, "search": 60, "reports": 30} # calls each client makes, one connection each
backends = ["pod-a", "pod-b", "pod-c", "pod-d"]
def per_connection(): # L4: round-robin when each connection opens
load = dict.fromkeys(backends, 0)
for i, calls in enumerate(clients.values()):
load[backends[i % len(backends)]] += calls
return load
def per_request(): # L7: round-robin over individual calls
load = dict.fromkeys(backends, 0)
n = 0
for calls in clients.values():
for _ in range(calls):
load[backends[n % len(backends)]] += 1
n += 1
return load
for name, fn in [("L4, per connection", per_connection), ("L7, per request", per_request)]:
load = fn()
print(f"{name:20} {load} busiest/idlest: {max(load.values())}/{min(load.values())}")L4, per connection {'pod-a': 150, 'pod-b': 60, 'pod-c': 30, 'pod-d': 0} busiest/idlest: 150/0
L7, per request {'pod-a': 60, 'pod-b': 60, 'pod-c': 60, 'pod-d': 60} busiest/idlest: 60/60
The checklist for running gRPC (and, mostly, WebSockets) behind infrastructure:
- Balance per request: an L7 proxy or mesh, or client-side load balancing (gRPC's
round_robinpolicy over a Kubernetes headless Service, so DNS returns every Pod IP). See Load Balancing and, in Kubernetes, Gateway API. - HTTP/2 end to end: every hop must speak HTTP/2 (with TLS and ALPN
h2, or cleartexth2cinside the cluster) and pass trailers through; a proxy that downgrades to HTTP/1.1 breaks gRPC. - Timeouts: streams can be open for hours; set proxy idle/stream timeouts deliberately, and have clients set deadlines on every call.
- Health checks: gRPC servers expose the standard
grpc.health.v1.Healthservice; Kubernetes probes support it natively (grpc:probe). - Connection churn: to spread load after scaling, servers can set a maximum connection age so clients reconnect (and rebalance) periodically.
Test yourself
What does the server put in Sec-WebSocket-Accept?
- The client's key, echoed back
- base64(SHA-1(key + a fixed GUID))
- A session token for authentication
- The TLS certificate fingerprint
A gRPC service scaled from 3 to 6 Pods, but the new Pods get almost no traffic. What is the most likely cause?
- Protobuf is too slow
- Clients reuse long-lived HTTP/2 connections and the load balancer balances per connection (L4)
- The Pods lack WebSocket support
- gRPC only supports one backend
Which gRPC call type fits a client that sends one request and then receives a stream of stock updates?
- Unary
- Server streaming
- Client streaming
- Bidirectional streaming