Opening your learning path
Progress is saved as you study.
Opening your learning path
Progress is saved as you study.
Opening your learning path
Progress is saved as you study.
Protocols (REST, gRPC, WebSocket, SSE), API design, pagination, and idempotency.
5 lessons · about 2 hours · Interview Soon · 1 worked case study
Networking & APIs is family 2 of 12 in the Thita system design course. It holds 4 lessons and 1 worked case study, and it is marked Interview Soon — the material that comes up in a standard interview loop.
Each one takes a product brief from this family through the whole worked answer — requirements, estimation, API, data model and trade-offs.
Most API protocol mistakes in interviews come from picking one tool for every traffic shape. Public CRUD APIs, internal RPC, bidirectional realtime, and one-way server streaming fail in different ways. Pick the protocol that matches the communication pattern before optimizing payload size, latency, or routing.
Classify the interaction first:
After that, the protocol choice is usually clear.
Use this decision tree before naming technologies.
1External CRUD API?
2 Yes → HTTP/REST
3
4Internal service-to-service RPC?
5 Yes → gRPC
6
7Client and server both send messages at arbitrary times?
8 Yes → WebSockets
9
10Only the server streams updates to the client?
11 Yes → SSE
12
13WebSockets or SSE blocked by clients, proxies, or platform limits?
14 Yes → Long pollingDirection matters. Clients asking for resources fit REST. Backend services calling backend services fit gRPC. Both sides pushing independently fits WebSockets. Server-only push fits SSE.
Use HTTP/REST for external CRUD APIs. REST works well for browsers, mobile apps, partners, public developers, and admin tools. Start with REST unless the system needs streaming or low-latency bidirectional communication.
REST maps resources to standard HTTP verbs. That gives you predictable behavior, simple debugging, gateway support, CDN support, browser support, and common operational tooling.
1GET /v1/users/123
2POST /v1/orders
3PATCH /v1/orders/456
4DELETE /v1/sessions/currentStateless means each request carries the data needed to process it, usually through cookies, session tokens, or authorization headers. The server can process the request without relying on a specific connection or local memory from a previous request.
REST also works well with caches. Product catalogs, profile images, public articles, search suggestions, and feature flag responses can often be cached in browsers, CDNs, API gateways, or service caches.
| Use case | Recommended protocol | Reason |
|---|---|---|
| Public CRUD API | REST | Broad client support and easy debugging |
| Browser or mobile app fetching resources | REST | Works naturally with HTTP caches and auth |
| Partner integrations | REST | Low integration friction |
| Admin dashboards | REST | Simple request/response is enough |
REST weakens when you need high-volume internal calls with strict schemas, streaming responses, or bidirectional communication. Use a different protocol for chat, multiplayer presence, collaborative editing, or internal fanout-heavy RPC.
Use gRPC for internal service-to-service communication when your organization controls both sides. gRPC uses protobuf schemas, binary encoding, HTTP/2 multiplexing, deadlines, status codes, and built-in streaming.
The main gain is tighter contracts and lower overhead. Protobuf messages are often around 10x smaller than equivalent JSON payloads, especially with repeated fields, numeric values, and nested objects.
1service UserService {
2 rpc GetUser(GetUserRequest) returns (User);
3 rpc ListUsers(ListUsersRequest) returns (stream User);
4}
5
6message GetUserRequest {
7 string user_id = 1;
8}Public APIs usually work better with HTTP/JSON because browsers, proxies, logs, debugging tools, and third-party developers handle it more easily. Expose gRPC publicly when clients are controlled, high-performance SDKs matter, and your team can own the integration work.
| Use case | Recommended protocol | Reason |
|---|---|---|
| Backend service calling another backend service | gRPC | Strong schema and efficient binary payloads |
| High-QPS internal RPC | gRPC | Lower serialization and network overhead |
| Streaming between backend services | gRPC streaming | Supports client, server, and bidirectional streams |
| Public third-party API | REST | Easier adoption and debugging |
A concrete interview answer: “I would expose REST externally and use gRPC internally between services.” That split gives public clients compatibility and gives internal services efficient typed calls.
Use WebSockets when the client and server both need to send messages at arbitrary times over a persistent connection. Chat, presence, multiplayer cursors, collaborative editing, live auctions, and game state updates fit this model.
Bidirectional traffic is the deciding factor. If the server streams updates and the client sends normal requests, use SSE for the stream and HTTP for client writes.
1const ws = new WebSocket("wss://api.example.com/chat");
2
3ws.onmessage = event => {
4 renderMessage(JSON.parse(event.data));
5};
6
7ws.send(JSON.stringify({ roomId: "r1", text: "hello" }));WebSockets add connection state. Plan for connection counts, heartbeats, reconnects, backpressure, load balancing behavior, authentication refresh, and fanout.
A clear design: clients connect to a WebSocket gateway, the gateway stores connection state, messages go through a broker, and gateways fan out messages to connected users. Without a gateway or broker, one backend can only push directly to clients connected to that backend.
| Use case | Recommended protocol | Reason |
|---|---|---|
| Chat | WebSockets | Users send and receive messages continuously |
| Presence | WebSockets | Online and offline changes need low latency |
| Collaborative editing | WebSockets | Clients send edits and receive remote edits |
| Live dashboard with server-only updates | SSE | One-way stream is simpler |
For LLM token streaming, use SSE by default. The client sends one prompt, then the server streams tokens back.
Use Server-Sent Events when the server streams events to the browser and the client can send commands through normal HTTP requests. SSE fits LLM token streaming, live feeds, progress updates, notification streams, and stock ticker updates.
SSE runs over normal HTTP and sends text events with text/event-stream. Browsers support automatic reconnects through EventSource, which reduces client-side connection code.
1const events = new EventSource("/v1/chat/completions/stream");
2
3events.onmessage = event => {
4 appendToken(JSON.parse(event.data).token);
5};
6
7events.onerror = () => events.close();SSE keeps the protocol simple. You get one-way streaming, normal HTTP behavior, easier gateway compatibility, and fewer custom connection rules. If the client needs to send another command, send a separate HTTP request.
For LLM systems, use this flow: POST the prompt or create a generation job, then stream tokens back with SSE. For cancellation, close the SSE connection or send a separate cancellation request.
| Use case | Recommended protocol | Reason |
|---|---|---|
| ChatGPT-style token streaming | SSE | Server streams tokens; client writes can use HTTP |
| Build progress updates | SSE | Server pushes status changes |
| Live news or activity feed | SSE | One-way ordered event stream |
| Collaborative editor | WebSockets | Client edits and server updates are both continuous |
Many candidates miss SSE in LLM interviews. Name SSE quickly when only the server streams data.
Use long polling when WebSockets or SSE fail because of legacy clients, restrictive proxies, old infrastructure, or platform limits. The client sends a request, the server holds it until an event is ready or a timeout occurs, then the client sends another request.
1Client → GET /events?cursor=100
2Server waits up to 30 seconds
3Server → 200 OK with events or empty response
4Client immediately repeats with new cursorLong polling works almost everywhere because it looks like normal HTTP. The costs are extra request overhead, higher latency variance, more server bookkeeping, and less efficient connection use than SSE or WebSockets.
Pick long polling only after explaining why SSE or WebSockets are unavailable. A good interview sentence: “If corporate proxies block persistent streaming, I would fall back to long polling with cursors and short timeouts.”
| Use case | Recommended protocol | Reason |
|---|---|---|
| Modern browser live feed | SSE | Simpler and more efficient |
| Corporate network blocking streams | Long polling | Most compatible fallback |
| Legacy mobile client | Long polling | Works with basic HTTP stacks |
| Bidirectional realtime app | WebSockets | Long polling adds avoidable overhead |
Long polling needs cursors or sequence numbers. Without them, reconnects can lose or duplicate events. Duplicates are usually acceptable if the client de-duplicates by event ID. Loss is harder to repair.
Keep load balancing brief unless the problem centers on routing. Most designs can start with round-robin behind a managed load balancer. Add health checks, least-connections, or consistent hashing when the traffic pattern requires them.
The first split is L4 load balancing versus L7 load balancing. L4 routes TCP or UDP connections without reading HTTP paths or headers. L7 reads HTTP and can route by host, path, headers, cookies, or method.
| Layer | Routes by | Best for |
|---|---|---|
| L4 | IP, port, TCP/UDP connection | Very high throughput, simple pass-through |
| L7 | HTTP host, path, headers, cookies | API routing, canaries, auth-aware routing |
| DNS load balancing | Domain resolution | Coarse regional distribution |
Use L7 for most API interview designs because it can route /api, /upload, /stream, and /admin to different backends. Use L4 for maximum throughput, non-HTTP protocols, or simple TCP pass-through.
Round-robin is the default algorithm to state first. Use least-connections for long-lived WebSocket connections because equal request distribution can still produce uneven active connection counts. Use consistent hashing when a request must land on a specific shard or cache node.
WebSockets add one load balancer issue: persistent connections stay attached to a backend. You can avoid sticky sessions by storing connection ownership in a gateway layer and routing messages through a broker. Simple first versions often use sticky routing.
A CDN caches content near users to reduce latency, origin load, and bandwidth cost. The default model is pull-based: the CDN fetches from your origin on the first miss, caches the response at the edge, and serves later requests from that edge until the object expires or is invalidated.
CDNs work best for static and cacheable content: images, videos, JavaScript bundles, CSS, public documents, product metadata, and public API responses. Personalized, rapidly changing, or authorization-sensitive responses need careful cache keys and headers.
Cache keys and Cache-Control headers matter most. If a candidate says “put a CDN in front,” they should also name the cacheable object and the TTL.
1Cache-Control: public, max-age=300, stale-while-revalidate=60
2ETag: "product-123-v42"Use short TTLs for frequently changing public data and long TTLs with versioned filenames for immutable assets. Cache /app.8f3a.js for a year because the filename changes on deploy. Cache /api/products/123 for minutes because product inventory can change.
| Content | CDN recommendation | Reason |
|---|---|---|
| Versioned JS, CSS, images | Long TTL | File name changes when content changes |
| Public product pages | Short to medium TTL | Reduces origin load with bounded staleness |
| User-specific dashboard | Avoid shared CDN cache | Reduces risk of leaking personalized data |
| Video or large media | Use CDN | Saves bandwidth and improves playback latency |
CDNs also absorb traffic spikes. If a viral product page hits the origin directly, the database may become the bottleneck. If the page is cached at the edge, most requests never reach your service.
The first request misses at the edge and is pulled from the origin, then cached for the max-age. The next request is served from the edge and never reaches the origin.
Use this table when you need to answer fast and return to the system design.
| Protocol | Communication pattern | Default use | Main tradeoff |
|---|---|---|---|
| REST | Request/response | External CRUD APIs | Simple and compatible; less efficient for internal high-QPS RPC |
| gRPC | Request/response plus streaming | Internal service-to-service | Efficient and typed; harder for public and browser clients |
| WebSockets | Persistent bidirectional | Chat, presence, collaboration | Flexible realtime; more connection state |
| SSE | Persistent server-to-client | LLM token streaming, live feeds | Simple streaming; same-channel client writes need another path |
| Long polling | Repeated delayed request/response | Compatibility fallback | Broad support; more overhead and latency variance |
A strong answer picks the protocol from the traffic shape, mentions one operational concern, then moves to storage, fanout, consistency, or scaling.
Default: Use REST for external CRUD APIs, gRPC for internal service-to-service calls, WebSockets for bidirectional realtime, SSE for server-to-client streaming, and long polling as a compatibility fallback. Put APIs behind an L7 load balancer with round-robin by default. Switch to least-connections for long-lived connections. Use a pull-based CDN for cacheable public content with explicit Cache-Control headers.
Common protocol failure modes:
Long polling re-asks after every answer. SSE opens one connection and the server pushes down it. WebSockets let both sides send at any time over one connection.
| Category | 2026 numbers | How to use in protocol decisions |
|---|---|---|
| Same-AZ latency | < 1ms | Internal gRPC calls inside one AZ can be fast, but fanout still multiplies latency. |
| Cross-AZ latency | 1-2ms | Acceptable for most synchronous backend calls; avoid long chains. |
| Cross-region latency, US-EU | 70-90ms | Realtime collaboration feels delayed across oceans without regional placement. |
| US-India latency | 150-250ms | User-facing realtime needs nearby gateways or regional edges. |
| CDN edge latency | 5-30ms | Cache static and public content at the edge before scaling origin services. |
| S3 first byte | 50-100ms | Use CDN for frequently accessed objects instead of serving directly from object storage. |
| Datacenter network | 25-100 Gbps | Payload size still matters at high QPS; protobuf helps internal services. |
| Redis throughput | 100K-500K ops/sec per instance | Useful for presence, connection metadata, rate limits, and ephemeral state. |
| Postgres single primary | 10K-50K TPS; tens of TB before sharding | Check load before adding sharding. |
| Kafka cluster | 1M+ msg/sec; single-digit ms latency | Good broker choice for WebSocket fanout, event delivery, and async pipelines. |
| General-purpose server | 512 GiB RAM, 128 vCPUs | Modern machines are large; avoid old assumptions about tiny servers. |
| Memory-optimized server | 4 TB RAM | Large in-memory fanout metadata or caches are plausible before custom partitioning. |
| High-memory server | 24 TB RAM | Specialized cases can hold very large working sets; interviews rarely need this first. |
| Local SSD | 60 TB | Local storage can be large, but persistent API state usually belongs in managed storage. |
| Local HDD | 336 TB | Useful for cost-heavy storage, not low-latency API serving. |
Use these numbers to avoid over-design. If a REST API has 2,000 QPS and small responses, the protocol is probably fine. If an internal service graph makes 30 calls per request across regions, protocol efficiency will not fix the topology.
For estimation, keep the protocol math short:
| Estimate | Formula | Example use |
|---|---|---|
| Average QPS | DAU × actions/user ÷ 86,400 | Size external REST traffic. |
| Peak QPS | 2-3 × average QPS | Choose load balancer and service capacity. |
| Bandwidth | QPS × average response size | Decide whether JSON size, protobuf, or CDN matters. |
| Storage | writes/day × bytes/write × retention days | Size logs, messages, and event streams. |
Spend 2-3 minutes estimating QPS, payload size, and connection count. Then design around the dominant constraint.
Apply this protocol decision tree when a case involves external APIs, internal service calls, realtime updates, LLM streaming, load balancing, or CDN caching.