Video in progress

How do you write an SSE endpoint with SseEmitter in Spring MVC?

The controller method returns an SseEmitter, the emitters are stored in one place (for example a ConcurrentHashMap), and emitter.send(...) is called when an event appears. When the connection drops or times out, the emitter is removed from the registry.

📖 Answer

@RestController
public class NotificationController {

    private final Map<Long, SseEmitter> emitters = new ConcurrentHashMap<>();

    @GetMapping(value = "/api/notifications/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter stream(@AuthenticationPrincipal AppUser user) {
        SseEmitter emitter = new SseEmitter(Duration.ofMinutes(30).toMillis());
        emitters.put(user.getId(), emitter);

        emitter.onCompletion(() -> emitters.remove(user.getId()));
        emitter.onTimeout(emitter::complete);
        emitter.onError(e -> emitters.remove(user.getId()));
        return emitter;
    }

    public void push(Long userId, NotificationDto dto) {
        SseEmitter emitter = emitters.get(userId);
        if (emitter == null) return;
        try {
            emitter.send(SseEmitter.event().name("notification").data(dto));
        } catch (IOException e) {
            emitters.remove(userId); // the client is gone
        }
    }
}

The method returns right away, but the HTTP response stays open; Spring switches it to async mode. The servlet thread is freed, so 1000 open SSE connections don't occupy 1000 threads.

In this example each user gets one emitter. In real life people open several tabs, so you'd need a Map<Long, List<SseEmitter>>.