DEV Community

Cover image for πŸš€ Realtime Communication in Frontend (Polling vs WebSocket vs SSE)
Vishwark
Vishwark

Posted on

πŸš€ Realtime Communication in Frontend (Polling vs WebSocket vs SSE)

Realtime features are everywhere today β€” chat apps, delivery tracking, payments, notifications.

But one mistake many developers make is:
πŸ‘‰ Using WebSocket for everything.

In real production systems, we use a mix of:

  • Polling
  • Server-Sent Events (SSE)
  • WebSocket

πŸ‘‰ The goal is simple: use the simplest solution that works reliably.


🧠 1. What is Realtime Communication?

Realtime means:
πŸ‘‰ Data updates without refreshing the page

But important point:
πŸ‘‰ Not all realtime needs to be instant

Some features can tolerate delay (2–5 seconds), and that changes the design.


πŸ” 2. Polling (Simple but Powerful)

What is Polling?

Client keeps asking server for updates:

setInterval(async () => {
  const res = await fetch("/status");
  const data = await res.json();
  console.log(data);
}, 5000);
Enter fullscreen mode Exit fullscreen mode

When Polling Works Best

Use polling when:

  • Data changes slowly
  • You need high reliability
  • Simplicity is preferred

Real Example: Payment Status

Let’s understand this properly.

Flow:

  1. User clicks β€œPay”
  2. Redirected to third-party gateway (Razorpay / Stripe)
  3. Payment happens outside your app
  4. Gateway sends webhook β†’ your backend
  5. Backend updates DB
  6. Frontend checks status

Why Polling is Used Here

  • Frontend doesn’t control payment result
  • Gateway response timing is unpredictable
  • User may refresh or leave page

πŸ‘‰ So frontend polls backend:

setInterval(async () => {
  const res = await fetch("/payment/status?id=123");
  const data = await res.json();

  if (data.status === "success") {
    // stop polling
  }
}, 3000);
Enter fullscreen mode Exit fullscreen mode

Real Example: Payment Status


Why Not WebSocket or SSE?

  • Requires active connection
  • Not reliable across page refresh
  • Overkill for single status change

πŸ‘‰ Polling wins because it is simple and reliable


πŸ”Œ 3. WebSocket (For True Realtime)

What is WebSocket?

  • Persistent connection
  • Two-way communication

πŸ‘‰ Both client and server can send data anytime


When to Use WebSocket

  • Chat apps
  • Live tracking (driver, delivery)
  • Multiplayer apps

Reconnection Problem (Real Issue)

Example:

  • User offline for 1 hour
  • 1000 updates missed

Problems:

  • Missing data
  • Duplicate data
  • Wrong order

Real-world Solution Pattern

  1. Use message IDs
  2. Store last received ID
  3. Fetch missing data after reconnect
fetch(`/messages?afterId=${lastId}`);
Enter fullscreen mode Exit fullscreen mode

WhatsApp Example (Important)

  • Uses message IDs + ACK
  • Stores messages locally
  • Syncs missing messages after reconnect
  • Loads messages in chunks (avoid UI freeze)

πŸ‘‰ Large data is never pushed blindly

WebSocket Reconnect & Sync


πŸ“‘ 4. Server-Sent Events (SSE)

What is SSE?

  • Server pushes data to client
  • One-way communication
const eventSource = new EventSource("/events");

 eventSource.onmessage = (event) => {
  console.log(event.data);
};
Enter fullscreen mode Exit fullscreen mode

When to Use SSE

  • Notifications
  • Live dashboards
  • Activity feeds
  • Jenkins pipeline updates
  • Live cricket/sports score/commentary updates

Limitations

  • Client cannot send data
  • Not suitable for interactive systems

βš–οΈ 5. Polling vs SSE vs WebSocket

Feature Polling SSE WebSocket
Direction Client β†’ Server Server β†’ Client Two-way
Complexity Low Medium High
Realtime Low Medium High
Use case Status Notifications Chat/Tracking

🧠 6. Real-world Scenarios (How to Choose)

This is where real engineering decisions happen.


πŸš— Driver Tracking (Uber / Ola)

Flow:

  • Driver app sends location β†’ Backend
  • Backend calculates ETA
  • Backend sends updates β†’ User app

Why WebSocket is Commonly Used

Driver side needs to:

  • Send frequent location updates
  • Receive updates (route change, cancel, reassign)

πŸ‘‰ This becomes two-way communication β†’ WebSocket fits well


Can We Avoid WebSocket?

Yes, there are alternatives.

Option 1: Driver β†’ REST API (Polling/Push)

  • Driver sends location every few seconds via HTTP
  • Backend processes and stores data

Option 2: Backend β†’ User via SSE

  • User receives updates via SSE

πŸ‘‰ This works if:

  • No real-time interaction required
  • Slight delay is acceptable

Trade-off

Approach Pros Cons
WebSocket Low latency, real-time More complex
REST + SSE Simpler infra Slight delay, more requests

πŸ‘‰ Real apps choose based on scale and need


πŸ” Zomato / Swiggy

🟑 Order Status (Placed β†’ Delivered)

  • Low frequency updates
  • Delay is acceptable

πŸ‘‰ Polling is usually used


Can SSE Work?

Yes, and some systems may use it.

Flow:

  • Backend updates DB
  • SSE pushes new status
  • Client updates UI

πŸ‘‰ But:

  • Needs persistent connection
  • More infra setup

πŸ‘‰ Polling is simpler and reliable


🟒 Delivery Tracking (Map Movement)

Flow:

  • Delivery partner β†’ Backend (location updates)
  • Backend β†’ User (location + ETA)

Common Assumption

πŸ‘‰ β€œUser only needs data, so SSE is enough”

This is partially correct.


Real-world Consideration

Even user app may need to:

  • Cancel order
  • Change address
  • Trigger actions

πŸ‘‰ These go via REST APIs


Possible Architectures

Option 1 (Simpler)

  • Driver β†’ REST (send location)
  • Backend β†’ SSE (push updates to user)
  • User β†’ REST (actions like cancel)

πŸ‘‰ Works well for moderate scale


Option 2 (Advanced / High Scale)

  • Driver ↔ Backend β†’ WebSocket
  • User ↔ Backend β†’ WebSocket

πŸ‘‰ Benefits:

  • Lower latency
  • Unified system
  • Easier event handling

Why Many Apps Still Use WebSocket

  • One consistent system
  • Handles all events (location, cancel, updates)
  • Better performance at scale

πŸ‘‰ Even if SSE + REST is possible, WebSocket simplifies architecture

Zomato/Swiggy realtime communication β€” Two Architecture Options


πŸ—οΈ 7. Stateless vs Stateful Architecture (Very Important)

Understanding this helps you choose the right protocol.

Stateless vs Stateful Architecture


Stateless (REST APIs)

  • Each request is independent
  • Server does not store connection state

Example:

GET /order/status
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Server responds and forgets


Pros

  • Easy to scale
  • Works with load balancers
  • Reliable

Cons

  • Not efficient for realtime
  • Requires repeated requests (polling)

Stateful (WebSocket)

  • Connection stays open
  • Server maintains session/connection state

πŸ‘‰ Server knows client is connected


Pros

  • Real-time communication
  • Low latency

Cons

  • Harder to scale
  • Needs connection management

SSE (Hybrid)

  • Uses HTTP (stateless)
  • But keeps connection open

πŸ‘‰ Semi-stateful


🌐 8. REST vs Realtime APIs

REST APIs

  • Request β†’ Response
  • Stateless
  • Works well for CRUD operations

Realtime APIs (WebSocket / SSE)

  • Event-driven
  • Continuous data flow

When to Use What

  • REST β†’ actions (create, update, cancel)
  • WebSocket/SSE β†’ live updates

πŸ‘‰ Most apps use both together


🧠 Decision Framework

Decision Framework : polling, SSE, webscoket

Ask these questions:

  1. Do I need two-way communication?
    πŸ‘‰ Yes β†’ WebSocket
    πŸ‘‰ No β†’ SSE or Polling

  2. How frequent are updates?
    πŸ‘‰ Low β†’ Polling
    πŸ‘‰ Medium β†’ SSE
    πŸ‘‰ High β†’ WebSocket

  3. Do I need simplicity or performance?
    πŸ‘‰ Simplicity β†’ Polling
    πŸ‘‰ Performance β†’ WebSocket


🧾 Conclusion

In real systems:

  • Polling β†’ simple and reliable
  • SSE β†’ simple realtime push
  • WebSocket β†’ complex realtime interaction

πŸ‘‰ Most systems combine:

  • REST for actions
  • Realtime for updates

Final Thought

There is no single best solution.

Good engineering is about choosing the right tool for the job.

πŸ‘‰ Start simple
πŸ‘‰ Scale when needed


Top comments (0)