Implementing Real-Time Messaging with SSE in Spring Boot

Server-Sent Events (SSE) is a mechanism that enables servers to push real-time updates to clients over HTTP. Compraed to WebSocket, SSE is simpler and suitable for many real-time communication scenarios. This article explores how to implement real-time messaging using Spring Boot and SSE.

What Are Server-Sent Events

SSE allows a server to send live updates to a client through an HTTP connection. Once a client initiates a request and keeps the connection open, the server can transmit data at any moment. It's ideal for applications requiring high real-time performance but minimal bidirectional communication needs, such as live stock prices or news feeds.

Using SSE in Spring Boot

Implementing SSE in Spring Boot is straightforward, typically involving returning an SSE response stream via a Controller.

1. Setting Up a Spring Boot Application

Begin by creating a basic Spring Boot project and including required dependencies.

pom.xml

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>
​

2. Building the Controller

Next, create a controller to manage SSE connections and deliver real-time updates.

SseEndpoint.java

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@RestController
public class SseEndpoint {

    private final ExecutorService threadPool = Executors.newCachedThreadPool();

    @GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter streamUpdates() {
        SseEmitter emitter = new SseEmitter();
        threadPool.execute(() -> {
            try {
                for (int count = 0; count < 10; count++) {
                    emitter.send("Update " + count, MediaType.TEXT_PLAIN);
                    TimeUnit.SECONDS.sleep(1);
                }
                emitter.complete();
            } catch (IOException | InterruptedException ex) {
                emitter.completeWithError(ex);
            }
        });
        return emitter;
    }
}
​

The above code defines a /stream endpoint that sends ten messages one per second using an SseEmitter object when accessed by a client.

Client-Side Implementation

To receive these messages, the client must establish a connection using the EventSource API and process incoming data.

index.html


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>SSE Example</title>
</head>
<body>
    <h1>Server-Sent Events Example</h1>
    <div id="output"></div>

    <script>
        const source = new EventSource("/stream");

        source.onmessage = function(event) {
            const outputDiv = document.getElementById("output");
            const entry = document.createElement("p");
            entry.textContent = event.data;
            outputDiv.appendChild(entry);
        };

        source.onerror = function() {
            console.error("Connection to server lost.");
        };
    </script>
</body>
</html>
​

In this HTML example, EventSource connects to the /stream endpoint and displays each received message in a paragraph element.

Advantages and Limitations of SSE

Benefits

  1. Ease of Use: Being based on HTTP, SSE is easy to set up and maintain.
  2. Built-in Reconnection: Browsers support automatic reconnection and recovery mechanisms for SSE.
  3. Resource Efficiency: Utilizing persistent HTTP connections avoids overhead associated with polling.

Drawbacks

  1. Unidirectional Flow: SSE supports only server-to-client data transmission.
  2. Connection Limits: Browsers impose limits on concurrent connections per domain, potentially affecting performance under heavy load.
  3. Latency Constraints: For ultra-low latency requirements, WebSocket might be more appropriate.

Tags: Spring Boot SSE Real-Time Messaging HTTP streaming EventSource

Posted on Wed, 13 May 2026 05:05:18 +0000 by iraja