Backend Development 7 min read

Server‑Sent Events vs WebSocket vs Polling: Choosing the Right Real‑Time Communication Technique for Backend Development

This article compares Server‑Sent Events, traditional polling, and WebSocket for server‑to‑client real‑time messaging, explains why WebSocket may be overkill for one‑way push scenarios, and provides a Spring Boot example of an SSE endpoint with code and configuration details.

Architecture Digest
Architecture Digest
Architecture Digest
Server‑Sent Events vs WebSocket vs Polling: Choosing the Right Real‑Time Communication Technique for Backend Development

In many projects real‑time communication is required, and developers often reach for WebSocket, but when the client only needs to receive data the full duplex nature of WebSocket is unnecessary; Server‑Sent Events (SSE) offers a lightweight, one‑way alternative.

A detailed comparison table outlines key characteristics of SSE, polling, and WebSocket, covering communication direction, connection type, transport protocol, browser support, message frequency, server and client overhead, data formats, reconnection mechanisms, suitable scenarios, complexity, real‑time performance, firewall compatibility, and bandwidth consumption.

The author lists several reasons for abandoning WebSocket in simple push use‑cases: cumbersome token handling during handshake, complex logging, the need to write reconnection and heartbeat logic, and the requirement to implement timed message sending, whereas SSE integrates with minimal dependencies and simple code.

To demonstrate SSE in practice, a Spring Boot configuration is shown. First, a custom AsyncTaskExecutor bean is defined to handle asynchronous tasks safely in production:

@Configuration
@Slf4j
public class WebMvcConfig implements WebMvcConfigurer {
    @Bean(name = "customAsyncTaskExecutor")
    public AsyncTaskExecutor customAsyncTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        int corePoolSize = Runtime.getRuntime().availableProcessors();
        int maxPoolSize = corePoolSize * 2;
        int queueCapacity = 500;
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setThreadNamePrefix("AsyncExecutor-");
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(60);
        executor.initialize();
        return executor;
    }

    @Override
    public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
        configurer.setTaskExecutor(customAsyncTaskExecutor());
        configurer.setDefaultTimeout(5000);
    }
}

Then an SSE endpoint is implemented that streams the number of online users every five seconds using Project Reactor:

@PreventDuplicateSubmit
@PreAuthorize("@permission.checker('monitor:online-user:list')")
@GetMapping(value = "/user-activity-sse", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<Integer> streamUserActivitySSE() {
    // Create a Flux that emits a value every 5 seconds
    return Flux.interval(Duration.ofSeconds(5))
        .flatMap(seq -> Mono.fromCallable(onlineUserService::getUserActivityNum)
            .onErrorReturn(0));
}

The article also shares a screenshot of the front‑end effect, illustrating how the browser receives incremental updates.

In a later anecdote the author admits that a recent project used polling to integrate a C++ ID‑card scanner because the device could only be queried, not push data; the author notes that SSE would have been a cleaner solution.

Finally, the author concludes that WebSocket, SSE, and polling each have their own appropriate scenarios; there is no universally superior choice, and developers should select the technique that matches the required communication pattern, such as notifications, monitoring, or full‑duplex chat.

backendSpring BootWebSocketreal-time communicationpollingSSE
Architecture Digest
Written by

Architecture Digest

Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.