ayushsalampuriya.xyz Revise

System Design · Core

Communication Protocols

Pick how services and clients talk: HTTP/REST, gRPC, WebSocket, GraphQL briefly, and sync vs async trade-offs.

1. Start from requirements

Request/response, public API, CRUD → HTTP + REST/JSON Low-latency internal RPC, typed → gRPC Server push, chat, live updates → WebSocket (or SSE) Flexible client-driven queries → GraphQL (with care) Decouple producers, buffer spikes → async messaging

2. HTTP and REST

REST over HTTP uses resources and verbs (GET/POST/PUT/PATCH/DELETE), status codes, and usually JSON. Ubiquitous, cacheable GETs, great for public APIs and browsers.

PrincipleMeaning
StatelessEach request carries auth/context; server does not rely on sticky memory
Resource-basedNouns in URLs (/orders/9), not RPC verbs in the path
HTTP methodsGET read, POST create, PUT replace, PATCH partial, DELETE remove
Uniform interfaceStatus codes + headers; clients share conventions
Cacheable GETsSafe methods can use CDN/browser caches when headers allow
GET /users/42 POST /orders Idempotency-Key: ... PUT /orders/9 full replace PATCH /orders/9 partial update

3. REST vs RPC

REST (resource HTTP)RPC (gRPC / JSON-RPC)
ModelResources + verbsProcedure calls (CreateOrder)
ContractOpenAPI / conventionsProto / IDL strongly typed
CachingNatural for GETUsually not HTTP-cache friendly
BrowserNativeNeeds gateway / grpc-web
Internal servicesFineOften preferred (latency + types)

4. gRPC

RPC framework over HTTP/2 with Protocol Buffers. Strong contracts (.proto), streaming (unary, server, client, bidi), efficient binary.

FitAvoid when
Service-to-service inside meshBrowser-first public API (need grpc-web/gateway)
Strict schema evolutionAd-hoc human debugging is the main workflow
Streaming large result setsOnly need simple CRUD JSON

Mention deadlines/timeouts, status codes, and backward-compatible proto field changes (no renumbering).

5. WebSocket

Client <===== persistent TCP/TLS duplex =====> Server - chat messages, presence, collaborative cursors - game state ticks - live notifications (alternative: SSE one-way)

6. Server-Sent Events (SSE)

One-way server→client stream over plain HTTP (text/event-stream). The browser EventSource API reconnects automatically. Simpler than WebSocket when the client only needs pushes (live scores, job progress, notification ticks) and still sends commands via normal REST.

7. Long polling

Client opens a request; server holds it until an event arrives or a timeout fires; client immediately opens the next request. Predecessor to SSE/WebSocket — still useful behind restrictive networks.

Client GET /events?since=cursor → (server waits ≤ 30s) ← 200 { events: [...] } or 204 empty Client immediately GETs again Trade-off: more HTTP overhead than WS/SSE; simpler than managing sockets

8. GraphQL (brief)

Client specifies the shape of data in one request. Helps mobile teams avoid over/under-fetching. Costs: complex caching, N+1 resolver risks, and a heavy public schema to secure. Use when product needs flexible queries; do not default to it for every backend.

9. Sync vs async

SynchronousAsynchronous
CallerWaits for resultEnqueues work; continues
UXImmediate answerPending / eventually notified
FailureCoupled latency and outagesBuffer, retry, DLQ
ExamplesLogin, price quoteEmail, transcoding, fan-out
Sync path: API → User Service → Profile DB → response Async path: API → DB + Outbox → Queue → Workers → side effects

10. Message queues vs synchronous calls

Prefer queues whenPrefer sync RPC/HTTP when
Work can finish later (email, encode)User needs the answer in this request
Absorb traffic spikesLatency budget is tight (tens of ms)
Multiple consumers / fan-outSimple request/response, one dependency
Retries and DLQ are requiredStrong immediate consistency across the call

11. Protocol selection summary

ProtocolDirectionPick when
REST/HTTPReq/respPublic APIs, CRUD, cacheable reads
gRPCReq/resp + streamsInternal typed RPC, low overhead
WebSocketBidirectionalChat, collaborative, games
SSEServer → clientOne-way live updates over HTTP
Long pollingHeld req/respFallback when WS/SSE blocked
Message queuesAsyncDecouple, buffer, retry side effects

12. How to choose in a design interview

  1. External clients: HTTPS REST (or GraphQL if justified).
  2. Internal fan-out of CPU work: queue + workers.
  3. Live duplex: WebSocket gateway + pub/sub.
  4. One-way server push: SSE (or long poll as fallback).
  5. Tight internal RPC: gRPC with deadlines.

Quick revision

  • REST: stateless, resource URLs, HTTP methods; default public API.
  • REST vs RPC: resources/cache vs typed procedures.
  • gRPC: typed, efficient, streaming; great inside the datacenter.
  • WebSocket duplex; SSE one-way; long poll as legacy fallback.
  • Queues when async/spikes/retries; sync when UX needs the answer now.
  • Always set timeouts/deadlines on remote calls.
  • Protocol choice follows access pattern, not hype.