Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Backend Development
11 min read

Stop Using WebSocket for One-Way Real-Time Push: SSE Implementation Guide with Spring Boot

This article compares polling, WebSocket, and SSE for real-time data push, demonstrating why Server-Sent Events is the optimal choice for one-way server-to-client streaming with practical Spring Boot implementation covering connection lifecycle, heartbeats, reconnection, multi-instance scaling, and Nginx configuration.

Problem: Polling Causes Unacceptable Latency

A factory dashboard originally used setInterval polling every 3 seconds, fetching six APIs to refresh production line counts, daily totals, and equipment status. During night shifts, the 3-second delay became critical — an equipment shutdown alarm took over two minutes to appear on screen because the polling interval masked the event.

Analysis revealed 90% of polling requests returned identical data, meaning most requests only confirmed "no change." The solution: let the server push updates only when data changes. The key architectural decision is not whether to push, but which push mechanism to use.

Three Push Mechanisms Compared

1. Polling

Client initiates requests on a timer. Not true push — the server passively responds. Costs include repeated connection establishment (TCP handshake), a persistent client-side timer, and browser connection limits (Chrome allows only 6 concurrent connections per domain). Worst of all: empty polling wastes resources querying the database only to return "no data."

2. WebSocket

True bidirectional channel over ws / wss protocol. Maximum capability but heaviest structure: requires server-side support, client adaptation, custom reconnection logic, and heartbeat implementation.

3. Server-Sent Events (SSE)

An unending HTTP response. Server keeps the response open and writes events downstream; client processes incrementally. Unidirectional — server to client only. Runs on standard HTTP, requiring no new ports, protocol upgrades, or firewall changes.

Decision Criterion: Do You Need Bidirectional Communication?

Server-to-client only (dashboards, unread counts, task progress, log streaming, order status, AI streaming responses): Use SSE.

Bidirectional (chat, collaborative editing, whiteboards, game frame sync): Must use WebSocket.

Temporary prototype : Polling is acceptable but not a long-term solution.

Rule: If SSE can do the job, don't add WebSocket complexity. The extra protocol overhead yields zero benefit for unidirectional flows.

Why SSE Is Simpler

SSE runs on HTTP. Only three response headers are needed:

Content-Type: text/event-stream
Cache-Control: no-cache
Connection: keep-alive

Meaning: this is an event stream, don't cache, don't close. Browsers handle the rest — no extra ports, no protocol upgrade, no gateway allowlist changes. This is huge in practice: many teams are blocked by "ops won't open WebSocket ports." SSE uses the already-open HTTP path.

Bonus: automatic reconnection is built into the browser — no custom code required.

Trade-offs: No IE support; not available in WeChat Mini Programs ( EventSource doesn't exist); unidirectional — client-to-server requires a separate REST call.

Spring Boot Implementation: Three Lines with SseEmitter

@GetMapping(value = "/screen/{lineId}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public SseEmitter subscribe(@PathVariable Long lineId) {
    SseEmitter emitter = new SseEmitter(0L); // 0 = no automatic timeout
    screenHub.register(lineId, emitter);
    return emitter;
}

The produces attribute sets the critical Content-Type header. Omitting it causes the browser to treat the response as JSON, breaking the stream. SseEmitter constructor argument is timeout in milliseconds. 0 means infinite — but don't actually do this without heartbeats (see below).

The Real Work: Clean Connection Lifecycle Management

The most common mistake: only calling send(), ignoring cleanup. A connection can end three ways: normal completion, timeout, or error. All three must remove the emitter from the registry, otherwise stale emitters accumulate in memory and cause exceptions on subsequent send() attempts, flooding logs.

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

public void register(Long lineId, SseEmitter emitter) {
    hub.computeIfAbsent(lineId, k -> new CopyOnWriteArraySet<>()).add(emitter);
    emitter.onCompletion(() -> remove(lineId, emitter));
    emitter.onTimeout(() -> {
        emitter.complete();
        remove(lineId, emitter);
    });
    emitter.onError(e -> remove(lineId, emitter));
}
send()

throwing exceptions is normal — user closes tab, network drops, laptop sleeps. The server discovers the broken connection only on the next send() failure.

Heartbeats: Prevent Silent Connection Termination

Proxies, load balancers, and cloud gateways all have idle timeouts. SSE sends nothing when idle, making it the most vulnerable to silent termination. Must send heartbeats — a comment line suffices:

@Scheduled(fixedRate = 20_000)
public void heartbeat() {
    hub.forEach((lineId, set) -> {
        for (SseEmitter emitter : set) {
            try {
                emitter.send(SseEmitter.event().comment("ping"));
            } catch (Exception e) {
                remove(lineId, emitter);
            }
        }
    });
}

Use comment not data — comments don't trigger client message events, so frontend stays clean, but the bytes still reset idle timers on the network path.

20 seconds is a safe default; must be shorter than the smallest idle timeout in your infrastructure chain. Check your gateway config — don't guess.

Message Format: Use event and id , Don't Hand-Craft

SSE format is strict: one field per line, data: followed by content, blank line terminates the message. Missing the final blank line causes the client to buffer indefinitely. SseEmitter handles formatting:

emitter.send(SseEmitter.event()
    .id(String.valueOf(seq))        // message sequence for replay on reconnect
    .name("line-status")           // event name for typed listeners
    .data(payload, MediaType.APPLICATION_JSON)
    .reconnectTime(3000));           // suggest browser reconnect delay
name

is especially valuable: multiple event types can share one connection. Frontend uses addEventListener('line-status', ...) for clean dispatch instead of parsing a type field inside a generic message handler.

Reconnection Is Free, But Gap-Filling Is Your Job

On reconnect, the browser sends the last received id in the Last-Event-ID header. This is SSE's most overlooked and valuable feature — it gives you a hook to replay missed messages.

@GetMapping(value = "/screen/{lineId}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public SseEmitter subscribe(@PathVariable Long lineId,
                            @RequestHeader(value = "Last-Event-ID", required = false) String lastId) {
    SseEmitter emitter = new SseEmitter(Duration.ofMinutes(30).toMillis());
    screenHub.register(lineId, emitter);
    if (lastId != null) {
        screenHub.replay(lineId, Long.parseLong(lastId))
            .forEach(e -> {
                try { emitter.send(e); } catch (Exception ignored) {}
            });
    }
    return emitter;
}

Without this, reconnection leaves a gap — the dashboard jumps from 120 to 137 with no record of the 17 missed events. For monitoring screens, a jump is more alarming than latency.

Frontend: Minimal EventSource Usage

const source = new EventSource(`/api/screen/${lineId}?ticket=${ticket}`);
source.onopen = () => console.log('connected', source.readyState);
source.onerror = () => console.log('disconnected, browser will reconnect', source.readyState);
source.addEventListener('line-status', e => {
    render(JSON.parse(e.data)); // typed listener, no manual dispatch
});
readyState

values: 0 = connecting or disconnected, 1 = open, 2 = closed permanently (usually server called complete() or auth failed). Only state 2 requires handling.

Critical: onerror fires on every network hiccup. Browser auto-reconnects. Never call new EventSource inside onerror — that stacks connections and exhausts the browser's connection limit.

On navigation/unmount: call source.close(). Otherwise SPA route changes leave zombie connections; server thinks clients are still listening.

Infrastructure: Nginx Must Not Buffer

Local works, test environment buffers entire response then flushes at once. Culprit: Nginx proxy_buffering default on.

location /api/screen/ {
    proxy_pass http://backend;
    proxy_http_version 1.1;
    proxy_set_header Connection '';
    proxy_buffering off;        # critical: don't buffer
    proxy_cache off;
    chunked_transfer_encoding off;
    proxy_read_timeout 3600s;   # don't let gateway kill long-lived connections
}
proxy_buffering off

is the key. Default on, Nginx accumulates upstream response in its buffer before forwarding — defeating streaming.

Raise proxy_read_timeout above your heartbeat interval. Default 60s; with 20s heartbeats it survives, but if someone disables heartbeats, all connections die at the 2-minute mark simultaneously.

Authentication: EventSource Cannot Send Custom Headers

new EventSource(url)

accepts only a URL — no headers. Authorization: Bearer xxx is impossible directly. Three workarounds:

Cookies : Simplest for same-origin deployments. EventSource sends cookies automatically. Requires withCredentials for cross-origin.

One-time ticket : Exchange a short-lived token via authenticated POST, then append to URL:

@PostMapping("/screen/ticket")
public String issueTicket(@CurrentUser Long userId) {
    String ticket = UUID.randomUUID().toString().replace("-", "");
    redis.opsForValue().set("sse:ticket:" + ticket, userId, Duration.ofSeconds(30));
    return ticket;
}

@GetMapping("/screen/{lineId}")
public SseEmitter subscribe(@PathVariable Long lineId, @RequestParam String ticket) {
    String key = "sse:ticket:" + ticket;
    String userId = redis.opsForValue().get(key);
    if (userId == null || !redis.delete(key)) {
        throw new ResponseStatusException(HttpStatus.UNAUTHORIZED);
    }
    // ... register emitter
}

Ticket must be short-lived, single-use, bound to user. Never put long-lived tokens in URLs — they leak into access logs, browser history, and copy-paste.

Fetch + ReadableStream : Use fetch with headers, read response.body as a stream, parse SSE format manually, implement reconnection. Only if you have special requirements; the ticket approach is simpler.

Multi-Instance: Broadcast via Redis Pub/Sub

Single instance: Map<Long, Set<SseEmitter>> works. Two instances: user's connection lands on instance A, business event occurs on instance B. B has the data but not the connection.

Solution: broadcast layer. Any instance publishes to a Redis channel; all instances subscribe and push to their local emitters only.

public void publish(Long lineId, String event, Object payload) {
    redis.convertAndSend("sse:screen:" + lineId,
        new ScreenMessage(event, objectMapper.writeValueAsString(payload)));
}

@Bean
public RedisMessageListenerContainer sseContainer(RedisConnectionFactory factory, ScreenHub hub) {
    RedisMessageListenerContainer container = new RedisMessageListenerContainer();
    container.setConnectionFactory(factory);
    container.addMessageListener((message, pattern) -> {
        String channel = new String(message.getChannel(), StandardCharsets.UTF_8);
        Long lineId = Long.valueOf(channel.substring(channel.lastIndexOf(':') + 1));
        hub.pushLocal(lineId, new String(message.getBody(), StandardCharsets.UTF_8));
    }, new PatternTopic("sse:screen:*"));
    return container;
}

Note pushLocal — each instance pushes only to emitters it holds locally. Missing emitters are silently skipped. Don't build a routing table mapping connections to instances; the complexity isn't worth it.

Optimization: Compute Once, Broadcast to Many

Dashboards often have multiple browser tabs viewing the same line. No need to query per connection. Scheduled job computes snapshot once per interval, broadcasts to all subscribers.

@Scheduled(fixedRate = 5_000)
public void broadcastLineStatus() {
    for (Long lineId : screenHub.activeLines()) {
        LineStatus status = statusService.snapshot(lineId); // one query
        hub.push(lineId, "line-status", objectMapper.writeValueAsString(status));
    }
}

This 5-second interval is not polling — direction reversed: server pushes on its schedule, client only receives. The frontend setInterval is deleted entirely.

Async Sending: Don't Let One Slow Client Block Others

emitter.send()

is a synchronous socket write. In a loop, a slow client (full send buffer) blocks the thread — all subsequent clients wait.

Fix: compute data synchronously, dispatch sends to a thread pool.

private final ExecutorService pusher = Executors.newFixedThreadPool(4);

public void pushAsync(Long lineId, String event, String data) {
    Set<SseEmitter> set = hub.getOrDefault(lineId, Set.of());
    for (SseEmitter emitter : set) {
        pusher.submit(() -> {
            try {
                emitter.send(SseEmitter.event().name(event).data(data));
            } catch (Exception e) {
                remove(lineId, emitter);
            }
        });
    }
}

Four threads suffice — they only write bytes, no business logic. Principle: no client's network condition may affect another's refresh cadence.

Similarly, don't let message queues grow unbounded. For dashboards, dropping intermediate snapshots is fine — the next full snapshot arrives shortly.

When WebSocket Is Still Required

Chat / customer service — both sides speak anytime

Collaborative editing / multi-user whiteboards — high-frequency upstream

Binary frames needed — SSE is text-only

Target is Mini Program or legacy IE — no EventSource support

If your business sends upstream half the time, SSE forces a separate REST API for upstream. Just use WebSocket.

Polling Still Has Niche Uses

Polling's virtues: one-line implementation, trivial debugging. Suitable for internal admin pages viewed twice daily, report pages, or short-lived "submit and wait for result" flows. The error is using polling for second-level dashboards and shortening intervals to compensate — 3s to 1s triples server load while still delivering up-to-1-second stale data.

Debugging: Use curl First

Skip browser DevTools initially. curl shows raw stream:

curl -N -H "Accept: text/event-stream" \
     "http://localhost:8080/api/screen/3?ticket=xxxx"
-N

disables curl's own buffering. If events appear line-by-line, backend is fine — problem is in gateway or frontend. If curl hangs then dumps everything at once, something in the chain (backend or gateway) is buffering.

Browser DevTools shows the request "pending" but won't reveal whether content streams or buffers.

Migration Result

Removed six polling endpoints, replaced with one text/event-stream endpoint. Frontend swapped setInterval for EventSource. Added heartbeats, replay logic, and three Nginx settings.

Most visible change: equipment shutdown appearance on dashboard dropped from 2+ minutes to instant — because it never should have waited for the next poll.

Selection heuristic: First ask which direction data flows, then ask if upstream is needed. "Downstream only" → SSE is the right-sized tool. Bidirectional → don't force it, use WebSocket. Reserve polling for pages that genuinely don't need real-time. Let simple things stay simple; don't let a dashboard carry 3-second latency that prompts "is this actually real-time?"

For attribution, corrections or content rights, contactadmin@besthub.dev

Report an issue with this article

Discussion 0

Write a comment

Sign in to join the discussion

No public comments on this page. Sign in to comment