Skip to content

REST vs WebSocket

REST (representational state transfer): You ask, the server answers. Like email. WebSocket: You open a connection and both sides can send messages anytime. Like a phone call.

flowchart TB
subgraph REST[REST - Request/Response]
direction TB
R1["Browser: GET /api/data"]
R2["Server: Here's the data"]
R3["Browser: POST /api/update"]
R4["Server: OK, updated"]
end
subgraph WebSocket[WebSocket - Persistent Connection]
direction TB
W1["Browser opens connection to server"]
W2["⬆ Browser sends: New message"]
W3["⬇ Server sends: Live update"]
W4["⬇ Server sends: Another update"]
W5["⬆ Browser sends: Typing..."]
end
style REST fill:#3b82f6,color:#fff
style WebSocket fill:#10b981,color:#fff

FeatureREST (HTTP)WebSocket
ModelRequest → ResponsePersistent connection, two-way
ConnectionOpens and closes per requestStays open
LatencyHigher (new connection each time)Lower (instant push)
Real-time❌ Polling needed✅ Instant
Use casesCRUD APIs, websitesChat, games, live updates

→ GET /api/weather
← 200 OK { "temp": 22, "city": "Mumbai" }
→ POST /api/weather/city
← 201 Created
→ GET /api/weather
← 200 OK { "temp": 23, "city": "Mumbai" }

Each request is independent. The server doesn’t remember you between requests (stateless). To get updates, the client has to ask repeatedly.


// Client side (JavaScript)
const ws = new WebSocket('wss://chat.example.com');
// Connection opens
ws.onopen = () => {
ws.send('Hello!'); // Send message
};
// Receive messages anytime
ws.onmessage = (event) => {
console.log('Got:', event.data); // "New message: Hey!"
};

One connection. Both sides can send messages anytime.


TechniqueHow it worksBest for
PollingClient asks every few secondsSimple, quick to implement
Long pollingServer holds the request until data is readyWhen updates are infrequent
SSE (Server-Sent Events)Server pushes to client (one-way)Notifications, news feeds
WebSocketFull two-way communicationChat, gaming, collaborative editing
flowchart LR
subgraph Methods[Real-Time Communication Methods]
Poll[Polling<br/>Client asks repeatedly] --> Server1
SSE[SSE<br/>Server pushes to client] --> Server2
WS[WebSocket<br/>Two-way persistent] --> Server3
end
style Methods fill:#7c3aed,color:#fff
style Poll fill:#3b82f6,color:#fff
style SSE fill:#f59e0b,color:#fff
style WS fill:#10b981,color:#fff

Use REST for…Use WebSocket for…
CRUD APIsChat applications
Loading page dataLive sports scores
Form submissionsStock price tickers
Simple queriesMultiplayer games
Mobile app backendsCollaborative editing (Google Docs)

  • REST = ask → receive (like HTTP). Each request is separate. Good for standard APIs.
  • WebSocket = open connection → both sides talk freely. Good for real-time apps.
  • REST is stateless; WebSocket maintains a persistent stateful connection
  • Polling fakes real-time by repeatedly asking the server; WebSocket is truly real-time
  • SSE is one-way (server → client); WebSocket is two-way