Communication (TCP, UDP, RPC, REST)¶
HTTP (Hypertext Transfer Protocol)¶
A method for encoding and transporting data between client and server. It's a request/response protocol: clients issue requests, servers issue responses with content and status info. HTTP is self-contained, so requests/responses can flow through intermediate routers and servers (load balancing, caching, encryption, compression).
A request = a verb (method) + a resource (endpoint).
| Verb | Description | Idempotent* | Safe | Cacheable |
|---|---|---|---|---|
| GET | Reads a resource | Yes | Yes | Yes |
| POST | Creates a resource or triggers a process | No | No | Yes (if freshness info) |
| PUT | Creates or replaces a resource | Yes | No | No |
| PATCH | Partially updates a resource | No | No | Yes (if freshness info) |
| DELETE | Deletes a resource | Yes | No | No |
* Can be called many times without different outcomes.
HTTP is an application-layer protocol relying on lower-level TCP and UDP.
TCP (Transmission Control Protocol)¶
A connection-oriented protocol over IP. Connection is established/terminated with a handshake. Packets are guaranteed to arrive in order and uncorrupted via:
- Sequence numbers and checksums per packet.
- Acknowledgements and automatic retransmission.
If the sender gets no correct response, it resends. Multiple timeouts → connection dropped. TCP also implements flow control and congestion control. These guarantees add delay and are less efficient than UDP.
High throughput web servers keep many TCP connections open → high memory use. Connection pooling (or switching to UDP) helps.
Use TCP when: you need all data to arrive intact, or want automatic use of network throughput. Examples: web servers, databases, SMTP, FTP, SSH.
UDP (User Datagram Protocol)¶
Connectionless. Datagrams (like packets) are guaranteed only at the datagram level — they may arrive out of order or not at all. No congestion control. More efficient than TCP (fewer guarantees).
UDP can broadcast to all devices on a subnet (useful for DHCP, where the client has no IP address yet).
Use UDP when: you need lowest latency, late data is worse than lost data, or you want to implement your own error correction. Examples: VoIP, video chat, streaming, real-time games.
TCP vs UDP¶
| TCP | UDP | |
|---|---|---|
| Connection | Connection-oriented | Connectionless |
| Delivery | Guaranteed, ordered | Best-effort, unordered |
| Overhead | Higher (handshake, ACKs) | Lower |
| Use cases | Web, DB, SSH | VoIP, video, games |
RPC (Remote Procedure Call)¶
A client causes a procedure to execute in a different address space (usually a remote server), coded like a local call — hiding network details. Remote calls are slower/less reliable than local calls, so distinguish them.
Popular frameworks: Protobuf, Thrift, Avro.
Flow: client program → client stub (marshals args) → OS sends → server OS → server stub (unmarshals, calls procedure) → response in reverse.
Sample RPC call:
GET /someoperation?data=anId
POST /anotheroperation
{
"data": "anId";
"anotherdata": "another value"
}
RPC focuses on exposing behaviors, often used for internal, performance-sensitive calls.
Choose an SDK/RPC when: you know your platform, want to control how logic is accessed/errored, or performance is the primary concern.
Disadvantages: tight coupling to implementation; new API per operation; hard to debug; may not leverage existing caching/proxies out of the box.
REST (Representational State Transfer)¶
An architectural style with a client/server model: the client acts on resources managed by the server. Communication must be stateless and cacheable.
Four qualities of a RESTful interface:
- Identify resources (URI in HTTP) — same URI regardless of operation.
- Change with representations (verbs in HTTP) — use verbs, headers, body.
- Self-descriptive errors (status codes) — don't reinvent the wheel.
- HATEOAS — the service should be fully accessible in a browser.
Sample REST calls:
GET /someresources/anId
PUT /someresources/anId
{"anotherdata": "another value"}
REST focuses on exposing data, minimizing client/server coupling. Being stateless, it's great for horizontal scaling and partitioning.
Disadvantages: poor fit for non-hierarchical operations; limited verbs; nested resources need multiple round-trips; responses can bloat over time.
RPC vs REST comparison¶
| Operation | RPC | REST |
|---|---|---|
| Signup | POST /signup |
POST /persons |
| Resign | POST /resign |
DELETE /persons/1234 |
| Read person | GET /readPerson?personid=1234 |
GET /persons/1234 |
| Read person's items | GET /readUsersItemsList?personid=1234 |
GET /persons/1234/items |
| Add item | POST /addItemToUsersItemsList |
POST /persons/1234/items |
| Update item | POST /modifyItem |
PUT /items/456 |
| Delete item | POST /removeItem |
DELETE /items/456 |
Key takeaways¶
-
RPC = verbs/behaviors (internal, performance). REST = nouns/resources (public, scalable, cacheable).
-
TCP vs UDP is a reliability vs latency trade-off.
- HTTP sits on top of TCP/UDP and is the workhorse of public APIs.
Design a Chat App like WhatsApp¶
Requirements and constraints¶
Start by clarifying the scope: one-on-one messages, group messages, media attachments, online presence, read receipts, multi-device sync, and offline delivery. The main non-functional requirements are low latency for message delivery, reliable and ordered delivery, high availability, and horizontal scalability. Unlike a URL shortener or a feed, a chat system is write-heavy and real-time, so the architecture must optimize for pushing data to connected users rather than only serving reads.
High-level architecture¶
Clients maintain persistent WebSocket connections to stateless connection/gateway servers. WebSocket is chosen over normal HTTP polling because it provides full-duplex, low-latency delivery while using TCP's reliable ordered stream. These gateway nodes authenticate users and register which user and device is connected to which node in a distributed session store such as Redis or etcd. Behind the gateways, separate services handle messaging, presence, group membership, notifications, and media. Service discovery helps these services locate each other as nodes scale up and down.
Message flow and ordering¶
When Alice sends a message to Bob, Alice's client includes a client-generated message ID and the conversation ID. The message service receives the message over the gateway, assigns a server-side monotonic sequence number for that conversation, and durably writes the message to a store sharded by conversation ID. Only after the write succeeds does the service return a server acknowledgement to Alice with the assigned sequence number. If Bob is online, the service consults the presence and session store to find the gateway holding Bob's connection, then pushes the message to Bob's client. Bob's client returns a delivery or read acknowledgement. If Bob is offline, the message is placed in an undelivered queue or per-user inbox so it can be delivered when Bob reconnects. Message IDs and per-conversation sequence numbers are essential for retries, idempotency, and preserving order on multi-device clients.
Presence and online status¶
Presence should be designed as an eventually consistent system. Clients send periodic heartbeats over their persistent connection, and the gateway refreshes a TTL-backed online flag and last-seen timestamp in Redis. If heartbeats stop or the TCP connection closes, the presence entry expires. This design favors availability and low cost over perfectly accurate presence. It is usually acceptable for online status and last-seen time to be slightly stale for a few hundred milliseconds, while message persistence and acknowledgements must be much stronger.
Storage model¶
Relational data such as users, groups, and memberships fits a SQL database with transactions. Message history is different: it is high-volume, append-heavy, rarely updated, and queried mostly by conversation. A good choice is to shard messages by conversation ID using consistent hashing or range-based partitioning. That keeps fetching a conversation's history local to one shard, although very active groups can create hot shards. A hybrid inbox model often works best: write the message once to the conversation log, then fan out a copy or reference to each recipient's inbox for ordinary one-on-one and small-group chats. For very large groups or broadcast channels, it is cheaper to keep the group log and let clients read from it on demand rather than duplicating a message into thousands of inboxes.
Group chat and media handling¶
For small and medium groups, fan-out on write is simple and fast: the messaging service persists the group message once, then enqueues delivery tasks or pushes the message to each member's connected devices. For very large groups, eager fan-out becomes expensive, so the system should switch to fan-out on read, where clients pull the latest group messages from the shared group log. Media files do not travel through the chat servers. A client uploads an image or video to object storage, receives an object URL, and sends that URL as part of the message. The receiving client downloads the object from object storage through a CDN, keeping the chat servers focused on small, real-time messages and metadata.
Multi-device and security¶
Each device has its own session. When a user logs in on a phone and a laptop, both register separate connections. For one-on-one messages, the system fans out to all active sessions for the recipient's user ID. If end-to-end encryption is required, clients exchange or register public keys through a key service, and messages are encrypted before they reach the server. The server still handles routing, persistence, and ordering, but it stores only ciphertext. Group encryption is more complex and typically uses a group session key distributed to all members.
Scaling and failure behavior¶
The stateless gateway tier scales horizontally behind load balancers because connection routing state lives in Redis or etcd, not on local disk. The message service can be partitioned by conversation or user. Asynchronous task queues and workers handle fan-out, push notifications, and media processing. Databases use replication: read replicas serve history, while the write path remains durable enough that after a server acknowledges a message, the message is not lost if a node fails. The central trade-off is to accept eventual consistency for presence and last-seen data while keeping accepted-message persistence strong and ordered. This combination of persistent WebSockets, sharded message storage, presence with TTLs, and hybrid fan-out is what allows a WhatsApp-like system to deliver billions of small messages per day with low latency and high reliability.
flowchart LR
A[User A] -->|WebSocket| G[Gateway]
B[User B] -->|WebSocket| G
G --> M[Message Service]
M --> D[(Message Store)]
G --> P[Presence Service]
M -->|fan-out| A
M -->|fan-out| B
Common Interview Questions¶
Design Google Docs (real-time sync)
Why it's asked here: real-time collaboration is a communication protocol problem.
Key points to discuss:
- WebSocket/TCP for real-time edits; why UDP fits games but not doc sync.
- Operational transforms (OT) / CRDTs to merge concurrent edits.
- Client/server communication model and connection recovery.
- Latency vs consistency when propagating edits.
flowchart LR
A[User A] -->|WebSocket| S[Sync server]
B[User B] -->|WebSocket| S
S -->|OT / CRDT| D[Converged doc]
D --> A
D --> B
Design a real-time multiplayer game
Why it's asked here: games force the UDP-vs-TCP decision.
Key points to discuss:
- UDP for position/state updates (low latency, loss-tolerant).
- TCP for login, chat, and transactions (reliable).
- Client-side interpolation/prediction to hide packet loss.
- When to add your own reliability layer on top of UDP.
flowchart LR
P1[Player 1] -->|UDP| GS[Game server]
P2[Player 2] -->|UDP| GS
P1 -->|TCP| A[Auth / chat]
GS -->|state| P1
GS -->|state| P2
Further reading¶
- Do you really know why you prefer REST over RPC
- Networking for game programming (UDP vs TCP)
- REST vs JSON-RPC
Design a Real-Time Multiplayer Game — Full Walkthrough¶
For scale, assume a session-based competitive game with about 10 million daily active players and 1 million concurrent players at peak. During active play, each client sends input and state updates about 20 times per second, so the peak input/update rate is roughly 20 million updates per second across all active sessions. Each update is small, typically on the order of 100 bytes for position, velocity, orientation, and input flags, but aggregate edge bandwidth is substantial and must be handled by regional relays rather than a single origin. The dominant functional requirements are matchmaking, joining a match, sending real-time inputs, receiving authoritative game state, and supporting slower non-real-time features such as profiles, friends, chat, leaderboards, inventory, and purchases. The main non-functional requirements are sub-100 ms latency for time-critical state, low jitter, high availability for the lobby and persistence layers, and tolerance of packet loss without freezing gameplay. Raw telemetry and replay recording can produce hundreds of terabytes per day if stored uncompressed, so the design samples, compresses, and retains only key events or highlights unless full replays are explicitly required.
The high-level architecture separates real-time traffic from ordinary application traffic. Clients connect to a regional edge relay layer over UDP for gameplay traffic, because UDP has lower overhead than TCP and avoids the head-of-line blocking caused by retransmitting stale movement packets. The relays forward packets to an authoritative game server assigned by a matchmaker. In parallel, clients use TCP or TLS for login, matchmaking, chat, friend lists, and purchases, because those operations need reliable delivery and can tolerate normal request latency. The matchmaker is a stateless lobby service that tracks waiting players, ranks, latency targets, party membership, and region, then assigns compatible players to a game server. The game server runs the simulation for its match and does not depend on a central database on every tick. This split keeps the database off the hot real-time path and prevents a slow persistence call from delaying gameplay.
The data model is split among several storage systems because the access patterns are very different. User accounts, profile settings, inventory, entitlements, and match history live in a relational database because they need strict uniqueness, indexed reads, and transactional updates. Matchmaking queues and current player presence are ephemeral and belong in Redis because they are high-churn and can be rebuilt if lost. Leaderboards are stored in Redis sorted sets because the system needs low-latency range queries by score or rank, and occasional rank staleness is acceptable. Replays are written as compressed event streams to object storage because they are large, append-heavy, infrequently read, and do not need relational operations. Telemetry and analytics events flow through Kafka to downstream processors. The live match state itself is not persisted on every update; it lives in the memory of the authoritative game server and is persisted only periodically or when the match ends.
The core mechanism is authoritative simulation with client prediction. The game server runs a simulation loop at a fixed tick rate, often 10 to 60 ticks per second, and treats its local simulation as the source of truth. Each client sends inputs with monotonically increasing sequence numbers. The server applies the oldest unprocessed input for that player during each tick, updates the world, and broadcasts a snapshot to each player's relay. To hide network latency, each client immediately predicts the effect of its own input and renders the predicted movement until the server snapshot arrives. If the server state differs, the client reconciles by replaying unacknowledged inputs from the corrected server state. For fairness, the server may use lag compensation: when validating an action such as a shot, it rewinds the world to the approximate state seen by the acting client, performs the hit test, and then restores the current state. This combination provides responsive movement on the client while preventing each player from freely cheating by modifying local game state.
Scaling and availability depend on regional pools of game servers, stateless lobby services, and reliable persistence paths. The world is divided by region, and players are routed to a nearby relay and matchmaker to reduce round-trip time. Matchmaking and profile services are stateless behind load balancers, so they scale horizontally. Game servers are treated as short-lived, per-match workers; a scheduler or cluster manager starts them on demand, monitors health, and returns failed servers to the pool. If a game server crashes, the match is usually terminated or migrated from a checkpoint, depending on how much state has been persisted. Redis and SQL replicas protect matchmaking, leaderboard, and account data. Edge relays are redundant and anycast-routed where possible so traffic can route around a failed or congested relay. Backpressure is applied to telemetry and replay streams so slow storage does not stall the game simulation. Cheating and abuse are mitigated by keeping all gameplay decisions authoritative on the server and treating client messages as untrusted input.
The main trade-offs are between latency and consistency, UDP and TCP, and centralized authority versus peer-to-peer cost. Using dedicated game servers gives stronger security and fairness than peer-to-peer play, but costs more infrastructure and can add an extra network hop. UDP is better for frequently changing position and combat state because losing a stale packet is preferable to delaying behind retransmissions, but it requires the application to handle reliability for events that must eventually arrive. Client prediction makes controls feel responsive but can cause visible corrections when predictions are wrong. Snapshots sent at a high rate use more bandwidth but reduce interpolation errors, while delta compression reduces bandwidth but complicates recovery when a snapshot is missed. Leaderboards are allowed to be eventually consistent because they are not part of the authoritative gameplay simulation, but purchases and account updates remain strongly consistent because they represent money or durable progression. Overall, the design optimizes the core real-time loop for low latency and loss tolerance while keeping slower, reliable systems around it for identity, progression, and persistence.
flowchart LR
C1[Player 1] -->|UDP input| R1[Edge Relay]
C2[Player 2] -->|UDP input| R2[Edge Relay]
R1 --> GS[Authoritative Game Server]
R2 --> GS
GS -->|UDP snapshots| R1
GS -->|UDP snapshots| R2
R1 --> C1
R2 --> C2
C1 -->|TCP/TLS| API[Lobby / Matchmaking API]
C2 -->|TCP/TLS| API
API --> MM[Matchmaker]
MM -->|assign match| GS
API --> DB[(SQL Profile / Progression DB)]
GS -->|leaderboard events| RC[(Redis Sorted Sets)]
GS -->|telemetry| K[Kafka Telemetry]
GS -->|replays| OS[(Object Storage)]
R1 -->|health| SLB[Regional Load Balancer]
R2 -->|health| SLB
API --> SLB