Last Minute Notes

Application Protocols and Infrastructure

Real-time and RPC protocols (polling, long polling, SSE, WebSockets, WebRTC, gRPC), other everyday protocols (SSH, email, FTP and SFTP, NTP), and the network infrastructure between client and server: forward and reverse proxies, L4 vs L7 load balancers, load balancing algorithms, CDNs, API gateways, service meshes, and connection pooling.

📘 Application Protocols and Infrastructure

This page covers the protocols applications build on top of TCP and UDP, and the boxes that sit between a client and a server. For architecture-level choices see Building Blocks; this page stays close to the wire.

Table of Contents

  1. Real-Time Options Compared
  2. WebSockets
  3. Server-Sent Events
  4. WebRTC
  5. gRPC and RPC Protocols
  6. Other Everyday Protocols
  7. Proxies
  8. Load Balancers
  9. CDNs
  10. API Gateways and Service Meshes
  11. Connection Management
  12. Questions

1. Real-Time Options Compared

TechniqueDirectionTransportGood forWatch out for
Short pollingClient pulls every N secondsHTTPSimple dashboards, low update ratesWasted requests, latency up to N
Long pollingServer holds the request until data or timeoutHTTPFallback, simple infraOne hanging request per client, reconnect overhead
Server-Sent EventsServer to clientHTTP stream (text/event-stream)Feeds, notifications, LLM token streamingOne direction only, text only
WebSocketsFull duplexUpgraded HTTP/1.1 connection, or over HTTP/2 (RFC 8441)Chat, collaboration, games, tradingStateful connections, harder to load balance and scale
WebRTCPeer to peerUDP (SRTP, SCTP)Voice, video, low-latency dataNAT traversal, signaling server, TURN costs
WebTransportFull duplex, streams and datagramsHTTP/3 over QUICLow-latency games and media in browsersNewer; Safari support arrived later than Chrome and Firefox

2. WebSockets

A WebSocket starts as an HTTP request and upgrades to a raw bidirectional message channel.

GET /chat HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=

The Accept value is a hash of the key plus a fixed GUID, proving the server really speaks WebSocket. After that, both sides exchange frames (text, binary, ping, pong, close). Client-to-server frames are masked to protect against cache poisoning in intermediaries.

Operating WebSockets at scale:

ConcernApproach
Load balancingL7 LB with upgrade support; connections are long-lived so balance by connection count, not round-robin
Fan-out across serversClients on server A must receive messages published on server B: use a pub/sub backplane (Redis, NATS, Kafka)
HeartbeatsPing/pong every 20 to 30 seconds to detect dead peers and keep NAT and LB idle timers alive
ReconnectExponential backoff with jitter, resume from a last-seen message ID
DeploysDraining closes thousands of connections; stagger and let clients reconnect elsewhere
AuthBrowsers cannot set custom headers on the WebSocket constructor: use cookies (check Origin to block cross-site hijacking) or a short-lived token in the first message
CapacityMemory per connection (buffers, TLS state) dominates; tens of thousands to a million per well-tuned server

3. Server-Sent Events

HTTP/1.1 200 OK
Content-Type: text/event-stream
Cache-Control: no-cache

id: 41
event: price
data: {"symbol":"ACME","price":101.2}

id: 42
data: plain message
  • Browser API: new EventSource("/stream").
  • Automatic reconnect with the Last-Event-ID header, so the server can resume.
  • Works through most proxies because it is plain HTTP, and over HTTP/2 many streams share one connection.
  • Under HTTP/1.1 browsers limit each origin to 6 connections, which SSE tabs can exhaust.
  • Proxies that buffer responses (for example nginx with proxy_buffering on) break streaming; disable buffering for these routes.

SSE is the standard way LLM APIs stream tokens.


4. WebRTC

WebRTC gives browsers direct peer-to-peer audio, video, and data channels.

PieceRole
SignalingExchange session descriptions (SDP offers and answers) through your own server, often over WebSockets
ICEGather candidate addresses and try them in pairs to find a working path
STUNServer that tells a client its public IP and port as seen from outside the NAT
TURNRelay server used when direct connection fails (symmetric NATs, strict firewalls); costs bandwidth
DTLS / SRTPEncryption for data and media, mandatory
SFUSelective forwarding unit: server that receives each participant's stream once and forwards it to others; how group calls scale

Peer to peer works for two people; group calls use an SFU because full mesh upload bandwidth grows with every participant.


5. gRPC and RPC Protocols

gRPC is an RPC framework using Protocol Buffers over HTTP/2.

FeatureDetail
Contract.proto files, generated clients and servers in many languages
EncodingProtobuf binary: small and fast, field numbers enable backward-compatible evolution
StreamingUnary, server streaming, client streaming, bidirectional
DeadlinesPropagated across calls, so a timed-out request stops work downstream
Status codesIts own (UNAVAILABLE, DEADLINE_EXCEEDED, NOT_FOUND), sent in HTTP/2 trailers
BrowsersCannot access HTTP/2 trailers, so need gRPC-Web or Connect through a proxy

Load balancing gotcha: gRPC multiplexes all calls over one long-lived HTTP/2 connection, so an L4 load balancer pins every call from a client to one backend. Use L7 (per-request) balancing: Envoy, a service mesh, or client-side balancing with a lookaside resolver.

ProtocolStyleTypical use
REST / JSON over HTTPResource orientedPublic APIs
GraphQLQuery language over HTTPClient-driven data fetching
gRPCRPC, protobuf, HTTP/2Internal service-to-service
Thrift, Avro RPCRPCLegacy big-data stacks
JSON-RPCRPC over any transportEthereum nodes, the Language Server Protocol, the Model Context Protocol (MCP)

6. Other Everyday Protocols

ProtocolPortWhat to know
SSH22/TCPEncrypted remote shell, key-based auth, port forwarding (-L local, -R remote, -D SOCKS), SCP and SFTP ride on it
SMTP25 (server to server), 587 (submission with STARTTLS), 465 (implicit TLS)Sending mail; SPF, DKIM, DMARC TXT records fight spoofing
IMAP / POP3993 / 995 with TLSReading mail: IMAP syncs folders on the server, POP3 downloads
FTP20, 21Plaintext, separate control and data connections, active vs passive mode headaches; avoid
SFTP22File transfer over SSH, unrelated to FTP despite the name
NTP123/UDPClock sync; skew breaks TLS validation, token expiry, and distributed logs. PTP for sub-microsecond accuracy
SNMP161/UDPLegacy device monitoring
LDAP389, 636 with TLSDirectory lookups, Active Directory
RDP3389Windows remote desktop; never expose it directly to the Internet
MQTT1883, 8883 with TLSLightweight pub/sub for IoT
AMQP5672RabbitMQ messaging

Email authentication in one line each: SPF lists which servers may send for a domain, DKIM signs messages with a key published in DNS, and DMARC tells receivers what to do when both fail and where to send reports. Gmail and Yahoo require all three for bulk senders since 2024.


7. Proxies

Forward proxyReverse proxy
Sits in front ofClientsServers
Who knows about itClient is configured to use itClient thinks it is the server
UsesEgress filtering, caching, anonymity, corporate policyTLS termination, load balancing, caching, compression, WAF, hiding backend topology
ExamplesSquid, corporate proxies, SOCKSnginx, HAProxy, Envoy, Caddy, Traefik, Cloudflare

A transparent proxy intercepts traffic without client configuration. Proxies pass the original client IP in X-Forwarded-For (or Forwarded) headers, or at L4 with the PROXY protocol. Only trust these headers when they come from your own proxy, otherwise clients can spoof their IP.


8. Load Balancers

L4 load balancerL7 load balancer
SeesIPs, ports, TCP/UDPHTTP method, path, headers, cookies
Decision perConnectionRequest
TLSUsually passes throughTerminates, can re-encrypt
FeaturesVery fast, protocol agnosticPath routing, header rewrites, retries, auth, rate limiting, canaries
CostCheaper, less CPUMore CPU, adds latency (usually under a millisecond)
ExamplesAWS NLB, Google Maglev, IPVS, Katran (eBPF)AWS ALB, nginx, HAProxy, Envoy

Algorithms

AlgorithmHowBest when
Round-robinNext backend in turnIdentical backends, uniform requests
Weighted round-robinProportional to capacityMixed instance sizes, canaries
Least connectionsBackend with fewest active connectionsLong or variable requests, WebSockets
Least response time / EWMAFastest recent backendLatency-sensitive services
Power of two choicesPick two at random, take the less loadedLarge fleets, avoids herding, used by Envoy and others
IP hash / consistent hashingHash of client or key picks backendSession affinity, cache locality
RandomUniform randomSimple and surprisingly good at scale

Health checks and failure handling

  • Active checks probe /healthz; passive checks (outlier detection) eject a backend after errors in real traffic.
  • Connection draining stops new requests to a backend being removed but lets in-flight ones finish.
  • Sticky sessions keep a client on one backend using a cookie; they hurt balance and failover, so prefer stateless backends.
  • Direct server return: the LB handles inbound packets only and backends reply straight to the client, useful when responses are much larger than requests.
  • High availability for the LB itself: a pair with a floating virtual IP (VRRP / keepalived), ECMP across many LB nodes, or anycast.

9. CDNs

A CDN is a global network of edge servers (points of presence) that serve content close to users.

BenefitHow
Lower latencyEdge is a few ms away, TLS terminates close to the user
OffloadCache hits never reach the origin
ResilienceAbsorb DDoS, serve stale content when the origin is down
Better transportTuned TCP, HTTP/3, persistent pooled connections from edge to origin
Edge computeRun code at the edge (Cloudflare Workers, Fastly Compute, Lambda@Edge)

How users reach the nearest edge: anycast IPs (Cloudflare) or DNS-based steering (Akamai, CloudFront).

Caching controls:

HeaderMeaning
Cache-Control: public, max-age=31536000, immutableCache for a year; use with content-hashed filenames
Cache-Control: s-maxage=60TTL for shared caches (CDN) only
Cache-Control: no-storeNever cache (private data)
Cache-Control: no-cacheMay store, but must revalidate before each use
stale-while-revalidate=30Serve stale while refreshing in the background
ETag / If-None-MatchValidator; unchanged content returns 304 Not Modified
Vary: Accept-EncodingCache separate variants per header value

Invalidation strategies: versioned URLs (best), purge by URL or by tag (surrogate keys), or short TTLs. Origin shield: one mid-tier cache in front of the origin so a cache miss storm across hundreds of edges becomes one origin request.

Classic bug: caching a personalized response publicly because Cache-Control was missing or a Set-Cookie was cached, leaking one user's page to others.


10. API Gateways and Service Meshes

ComponentScopeTypical features
API gatewayNorth-south (clients into your system)Auth, rate limiting, request routing, API keys, request transformation, analytics
Service meshEast-west (service to service)mTLS, retries, timeouts, circuit breaking, traffic splitting, telemetry, without app code changes

Meshes deploy a proxy next to each service (the sidecar, usually Envoy) or, increasingly, a per-node proxy plus lightweight per-service components (Istio ambient mode, Cilium with eBPF) to cut overhead.


11. Connection Management

Connections are expensive: TCP handshake, TLS handshake, slow start, kernel memory. Most network performance work is really about reusing them.

PracticeWhy
HTTP keep-aliveReuse TCP + TLS across requests
Client connection poolsBound concurrency, avoid handshake per request, avoid ephemeral port exhaustion
Idle timeouts in orderClient idle timeout < LB idle timeout < server idle timeout; otherwise clients send on connections the server already closed, causing sporadic 502 or "connection reset" errors
Timeouts everywhereConnect, TLS, read, and total deadlines; a missing timeout turns a slow dependency into a full outage
Retries with backoff and jitterOnly for idempotent requests, with a retry budget to avoid retry storms
Circuit breakersStop calling a failing dependency and fail fast
DNS re-resolutionLong-lived pools pin old IPs; recycle connections periodically (max connection age)

12. Questions

QuestionShort answer
WebSockets vs SSE vs long polling?Full duplex frames vs server-to-client HTTP stream vs repeated held requests
How do you scale WebSockets horizontally?L7 LB with least connections, pub/sub backplane for fan-out, heartbeats, reconnect with resume
Forward vs reverse proxy?Acts for clients vs acts for servers
L4 vs L7 load balancer?Per connection on IP/port vs per request on HTTP content
Why does gRPC need L7 load balancing?One long-lived HTTP/2 connection carries all calls; L4 pins them to one backend
How does a CDN route users to the nearest edge?Anycast or DNS-based steering
How do you invalidate CDN caches?Versioned URLs, purge by tag or URL, short TTL with stale-while-revalidate
What are STUN and TURN?Discover public address vs relay traffic when direct paths fail
Why order idle timeouts?So the client never reuses a connection the server or LB already closed
What is a service mesh?Proxies that give service-to-service mTLS, retries, and telemetry without code changes

Next: Network Security.

On this page