DEV Community

araf
araf

Posted on

πŸ”„ Server-Sent Events (SSE) vs WebSockets vs Long Polling: What’s Best in 2025?

Real-time data is everywhere in 2025 β€” whether you're building stock dashboards, multiplayer games, or live chat apps. But should you use WebSockets, SSE, or Long Polling?

This post breaks them down with real-world examples, pros & cons, and beginner-friendly code snippets.


πŸ“¦ TL;DR

Feature Long Polling Server-Sent Events (SSE) WebSockets
Direction Client ➑️ Server Server ➑️ Client Bi-directional πŸ”
Protocol HTTP/1 HTTP/1 WS (separate proto)
Complexity Simple Moderate Advanced
Reconnection Handling Manual Automatic Manual
Use For Legacy systems Live feeds, notifications Games, chats, collab

🎯 Use Case: Live Order Status in an eCommerce App

Imagine you're building a real-time order tracking feature.

A user places an order and wants to see status updates as it progresses: "Confirmed β†’ Packed β†’ Shipped β†’ Delivered"

Let’s implement this with all three options.


🧡 1. Long Polling (Legacy but still used)

How it works:

Client sends a request β†’ Server holds it open until data is available β†’ Responds β†’ Client starts again.

// Client-side (JS)
setInterval(() => {
  fetch("/order-status")
    .then(res => res.text())
    .then(console.log);
}, 3000); // Poll every 3 seconds
Enter fullscreen mode Exit fullscreen mode

Spring Boot Controller (pseudo):

@GetMapping("/order-status")
public ResponseEntity<String> getStatus() {
    String status = orderService.getLatestStatus();
    return ResponseEntity.ok(status);
}
Enter fullscreen mode Exit fullscreen mode

βœ… Pros:

  • Simple to implement
  • Works with old infrastructure ❌ Cons:
  • Wastes bandwidth (even when nothing changes)
  • Higher latency and server load

πŸ”„ 2. Server-Sent Events (SSE)

How it works:

A single HTTP connection where the server pushes updates as they happen.

Spring Boot Server:

@GetMapping(value = "/order-stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<String> streamOrderStatus() {
    return Flux.interval(Duration.ofSeconds(2))
               .map(i -> orderService.getLiveStatus());
}
Enter fullscreen mode Exit fullscreen mode

Client (JS):

const source = new EventSource("/order-stream");

source.onmessage = function(event) {
  console.log("Order Update:", event.data);
};
Enter fullscreen mode Exit fullscreen mode

βœ… Pros:

  • Easy setup with HTTP
  • Built-in reconnect
  • Lightweight for 1-way data ❌ Cons:
  • Only server ➑️ client
  • Not supported in older browsers or HTTP/2+

πŸ”„πŸ” 3. WebSockets (For Real-time, Bi-directional Apps)

How it works:

Client and server establish a persistent connection for 2-way data flow.

Spring Boot WebSocket Config:

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(new OrderWebSocketHandler(), "/ws/orders");
    }
}
Enter fullscreen mode Exit fullscreen mode

Java WebSocket Handler:

public class OrderWebSocketHandler extends TextWebSocketHandler {
    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) {
        // Send real-time status
        session.sendMessage(new TextMessage("Shipped"));
    }
}
Enter fullscreen mode Exit fullscreen mode

Client:

const socket = new WebSocket("ws://localhost:8080/ws/orders");

socket.onmessage = (e) => {
  console.log("Update:", e.data);
};
Enter fullscreen mode Exit fullscreen mode

βœ… Pros:

  • Real-time, bidirectional
  • Efficient for interactive apps ❌ Cons:
  • Harder to scale
  • Needs WebSocket support in infra (load balancer, proxy, etc.)

🧠 Which One Should I Use?

If you’re building... Use
Live notifications / news ticker βœ… SSE
Chat / multiplayer game βœ… WebSockets
Legacy or low-budget integration βœ… Long Polling
Live dashboards (1-way) βœ… SSE or WebSockets
IoT control panels (2-way) βœ… WebSockets

πŸ§ͺ Bonus: Performance Tips

  • For high-frequency updates, use WebSockets with message batching.
  • Use SSE for server-to-client streams like:
    • Logs
    • Stock prices
    • Notifications
  • For mobile networks or flaky connections, SSE reconnects automatically.
  • Avoid Long Polling unless compatibility is a must.

βœ… Final Thoughts

Each technique has a purpose. Don’t just default to WebSockets β€” sometimes SSE is better for one-way updates, and Long Polling works in legacy APIs.

Start simple, and only level up when your use case demands it.


πŸ’¬ What’s your go-to for real-time features in Java? Drop your comments or share your favorite stack!


πŸ‘‹ Follow me for more Java, Spring Boot, and backend real-time architecture deep dives!




---

Would you like me to:
- Add some visuals or diagrams for connection flows?
- Turn this into a live working GitHub repo?
- Add a part 2: scaling SSE or WebSockets with Redis / Kafka?

Let’s build it together if you’re planning to post it soon!
Enter fullscreen mode Exit fullscreen mode

Top comments (0)