Spring › Wanted-Challenge

Delivering Spring MVC SSE without long-lived DB sessions

Manage multiple SSE connections per user, serialize notification DTOs, and keep Spring MVC streaming separate from database transactions.

Delivering Spring MVC SSE without long-lived DB sessions

I used Spring MVC’s SseEmitter to deliver notifications across browser tabs. The subscription can stay open for an hour, so I separated its lifetime from the database lookup and gave every completion path a way to unregister the emitter.

The examples use Spring Boot 3.5, Kotlin 1.9, and Java 21.

Choosing a unidirectional transport

OptionDirectionProtocolReconnect behavior
PollingClient requests updatesHTTPThe client repeats requests
WebSocketBidirectionalWebSocketThe application manages reconnection
SSEServer pushes eventsHTTP with text/event-streamBrowser EventSource reconnects

Comments and announcements only need server-to-browser delivery. Polling would make idle clients ask for empty updates. WebSocket provides bidirectional messaging the feature does not need. SSE fit the existing HTTP and Spring MVC stack and let the browser reconnect.

Native EventSource cannot attach an arbitrary Authorization header. A site that uses Bearer tokens needs a compatible fetch-based client or polyfill, or a cookie authentication design with appropriate browser and security settings. Chat and other streams that need a client-to-server message channel can use WebSocket instead.

Registering and removing emitters

A person can subscribe from several tabs or devices. I index connections by email with ConcurrentHashMap<String, CopyOnWriteArrayList<SseEmitter>>. A notification visits all emitters for that recipient.

flowchart TD
    A["Subscribe"] --> B["Register emitter"]
    B --> C["Send recent alerts"]
    C --> D["Push new alerts"]
    D --> E["Remove dead emitter"]

The copy-on-write list provides snapshot iteration. If a send throws IOException and removes its emitter, other connections in that iteration can still receive the notification. This has a cost when subscriptions churn because writes copy the list. It suits a workload where sends are more frequent than connection changes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// notification/application/NotificationSseService.kt
package org.project.portfolio.notification.application

import com.fasterxml.jackson.databind.ObjectMapper
import io.github.oshai.kotlinlogging.KotlinLogging
import org.project.portfolio.notification.presentation.response.NotificationResponse
import org.springframework.data.domain.PageRequest
import org.springframework.stereotype.Service
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter
import java.io.IOException
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.CopyOnWriteArrayList

@Service
class NotificationSseService(
    private val notificationQueryService: NotificationQueryService,
    private val objectMapper: ObjectMapper,
) {
    /** Active SSE clients, grouped by email */
    private val emitters = ConcurrentHashMap<String, CopyOnWriteArrayList<SseEmitter>>()

    /** Subscribe to notifications */
    fun subscribe(email: String): SseEmitter {
        val emitter = SseEmitter(SSE_TIMEOUT_MS)
        val userEmitters = emitters.computeIfAbsent(email) { CopyOnWriteArrayList() }
        userEmitters.add(emitter)

        val cleanup = { removeEmitter(email, emitter) }
        emitter.onCompletion(cleanup)
        emitter.onTimeout(cleanup)
        emitter.onError { cleanup() }

        sendEvent(email, emitter, "system", "connected")

        // Send the ten latest notifications
        notificationQueryService.getNotifications(email, PageRequest.of(0, 10)).forEach {
            sendEvent(email, emitter, "notification", objectMapper.writeValueAsString(it))
        }

        return emitter
    }

    /** Send a live alert to a recipient */
    fun sendToUser(
        email: String,
        notification: NotificationResponse,
    ) {
        val userEmitters = emitters[email] ?: return
        val payload = objectMapper.writeValueAsString(notification)
        userEmitters.forEach { emitter ->
            sendEvent(email, emitter, "notification", payload)
        }
    }

    private fun sendEvent(
        email: String,
        emitter: SseEmitter,
        eventName: String,
        data: Any,
    ) {
        try {
            emitter.send(SseEmitter.event().name(eventName).data(data))
        } catch (e: IOException) {
            logger.debug(e) { "Removing failed SSE connection: email=$email" }
            removeEmitter(email, emitter)
        }
    }

    private fun removeEmitter(
        email: String,
        emitter: SseEmitter,
    ) {
        emitters.computeIfPresent(email) { _, list ->
            list.remove(emitter)
            if (list.isEmpty()) null else list
        }
    }

    companion object {
        private const val SSE_TIMEOUT_MS = 60L * 60L * 1000L // One hour
        private val logger = KotlinLogging.logger {}
    }
}

Completion, timeout, errors, and failed sends all call removeEmitter(). computeIfPresent removes an email’s key when its list empties. The subscription begins with a connected event, which starts the response promptly, and sends the most recent ten alerts. Subsequent reconnects may replay recent alerts, so use a stable notification ID if the client deduplicates rows.

1
2
3
4
5
6
7
8
// notification/presentation/NotificationController.kt
@GetMapping(path = ["/subscribe"], produces = [MediaType.TEXT_EVENT_STREAM_VALUE])
@PreAuthorize("isAuthenticated()")
fun notificationSubscribe(
    @AuthenticationPrincipal jwt: Jwt,
): SseEmitter {
    return notificationSseService.subscribe(jwt.subject)
}

The controller declares MediaType.TEXT_EVENT_STREAM_VALUE. Proxies and clients can then treat the response as an event stream instead of buffering it as a regular JSON response.

Sending DTOs across the stream

Notification has a @ManyToOne association to User. Serializing a managed entity directly can traverse that association and expose account data such as the password hash, phone number, and roles. A closed persistence context creates a separate risk of failing on a lazy association.

1
2
3
4
5
6
7
8
9
10
11
12
// notification/domain/Notification.kt
@Entity
@SoftDelete(columnName = "is_deleted")
class Notification(
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    val id: Long = 0,
    val title: String,
    val content: String,
    @ManyToOne
    val receiver: User,
    val sender: String,
) : BaseTimeEntity()

I map query and command results to NotificationResponse in their transactional scopes. The emitter receives response data. That data contains the fields chosen for the API contract and does not require Hibernate to initialize an entity during serialization.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// notification/presentation/response/NotificationResponse.kt
data class NotificationResponse(
    val id: Long,
    val title: String,
    val content: String,
    val receiverId: Long,
    val sender: String,
    val createdAt: Instant,
) {
    companion object {
        fun from(notification: Notification): NotificationResponse {
            return NotificationResponse(
                id = notification.id,
                title = notification.title,
                content = notification.content,
                receiverId = notification.receiver.id,
                sender = notification.sender,
                createdAt = notification.createdAt,
            )
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// notification/application/NotificationCommandService.kt
@Service
@Transactional
class NotificationCommandService(
    private val notificationRepository: NotificationRepository,
    private val userRepository: UserRepository,
    private val notificationSseService: NotificationSseService,
) {
    fun sendNotification(
        notificationRequestDto: NotificationRequestDto,
        sender: String,
    ) {
        val receiverId = notificationRequestDto.receiver
        if (receiverId == null) {
            userRepository.findAll().forEach { user ->
                val saved = saveNotification(notificationRequestDto, receiver = user, sender = sender)
                notificationSseService.sendToUser(user.email, NotificationResponse.from(saved))
            }
        } else {
            userRepository.findByIdOrNull(receiverId)?.let { user ->
                val saved = saveNotification(notificationRequestDto, receiver = user, sender = sender)
                notificationSseService.sendToUser(user.email, NotificationResponse.from(saved))
            }
        }
    }
}

The domain notification listeners invoke the notification operation after the originating transaction commits. The storage of a notification and the delivery to an open connection are different events. If one SSE send fails, the stored notification can still appear when the client reconnects.

Releasing database resources before the stream waits

Open Session in View can keep an EntityManager available until a request completes. Connection retention depends on transaction and Hibernate settings. If an SSE request keeps a borrowed connection while the stream is open, ten subscribers can exhaust a ten-connection HikariCP pool. I turned OSIV off and made the initial history lookup a short service transaction, then sent its DTOs independently of that session.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# src/main/resources/application.yml
spring:
  threads:
    virtual:
      enabled: true

  lifecycle:
    timeout-per-shutdown-phase: 30s

  jpa:
    open-in-view: false
    properties:
      hibernate:
        default_batch_fetch_size: 100

server:
  shutdown: graceful
  • open-in-view: false keeps the persistence context boundary around the service operation.
  • Java 21 virtual threads help with some blocking I/O, but a virtual thread still cannot create an extra database connection or remove a slow client.
  • The configured 30-second graceful shutdown window bounds how long a deployment waits for in-flight work. Streams that outlast it close, and the browser reconnects to an available instance.

Running behind a proxy and across instances

Reverse proxies may buffer small SSE writes. For Nginx, configure proxy_buffering off; for the route or send X-Accel-Buffering: no where the proxy honors it. Make the upstream read timeout long enough, or send periodic heartbeats so idle streams remain active. Exercise reconnection with the actual load balancer, since each hop can have its own idle timeout.

The emitter registry only knows connections in one JVM. Once multiple replicas accept subscriptions, publish DTO events with Redis Pub/Sub and let each replica send to matching local emitters. Redis Pub/Sub does not persist pending notifications. Keep the database-backed history and client reconnect behavior if missed events matter.

  • Open two tabs for one account, close one, and confirm the other still receives alerts.
  • Test a timeout and a failed send, then inspect the registry for obsolete emitters.
  • Inspect database pool metrics while streams stay open after their initial history query.
  • Stop one replica and verify reconnection and catch-up through a different replica.
This post is licensed under CC BY 4.0 by the author.