Chapter 2 · Communication
Revision sheet
Every lesson's idea and recap on one page. Read it before an interview, or print it.
-
2.1Communication Overview
Two questions decide everything: who starts the message, and how often does it arrive?
- Direction and frequency pick the transport; everything else is detail.
- Pull wastes requests, push holds connections — choose which cost you prefer.
- Real screens mix transports; one answer for the whole app is a red flag.
-
2.2Short Polling
Ask the server every N seconds. Simple, stateless, and mostly wasted requests.
- The client owns the clock; freshness is capped by the interval.
- Cheap to build, expensive to run — cost scales with clients, not with events.
- Fix the three defaults: chain timeouts, honour visibility, add jitter.
-
2.3Long Polling
The client asks, and the server holds the request open until it actually has news.
- Long polling is pull that feels like push.
- Always pass a cursor (
?since=) — the gap between responses drops messages otherwise. - Bridge technology: correct when WebSockets aren't available, not when they are.
-
2.4Web Sockets
One HTTP request upgrades into a persistent two-way pipe that stays open for the session.
- One handshake, then a permanent duplex pipe with tiny per-message overhead.
- The protocol is the easy part; reconnect, resubscribe, and replay are the design.
- Only pay for duplex when the client genuinely needs to talk back.
-
2.5Server-Sent Events
A one-way stream over ordinary HTTP that reconnects and resumes by itself.
- One-way, text-only, plain HTTP, streamed over a response that never ends.
- Auto-reconnect and
Last-Event-IDresume are the killer features. - Default to SSE for feeds; upgrade to WebSocket only when the client must talk back.
-
2.6WebHooks
Server-to-server push: you register a URL, and the other system calls you when something happens.
- Webhooks are push between servers; the browser needs a second transport for the last mile.
- Respond
200fast, queue the work, verify the signature. - At-least-once delivery means idempotency is mandatory, not optional.
-
2.7Picking a Transport
Answer three questions in order — direction, frequency, tolerance for staleness — then defend the cost.
- Direction → frequency → staleness. Three questions, in that order.
- State the cost you accepted and the fallback you'd ship; that's the senior signal.
- Mixing transports on one screen is the correct answer, not a compromise.
Capstone
Pick and justify a transport for each: stock ticker, chat, CI build log, order status, payment confirmation.