Networking & APIs: HTTP, REST, gRPC, WebSockets
Choose an API style and protocol for a given client and traffic pattern.
By Invicly Tech, , in System Design Deep Dive. About 10 minutes to read.
In short
Clients and services talk over protocols like HTTP, and API styles like REST, gRPC and GraphQL shape those conversations. Choose based on who the client is, how chatty the traffic is and whether the server must push updates.
Explained simply
When an app shows your messages, it sent a request across the internet and got an answer back. Networking is how that request travels. An API is the agreed shape of the question and the answer, so both sides understand each other.
Think of the postal system. The protocol is the set of postal rules: how to write an address and what goes on the envelope. The API is the specific form you fill in at one office. HTTP is the postal system most of the web uses.
On top of HTTP there are different styles. REST treats everything as resources like /users/42. gRPC sends compact binary messages between services. GraphQL lets the client ask for exactly the fields it wants. WebSockets keep a line open so either side can talk at any time.
Choosing one comes down to three questions. Who is calling: a browser, a mobile app or another service? How often do they talk? And does the server need to push news to the client without being asked?
Press Play on a diagram to walk through it one step at a time.
- Resources over HTTP verbs
- JSON, human readable
- Easy caching with HTTP
- Best for public APIs
- Protobuf over HTTP/2
- Compact and fast
- Typed contracts, streaming
- Best for service-to-service
- Client picks fields
- One endpoint, typed schema
- Avoids over-fetching
- Best for varied frontends
- Client asks every few seconds
- Simple but wasteful
- Delayed updates
- Server streams events one way
- Plain HTTP, auto reconnect
- Good for feeds and dashboards
- Full duplex persistent connection
- Low latency both directions
- Good for chat and games
- Client to DNS resolver: Where is api.example.com?1Where is api.example.com?
- DNS resolver to Client: 203.0.113.102203.0.113.10
- Client to API server: TCP SYN3TCP SYN
- API server to Client: SYN-ACK (1st round trip done)4SYN-ACK (1st round trip done)
- Client to API server: ACK + TLS ClientHello5ACK + TLS ClientHello
- API server to Client: TLS ServerHello + certificate (2nd)6TLS ServerHello + certificate (2nd)
- Client to API server: GET /v1/feed (encrypted)7GET /v1/feed (encrypted)
- API server to Client: 200 OK + JSON (3rd)8200 OK + JSON (3rd)
- Browser or public client
- REST + JSON
- GraphQL if many screens need different fields
- Service to service
- gRPC for speed and typed contracts
- Server pushes, client listens
- Server-Sent Events
- Both sides talk constantly
- WebSockets
- Big file upload or download
- Presigned URL straight to object storage
In depth
What one HTTPS request really costs
Before the first byte of your data moves, a new connection needs setup. The client looks up the server's address with DNS. Then a TCP handshake takes one round trip, and a TLS 1.3 handshake for encryption takes another. Only then does the request go out, taking a third round trip.
Inside one data centre a round trip is under a millisecond, so this barely matters. Between continents it is about 150 ms, so a fresh connection can cost 450 ms before any work happens. That is why clients reuse connections (keep-alive and connection pools) and why CDNs place servers close to users.
HTTP/1.1, HTTP/2 and HTTP/3
HTTP/1.1 sends one request at a time per connection, so browsers open about six connections per site to work in parallel. HTTP/2 multiplexes many requests as separate streams over one TCP connection and compresses headers, which saves handshakes.
HTTP/2 has one weakness: TCP delivers bytes strictly in order, so one lost packet stalls every stream until it is resent. HTTP/3 runs over QUIC, which is built on UDP. Each stream recovers from loss on its own, and the connection and encryption handshakes are combined. It helps most on mobile networks with lossy signals.
- One request at a time per connection
- Browsers open about 6 per site
- No header compression
- Many streams on one TCP connection
- Compressed headers
- One lost packet stalls every stream
- Runs over QUIC on UDP
- Each stream recovers from loss alone
- Connection and TLS handshakes combined
Designing REST endpoints that age well
Use nouns for resources and HTTP methods for actions: GET to read, POST to create, PUT or PATCH to update, DELETE to remove. Return honest status codes so clients can react without parsing text. Give errors one consistent JSON shape with a machine-readable code and a human message.
Public APIs live for years, so plan for change. Put a version in the path, like /v1/. Adding new optional fields is safe. Removing or renaming fields breaks old apps that people never update, so do that only in a new version.
- 201 Created, 204 No Content
- 400 bad input, 401 not logged in, 403 not allowed
- 404 not found, 409 conflict
- 429 too many requests, 503 try again later
Keeping WebSocket connections at scale
A WebSocket stays open for minutes or hours, so the server holding it becomes stateful: it is the only one that can talk to that user. One well-tuned server can hold tens of thousands to hundreds of thousands of mostly idle connections, limited by memory and file descriptors.
To send a message to a user, other servers must find which server holds their connection. A shared registry in Redis, mapping user to server, plus a pub/sub channel between servers, solves this. Send heartbeats every 20 to 30 seconds so dead connections are noticed and proxies do not close idle ones. During deploys, close connections gradually and let clients reconnect with random delays.
- Server A to Redis: Which server holds user 42?1Which server holds user 42?
- Redis to Server A: Server B2Server B
- Server A to Redis: Publish on server B's channel3Publish on server B's channel
- Redis to Server B: Message for user 424Message for user 42
- Server B to User 42: Push over the open WebSocket5Push over the open WebSocket
Learn it in 4 short steps
About 45m each. Track them with a timer in your plan.
- 1Compare REST, gRPC and GraphQL~45m
- 2Know when to use WebSockets or SSE~45m
- 3Design a REST API with pagination~45m
- 4Choose a protocol for a scenario~45m
Key points
- REST suits public, cacheable, resource-oriented APIs.
- gRPC suits internal low-latency calls with strict typed contracts.
- Use WebSockets when both sides send frequently; SSE when only the server pushes.
- Paginate list endpoints with cursors rather than large offsets.
- Make writes idempotent where clients may retry.
Key terms
Tap a card to flip it. 0/5 known
Examples
GET /v1/users/42/posts?limit=20&cursor=eyJpZCI6OTl9
200 OK
{
"items": [ { "id": 98, "text": "hi" } ],
"nextCursor": "eyJpZCI6Nzh9"
}
POST /v1/payments
Idempotency-Key: 7f3c-91ab
{ "amount": 500, "currency": "USD" }Cursor pagination and an idempotent write.
A REST API for a book review site
Features: browse books, read one book, write a review, edit or delete your own review. Each becomes an endpoint with a resource noun and a method. Notice the status codes: 201 with a Location header after creating, 204 when there is nothing to return, 403 when someone edits another person's review. The list uses a cursor so pages stay stable when new books are added. Errors share one JSON shape.
GET /v1/books?limit=20&cursor=abc -> 200 { items, nextCursor }
GET /v1/books/123 -> 200 book | 404
POST /v1/books/123/reviews -> 201 + Location: /v1/reviews/987
PATCH /v1/reviews/987 -> 200 | 403 if not the author
DELETE /v1/reviews/987 -> 204
Error body:
{ "error": { "code": "REVIEW_TOO_LONG", "message": "Max 5000 characters" } }Choosing a protocol for live sports scores
Requirement: 5 million fans watch a match and scores should update within a few seconds. Option 1, polling every 5 seconds: 5M ÷ 5 = 1 million requests per second, almost all returning "no change". Option 2, WebSockets: works, but fans never send anything, so two-way is wasted complexity. Option 3, Server-Sent Events: one long HTTP response per fan, the server pushes only when the score changes, and browsers reconnect automatically. Choose SSE. Each SSE server subscribes to a pub/sub topic for the match, so one score event fans out to every connected fan.
Quick reference
- New HTTPS connection ≈ 3 round trips before the response; reuse connections
- Cross-continent round trip ≈ 150 ms; same data centre < 1 ms
- HTTP/2: many requests on one connection; HTTP/3: QUIC over UDP, better on lossy networks
- Version public APIs (/v1); adding fields is safe, removing or renaming is not
- 429 = slow down (send Retry-After); 503 = temporarily unavailable
- WebSocket servers are stateful: keep a user → server map in a shared store
- Heartbeat every 20–30 s so dead or idle connections are detected
Common mistakes
- Using offset pagination on huge tables, which gets slower per page.
- Choosing WebSockets for rare updates where polling or SSE suffices.
- Exposing gRPC directly to browsers without a gateway or gRPC-Web.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Give the HTTP method, path and success status code for: create an order, fetch an order, change its shipping address, cancel it by deleting it.
- Exercise 2medium
Design a cursor-paginated endpoint that lists a user's notifications, newest first. Show a request, a response, and explain what the cursor contains.
- Exercise 3hard
Design connection handling for 2 million users connected by WebSocket at once. How many servers, how a message reaches a user on another server, and what happens during a deploy?
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Is REST the same as HTTP?
- No. HTTP is the protocol that carries requests. REST is a style of designing APIs on top of HTTP using resources, methods and status codes.
- Should I use GraphQL for everything?
- No. It shines when many different screens need different slices of data. For simple public APIs, REST is easier to cache and operate, and gRPC is better between internal services.
- Do WebSockets work behind a load balancer?
- Yes, as long as it supports the HTTP upgrade and long-lived connections, which AWS ALB, NGINX and most modern balancers do. Set idle timeouts longer than your heartbeat interval.