04. Communication: cheatsheets

4 lessons, one page each when printed.

System Design · 04. Communication · 10 min · Beginner

REST, RPC & GraphQL

Three ways for a client and a server to talk, and what each one costs.

In short

The same screen cost 2 trips and 12 KB with fixed REST endpoints, and 1 trip and about 1 KB with a tailored RPC call or a GraphQL query.

REST names resources and uses status codes. RPC and gRPC call actions with compact messages. GraphQL lets the client pick fields, but needs care with N+1 queries.

Key ideas

  • REST, RPC and GraphQL are three styles for shaping that request and response. All three usually travel over HTTP. (step 1)
  • Pick by who calls you. Strangers and browsers: REST. Your own services: gRPC. Many different screens: GraphQL. (step 9)

Good to know

  • REST is easy to guess, easy to test with a browser or curl, and easy to cache. That is why most public APIs use it. (step 2)
  • gRPC is a good fit between your own services: fast, typed, and streams. Browsers cannot call it directly without a helper. (step 6)
  • GraphQL suits many different clients (phone, web, watch) that each need a different slice of the same data. (step 7)

Watch out

  • Do not return 200 with an error hidden in the body. Monitoring and caches look at the status code. (step 3)
  • Fixed endpoints return a fixed shape. Every screen that wants a different shape either wastes data or makes extra calls. (step 4)
  • The price: one method per screen. When the screen changes, the server method changes too. (step 5)
  • The client sees one fast request, but the database pays for the hidden loop. Watch query counts, and limit how deep a query may go. (step 8)
Phone appAPI serverUsers serviceOrders service

Key numbers

Round trips
1
Data received
1 KB
Screen time
80 ms

Terms

Round trip
One request and its response; on a mobile network each one costs tens of milliseconds.
REST
An API style where each thing is a resource with a URL and HTTP methods say what to do with it.
HTTP status code
A number at the start of every response: 2xx success, 4xx client mistake, 5xx server failure.
Over-fetching
Receiving more data than the screen needs because the endpoint has a fixed shape.
Under-fetching
Needing extra calls because one endpoint did not return everything the screen needs.
RPC
Calling a named action on a server as if it were a local function.
gRPC
An RPC system that uses typed .proto files, binary Protocol Buffers and HTTP/2, with streaming.
GraphQL
A query language where the client names the exact fields it wants from one endpoint.
Resolver
The small function that fills in one GraphQL field.
N+1 problem
One query for a list plus one more per item, which a batched lookup (DataLoader) avoids.

System Design · 04. Communication · 10 min · Intermediate

Message Queues

Put slow work in a line and let workers handle it later.

In short

A queue lets the API answer in 52 ms instead of 850 ms, and lets workers do the slow part later. A pool of 4 workers does 5 jobs a second and the line absorbs spikes.

Ack after the work, make jobs idempotent, send poison messages to a dead-letter queue, partition by key when order matters, and watch the depth.

Key ideas

  • Work the user does not need right now should leave the request path. (step 1)
  • The queue is a buffer between a fast producer and a slower consumer. (step 3)
  • Ack after the work is done, never before. An early ack loses the job if the worker dies. (step 6)
  • A queue hides a slow consumer; it does not fix it. Capacity must still match the average load. (step 10)

Good to know

  • A queue turns "do it now and wait" into "promise to do it soon". The HTTP answer is often 202 Accepted. (step 2)
  • Need more speed? Add workers. They are stateless, so any number can read the same queue. (step 4)
  • Idempotent jobs are safe to retry. This one habit makes queues, retries and crashes much less scary. (step 7)

Watch out

  • Users do not wait, but the last email is sent minutes late. Watch the queue depth and the age of the oldest message. (step 5)
  • Put an alert on the DLQ. A DLQ nobody looks at is only a quiet place to lose work. (step 8)
  • Strict order costs parallelism. Keep it only where the business needs it. (step 9)
UsersSignup APIEmail queueWorker 1Worker 2Worker 3Worker 4

Key numbers

Queue depth
~0
Workers
4
Signup p99
52 ms

Terms

Message queue
A line where producers leave messages and consumers take them later, so slow work leaves the request.
Producer
The code that puts messages into the queue.
Consumer
The code (a worker) that takes messages from the queue and does the job.
Worker pool
Several workers reading one queue; each message goes to one of them.
Acknowledgement (ack)
A worker's note that a message is done, after which the queue deletes it.
Visibility timeout
How long a taken message stays hidden before the queue offers it to another worker.
At-least-once delivery
The queue may deliver a message more than once, but not lose it.
Idempotency
Doing a job twice gives the same result as doing it once.
Dead-letter queue
A side queue that keeps messages which failed too many times.
Partition key
A value such as user id that sends related messages to the same partition so they stay in order.
Backpressure
Slowing or rejecting producers when consumers cannot keep up.

System Design · 04. Communication · 10 min · Intermediate

Pub/Sub & Events

Announce that something happened, and let anyone who cares listen.

In short

The publisher sends one event and makes 1 call, not 3 or 4. The broker fans it out: 500 orders a second to 4 subscribers is 2,000/s.

A log keeps events so readers track their own offsets and can replay. Partitions and consumer groups share the work and keep order per key.

Key ideas

  • An event says what happened ("order placed"). A command says what to do ("send an email"). Pub/sub carries events. (step 2)
  • The log is the source of the story. Subscribers are just different positions in it. (step 5)

Good to know

  • Loose coupling: teams add listeners without asking the publisher's team. (step 3)
  • More partitions means more parallel readers and writers. Pick the key so related events stay together. (step 6)
  • Replay turns "we lost a day of statistics" into "we ran the job again". (step 8)

Watch out

  • Every new listener means a change in the one service that should not care who listens. (step 1)
  • Fan-out multiplies traffic. A topic with 1,000 subscribers turns 500 events a second into 500,000 deliveries a second. (step 4)
  • The number of partitions is the ceiling for parallelism inside one group. (step 7)
  • Write down event names and shapes like a public API, and version them. (step 9)
Order serviceEvent logEmailStockAnalyticsFraud check

Key numbers

Calls per order
1
Subscribers
4
Deliveries
2,000/s

Terms

Publish/subscribe
A style where senders publish events to a topic and any number of subscribers receive them.
Topic
A named channel that events are published to.
Event
A message saying that something happened, such as order.placed.
Subscription
A subscriber's own place in a topic, so each reader gets its own copy.
Fan-out
One published event becoming many deliveries, one per subscriber.
Event log
An append-only list of events that stays for a set time and is not deleted when read.
Offset
The position of the next event a reader will read in a log.
Partition
One slice of a topic; order is kept inside a partition, chosen by a key.
Consumer group
A set of workers that share a topic's partitions, each partition read by one of them.
Replay
Resetting the offset to read old events again.
Event-driven design
Services react to events instead of being called directly.

System Design · 04. Communication · 10 min · Intermediate

Real-time Updates

How a server tells a browser the moment something changes.

In short

Polling asks 50,000 times a second and gets empty answers; long polling and SSE hold a request open; WebSockets give a two-way pipe. Push removes the wait: about 50 ms instead of up to 2 s.

Many connections need many gateways, pub/sub to reach the right one, heartbeats for presence, and clients that reconnect with backoff and catch up.

Key ideas

  • Only listening: SSE. Talking both ways, fast: WebSockets. Rarely changing: plain polling is fine. (step 4)
  • Reconnect is the normal case, not the rare one. Design for it: backoff, jitter and catch-up from the last id. (step 8)

Good to know

  • It works everywhere, even through old proxies. The cost is a new request after every message. (step 2)
  • SSE is the least work when the browser only listens. (step 3)
  • Pub/sub lets you add gateways without changing the others. Gateways can come and go. (step 6)
  • Scale by adding gateways, and by sharding pub/sub channels and the presence store by key. (step 9)

Watch out

  • Polling is simple and fine for slow data (a build status every minute). For anything live, it is wasteful and late. (step 1)
  • Connection servers hold state (who is connected). Keep them thin: they only move messages, while the logic lives elsewhere. (step 5)
  • Do not tell all your friends every time you flicker offline. Add a short delay, or send presence only for the chat that is open. (step 7)
100,000 usersLoad balancerGateway 125,000Gateway 225,000Gateway 325,000Gateway 425,000Pub/sub

Key numbers

Open connections
100,000
New requests/s
~0
Delay
~50 ms

Terms

Polling
The client asks for news on a timer, even when there is none.
Long polling
The server holds a request open until there is news, and the client asks again after each answer.
Server-Sent Events (SSE)
One long HTTP response that the server keeps writing to; one-way, with automatic reconnect.
WebSocket
A connection upgraded from HTTP that lets both sides send messages at any time.
Gateway (connection server)
A server that only holds open connections and moves messages to and from them.
Pub/sub channel
How a gateway reaches a user connected to a different gateway: publish to a channel the right gateway subscribes to.
Presence
Who is online, tracked with heartbeats and keys that expire.
Heartbeat
A small periodic message that tells the server the client is still there.
Thundering herd
Many clients reconnecting at the same moment and overloading the servers.
Backoff with jitter
Waiting a growing, random time before each retry so clients spread out.