Video in progress
When a Spring MVC method returns an `SseEmitter`, does the Tomcat thread stay busy for the whole connection?
No. SseEmitter uses Servlet async: after the controller returns, the request thread goes back to the pool while the connection stays open. But every open connection is still a resource tied to a socket, memory and a timeout.
📖 Answer
When a controller returns an SseEmitter, Spring calls request.startAsync(). The Tomcat thread is freed and the response stays open. Then any thread can write with emitter.send(...).
That's why a Tomcat with 200 threads can hold several thousand SSE connections. Other things set the limit:
server.tomcat.max-connections(default 8192 for NIO): beyond that, new connections wait in the queue;- the timeout. In Spring it's
spring.mvc.async.request-timeoutornew SseEmitter(ms). If you don't set one, the container default applies and the connection closes at an unexpected time; send()is blocking. A thread writing to a slow client waits until the socket buffer drains.
That last point is often forgotten. For example, one @Scheduled method does send to 5000 emitters one after another. If one client's network is bad, everyone else is delayed. The fix is to move the sending to a separate executor or to keep a queue per emitter.
Don't forget cleanup:
emitter.onCompletion(() -> registry.remove(emitter));
emitter.onTimeout(() -> registry.remove(emitter));
emitter.onError(e -> registry.remove(emitter));
Otherwise dead emitters stay in the list, every send throws IOException, and you get a memory leak.
One more thing: even with virtual threads enabled on Java 21, this model doesn't change. SSE keeps working asynchronously.
Sign up to mark studied questions and save your progress.