Site Icon THEREiSLatest Posts · reading #025한국어

Title :

SSE(Server-Sent Events) With Spring Boot

Author
[Yahum]
Date
Tags

This page was translated from the Korean original using AI. If anything reads oddly, please refer to the original. Read the Korean original →

Alright, if last time you got the theoretical background on SSE, this time let’s build it with Spring Boot. If I get the chance later, let’s also try it with Express.js, Nest.js or Next.js, or with Django Rest Framework or FastAPI. Who knows how many languages I’ll milk SSE for.

Honestly, I’ve got way too many things going on right now. I still have 우리집 비서만들기 (Building a Home Assistant) to do, and building a Meshy AI application too. There’s so much I want to do and I can’t keep it all under control, so for SSE let’s settle for Spring Boot for now.

Well, I’m sure at work I’ll end up implementing it in a Node.js environment someday. I’ll post about it then.

Setting Up the Project

I’m going to build this in VS Code, as a Maven project. I’ll assume you’ve installed the Spring Boot Extension Pack in VS Code and carry on from there. In this age of AI coding everywhere, I doubt anyone is disciplined enough to read this post line by line and follow along, but I’m a nice guy, so I’ll walk you through it step by step.

Spring Boot Extension Pack

Press Ctrl + Shift + P on Windows or Cmd + Shift + P on macOS, then pick Spring Initializr, and you should see a list like the one in the screenshot.

Creating a Spring Boot project

I’m making the project with Maven, so I’ll choose Spring Initializr: Create a Maven Project…, but if you prefer Gradle, feel free to pick Spring Initializr: Create a Gradle Project…. Honestly, the syntax is a bit different but they work the same way, so I think it’s just personal taste.

Choosing the Spring Boot version

The next prompt asks for the Spring Boot version. I went with 4.2.0. To be honest, I don’t know much about the performance stuff. I’m using it because its OSS (Open Source Software) support runs until December 31, 2027. Of course, it also comes with things like faster startup and AMQP 1.0 support.

Pick a language, it says

For the next choice, I picked Java. Ah, I really need to study Kotlin too. I just never get the chance. I’ll learn it when I end up building a native Android app someday.

Deciding the Group ID

It asks for a Group Id, but does a sample project really need a grand Group Id? I just typed com.sample.

Deciding the Artifact Id

Then it asks for an Artifact Id. What’s an Artifact Id? Just think of it as the project name. It’s the unique name of the project within the Group Id. I’m making an SSE sample, so I named it sse. Next you decide the package name, which is simply the Group Id and Artifact Id combined. So for me, the package name becomes com.sample.sse.

Setting the package name

Now we pick the packaging type. Unless you need to deploy to a separate WAS (Web Application Server) or apply some other special setup, go with Jar. Setting up a WAS is quite a chore.

Choosing the packaging type

Next is the Java version. You might be worried about recent JDK vulnerabilities, but we’re only running this as a local server for testing, so why worry about vulnerabilities? Setting up a JDK is a pain anyway, so I’ll go with JDK 21.

JDK 21 it is!

Then comes the dependency selection screen. There’s a lot in there, but all we need is an SSE sample, so just select Spring Web. And nothing bad happens if you miss something here. You can always add the dependency to pom.xml later.

Selecting dependencies

After that it asks about creating a directory, and once you let it, the project is generated like in the image below.

The project has been created!

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc</artifactId>
</dependency>

If this dependency is set, you’re good. Now let’s print Hello, World from a controller.

Making Hello, World

src/main/java/com/sample/sse/controllers/HelloController.java
package com.sample.sse.controllers;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping ("/health")
public class HelloController {
@GetMapping("/hello")
public String getMethodName() {
return "Hello, World";
}
}

Create HelloController like this and start the server…. For those who don’t know how to start it: if you installed the Spring Boot Extension Pack properly at the beginning,

Spring Boot Dashboard

you should have Spring Boot Dashboard installed. If you don’t see it, restart VS Code and it should show up. Click this button and you’ll see a screen like the one below.

Spring Boot Dashboard

There’s my project, sse. Hover over it and right-click to bring up the context menu.

Hit Run!

Click Run.

Terminal logs show up

If the terminal opens at the bottom of VS Code and you see a log like Started SseApplication blah blah, the local server has started properly. Spring Boot usually uses port 8080, so open a browser like Chrome and enter http://localhost:8080/health/hello. If you see “Hello, World” in the top-left corner on a white background, everything works.

Checking Hello, World with Postman (I tested it with Postman, though.)

Let’s Build the SSE Sample

Without further ado, code first. Files first, actually.

Creating the class files

I created SseController.java and SseEmitterService.java.

SseController.java
package com.sample.sse.controllers;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.UUID;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import com.sample.sse.services.SseEmitterService;
@RestController
@RequestMapping("/sse")
public class SseController {
private final SseEmitterService sseEmitterService;
//-----------------------------------------------------------------------------
//
// CONSTRUCTOR
//
//-----------------------------------------------------------------------------
public SseController(SseEmitterService sseEmitterService) {
this.sseEmitterService = sseEmitterService;
}
//-----------------------------------------------------------------------------
//
// METHODS : PUBLIC
//
//-----------------------------------------------------------------------------
/**
* Subscribe (connect) endpoint.
* e.g.) GET /sse/subscribe?clientId=user1
*/
@GetMapping(value = "/subscribe", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public SseEmitter subscribe(@RequestParam(required = false) String clientId) {
String id = (clientId == null || clientId.isBlank()) ?
UUID.randomUUID().toString().substring(0, 8) : clientId;
return sseEmitterService.subscribe(id);
}
/**
* Publish a message to all clients.
* e.g.) POST /sse/broadcast {"message":"Hello"}
*/
@PostMapping("/broadcast")
public Map<String, Object> broadcast(@RequestBody MessageRequest request) {
ChatMessage message = new ChatMessage("broadcast", request.message(), LocalDateTime.now());
int sent = sseEmitterService.broadcast("message", message);
return Map.of("sent", sent, "connections", sseEmitterService.connectionCount());
}
/**
* Send a message to one specific client only.
* e.g.) POST /sse/send/user1 {"message":"only for user1"}
*/
@PostMapping("/send/{clientId}")
public ResponseEntity<Map<String, Object>> sendTo(@PathVariable String clientId, @RequestBody MessageRequest request) {
ChatMessage message = new ChatMessage("direct", request.message(), LocalDateTime.now());
boolean sent = sseEmitterService.sendTo(clientId, "message", message);
if (!sent) {
return ResponseEntity.status(404).body(Map.of("error", "연결된 클라이언트가 없습니다: " + clientId));
}
return ResponseEntity.ok(Map.of("sent", true, "clientId", clientId));
}
/** Check the current number of connections */
@GetMapping("/connections")
public Map<String, Integer> connections() {
return Map.of("connections", sseEmitterService.connectionCount());
}
//-----------------------------------------------------------------------------
//
// DTO
//
//-----------------------------------------------------------------------------
public record MessageRequest(String message) {
}
public record ChatMessage(String type, String message, LocalDateTime sentAt) {
}
}

The code alone can be confusing, so let’s go through it method by method.

PUBLIC METHODS

Method Request What it does Response
subscribe GET /sse/subscribe?clientId=user1 The entry point that opens an SSE connection. If there’s no clientId, it makes one from the first 8 characters of a UUID, and the service creates and returns an SseEmitter for that ID. Because the method returns an SseEmitter, Spring keeps the response open instead of finishing it, so the connection stays alive. produces = text/event-stream sets the response format to SSE SseEmitter (connection stays open, events keep flowing)
broadcast POST /sse/broadcast
{"message":"Hello"}
Sends a message to every connected client. It sets type to "broadcast" and publishes it as a message event along with the time it was sent {"sent": number sent, "connections": current connections}
sendTo POST /sse/send/user1
{"message":"only for user1"}
Sends a message to just the one client named in the URL. type is "direct". If no client is connected with that ID, it returns 404 Success: {"sent": true, "clientId": "user1"}
Failure: 404 {"error": "연결된 클라이언트가 없습니다: user1"} (“no connected client”)
connections GET /sse/connections Tells you how many clients are connected right now. Handy for checking that connections went through while testing {"connections": current connections}

DTO

DTO Where it’s used Fields
MessageRequest Request body of broadcast and sendTo message: the content to send
ChatMessage Data sent to clients over SSE (goes into data: as JSON) type: broadcast / direct
message: content
sentAt: time sent
SseEmitterService.java
package com.sample.sse.services;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
/**
* Manages connected clients (SseEmitter) and sends events to them.
*
* <p>Note: connections are kept in memory (a Map), so this only works correctly with a single server instance.
* To scale out to multiple instances, you need to share events through something like Redis Pub/Sub.
*/
@Service
public class SseEmitterService {
private static final Logger log = LoggerFactory.getLogger(SseEmitterService.class);
/** Connection lifetime: 30 minutes. When it expires, the browser's EventSource reconnects automatically. */
private static final long TIMEOUT_MILLIS = 30 * 60 * 1000L;
/** How long the browser waits before trying to reconnect after a disconnect (ms) */
private static final long RECONNECT_MILLIS = 3_000L;
private final Map<String, SseEmitter> emitters = new ConcurrentHashMap<>();
private final AtomicLong eventIdSequence = new AtomicLong();
/** Client subscription: creates an SseEmitter, stores it, and returns it. */
public SseEmitter subscribe(String clientId) {
SseEmitter emitter = new SseEmitter(TIMEOUT_MILLIS);
// If the same clientId connects again, clean up the previous connection
SseEmitter previous = emitters.put(clientId, emitter);
if (previous != null) {
previous.complete();
}
// Remove from the Map on completion/timeout/error (only if it's still this emitter)
emitter.onCompletion(() -> {
emitters.remove(clientId, emitter);
log.info("SSE 연결 종료: {} (현재 {}명)", clientId, emitters.size());
});
emitter.onTimeout(() -> {
log.info("SSE 연결 만료: {}", clientId);
emitter.complete();
});
emitter.onError(e -> {
log.info("SSE 연결 에러: {} - {}", clientId, e.getMessage());
emitters.remove(clientId, emitter);
});
// Send a first event right after connecting.
// If nothing is sent, the response stays empty until the timeout, which can lead to a 503 or similar.
sendTo(clientId, "connect", "연결되었습니다. clientId=" + clientId);
log.info("SSE 연결 시작: {} (현재 {}명)", clientId, emitters.size());
return emitter;
}
/** Send an event to a specific client */
public boolean sendTo(String clientId, String eventName, Object data) {
SseEmitter emitter = emitters.get(clientId);
if (emitter == null) {
return false;
}
return send(clientId, emitter, eventName, data);
}
/** Send an event to all connected clients. Returns the number of successful sends. */
public int broadcast(String eventName, Object data) {
int success = 0;
for (Map.Entry<String, SseEmitter> entry : emitters.entrySet()) {
if (send(entry.getKey(), entry.getValue(), eventName, data)) {
success++;
}
}
return success;
}
public int connectionCount() {
return emitters.size();
}
/**
* Heartbeat: sends a comment line every 15 seconds.
* - keeps proxies/load balancers from dropping idle connections, and
* - finds and cleans up clients that have already disconnected.
* Comments are not delivered to the browser's onmessage.
*/
@Scheduled(fixedRate = 15_000)
public void heartbeat() {
emitters.forEach((clientId, emitter) -> {
try {
emitter.send(SseEmitter.event().comment("heartbeat " + LocalDateTime.now()));
} catch (IOException | IllegalStateException e) {
emitters.remove(clientId, emitter);
}
});
}
private boolean send(String clientId, SseEmitter emitter, String eventName, Object data) {
try {
emitter.send(
SseEmitter.event()
.id(String.valueOf(eventIdSequence.incrementAndGet()))
.name(eventName)
.reconnectTime(RECONNECT_MILLIS)
.data(data, data instanceof String ? MediaType.TEXT_PLAIN : MediaType.APPLICATION_JSON)
);
return true;
} catch (IOException | IllegalStateException e) {
// The client has already disconnected
emitters.remove(clientId, emitter);
log.debug("전송 실패, 연결 제거: {}", clientId);
return false;
}
}
}

Here’s how data moves between the Controller and the Service, as a diagram.

sequenceDiagram participant C as Browser (EventSource) participant P as Sender (e.g. Postman) participant Ctrl as SseController participant Svc as SseEmitterService participant Map as emitters (Map) rect rgba(120, 170, 255, 0.12) Note over C,Map: 1. Subscribe C->>Ctrl: GET /sse/subscribe?clientId=user1 Ctrl->>Svc: subscribe("user1") Svc->>Map: put("user1", new SseEmitter) Map-->>Svc: previous connection (complete() if any) Svc-)C: event: connect / data: connected Svc-->>Ctrl: SseEmitter Ctrl-->>C: keep the connection open without finishing the response end rect rgba(120, 220, 150, 0.12) Note over C,Map: 2. Broadcast P->>Ctrl: POST /sse/broadcast {"message":"Hello"} Ctrl->>Ctrl: create ChatMessage("broadcast", ...) Ctrl->>Svc: broadcast("message", ChatMessage) loop every connection in emitters Svc-)C: event: message / data: ChatMessage(JSON) end Svc-->>Ctrl: number of successful sends Ctrl-->>P: {"sent": n, "connections": m} end rect rgba(255, 190, 110, 0.12) Note over C,Map: 3. Send to one client P->>Ctrl: POST /sse/send/user1 {"message":"only for user1"} Ctrl->>Ctrl: create ChatMessage("direct", ...) Ctrl->>Svc: sendTo("user1", "message", ChatMessage) Svc->>Map: get("user1") alt connected Svc-)C: event: message / data: ChatMessage(JSON) Svc-->>Ctrl: true Ctrl-->>P: 200 {"sent": true, "clientId": "user1"} else not connected Svc-->>Ctrl: false Ctrl-->>P: 404 {"error": "no connected client: user1"} end end rect rgba(200, 200, 200, 0.15) Note over C,Map: 4. Heartbeat (every 15s, @Scheduled) loop every connection in emitters Svc-)C: : heartbeat (comment line) end Note over Svc,Map: remove from the Map if sending fails end

If the text is too small to read, check out the image below. Data flow between Controller and Service

Oops, I forgot to update SseApplication.java.

SseApplication.java
package com.sample.sse;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling // You need EnableScheduling for the Scheduled annotation in the Service to work.
public class SseApplication {
public static void main(String[] args) {
SpringApplication.run(SseApplication.class, args);
}
}

Once you’ve coded everything, here’s how to test it in Postman.

Postman Test

Enter http://localhost:8080/sse/subscribe?clientId=user1 as the URL and set Accept: text/event-stream in the Headers tab. Then click Send, and you’ll see it connect to the server.

While that’s running, open a new tab and call broadcast.

broadcast Test

Set the message to {"message": "hello, world"} with POST like this and hit Send.

Receiving the message

And you can see the subscribe side receiving the message.
Besides this, you can also send messages to individual users, or check how many people are currently connected.

Wrapping Up

Thanks for sticking through all that code. Honestly, beyond the technical side, what surprised me was that this is a built-in feature of Spring Boot’s Web MVC package. You can build something like this without much effort at all. I’m glad I now have a new option to suggest when developing services.

Learned a lot again today. That’s it for now! See you next time!

Good bye

[ Comments ]Shown after approval

Loading comments...