System Design Part 5 Service communication

Real-Time Updates: Choosing Between Polling, Long Polling, SSE, and WebSocket, and Pushing from Many Servers

Bill.Lin 20 min read

System Design series Part 5-5 | Previous: Idempotency and Idempotency Keys | Next: Redundancy, Failover, and DR | Series map

Read first: Part 5-3 Pub/Sub and Delivery Semantics.

Scenario and problem

The moment sign-ups open for a popular lecture, 20,000 people are watching the “seats left” number on the lecture page. The number changes every second. Users want to see the live number, not tap “Sign up” and only then find out the lecture filled up long ago.

Once the lecture starts, there is a second need: live questions during the stream. Audience members send questions, the speaker and the rest of the audience see them right away, and the speaker can mark a question as “answered”.

When the server needs to speak first1 / 5
When the server needs to speak first20k usersServerSpeakerLive audience20k usersServerKeep refreshingWant the live count20k usersServerSign upFull long agoServer20k usersCan't push itCan only wait to be askedLive audienceServerSpeakerSend questionSee it at onceOthers must see it tooSpeakerServerLive audienceMark answeredPush to all
  1. Watching the seats leftThe moment sign-ups open for a popular lecture, 20,000 people are watching the seats left on the lecture page, and the number changes every second.
  2. Sign up, then find it fullThe number users see is already out of date. They tap Sign up and only then find out it filled up long ago.
  3. The server cannot speak firstHTTP was built for the client to ask and the server to answer. The seats change, but the server has no way to tell 20,000 browsers on its own.
  4. Live questions during the talkOnce the lecture starts, audience members send questions, and the speaker and other listeners need to see them right away. Unlike seats, questions are events: every single one must arrive.
  5. The speaker marks it answeredThe speaker marks a question as "answered", and that change must also reach every listener in real time. Questions go both ways, and only registered attendees can subscribe.

These two needs are not quite the same:

Seats left Live questions
Direction Server to browser only Both ways
Kind of data State: only the latest value matters Events: every one must arrive
Missing one update The next update overwrites it One question is lost
Subscribers Anyone, no login needed Registered attendees only

HTTP was built on “the client asks, the server answers”, and the server has no way to speak first. This post compares the ways to let the server “push” data, and the problems push runs into across many servers.

The simplest approach and its limits

Short polling: the browser calls GET /v1/lectures/42/seats every 2 seconds.

  • It is the simplest to build, and load balancing, caching, and monitoring all reuse your existing HTTP infrastructure
  • 20,000 people once every 2 seconds is 10,000 requests per second, and most responses are the same as the last one. Returning 304 with an ETag saves bandwidth, but the number of requests does not go down
  • The worst-case update delay is one polling interval. Shorten the interval and the number of requests grows in proportion

For a back-office tool with a few dozen users, or a page that updates every few minutes, short polling is plenty. The trouble starts when there are many users and they expect real time.

Core mechanism

The four approaches

sequenceDiagram
    participant B as Browser
    participant S as Server
    Note over B,S: Short polling
    B->>S: GET /seats
    S-->>B: 120 (immediate response)
    B->>S: GET /seats (2 seconds later)
    S-->>B: 120 (must respond even with no change)
    Note over B,S: Long polling
    B->>S: GET /seats?after=v17
    Note right of S: Responds only on a change,<br/>or after a 30-second timeout
    S-->>B: 119 (v18)
    B->>S: GET /seats?after=v18 (sent again right away)
    Note over B,S: SSE
    B->>S: GET /seats/stream
    S-->>B: event: seats (connection stays open)
    S-->>B: event: seats
    Note over B,S: WebSocket
    B->>S: GET /ws (Upgrade: websocket)
    S-->>B: 101 Switching Protocols
    B->>S: Question
    S-->>B: New questions, seat changes

Long polling: the server does not respond right away when a request arrives; it waits until there is new data or a timeout. The client sends the next request as soon as it gets a response. Latency is close to real time, and it is still an ordinary HTTP request. But every message costs a new request, and a change that happens between two requests has to be recovered with a cursor such as after=v18, or it is lost.

Server-Sent Events (SSE): the browser sends a GET with EventSource. The server responds with Content-Type: text/event-stream, does not end the response, and keeps writing events:

text
id: 18
event: seats
data: {"lectureId":42,"remaining":119,"version":18}

: this is a comment line; it can serve as a heartbeat

The SSE specification (WHATWG HTML Living Standard) builds in a few important behaviors:

  • Automatic reconnection: when the connection drops, the browser reconnects on its own. The server can adjust the reconnection interval with the retry: field
  • Resuming where it left off: on reconnect, the browser sends the id of the last event it received in the Last-Event-ID header, and the server can resend everything after it
  • Stopping reconnection: if the server returns a status other than 200 (204, for example), the browser stops reconnecting
  • One-way, text only: data flows only from the server to the browser, as UTF-8 text. To send data, the client makes a separate ordinary HTTP request

WebSocket (RFC 6455): one HTTP request negotiates an upgrade. After the server answers 101 Switching Protocols, the TCP connection is no longer HTTP but a two-way message channel. It has the lowest latency and works both ways, but once the connection is up, everything is yours to handle:

  • No built-in reconnection, no resuming
  • No message “type” or “destination”; you define your own format, or use a subprotocol such as STOMP
  • The protocol has ping/pong control frames, but the browser’s JavaScript API cannot send a ping on its own, so the application layer usually still needs its own heartbeat

Direction decides most of the choice

The seat count only needs the server to push to the browser, so SSE is enough, and automatic reconnection and resuming come for free. Live questions are a two-way interaction, and WebSocket is the more natural fit. But “two-way” can also be split into “SSE to receive plus an ordinary POST to send”. For actions that are not sent often (one person asks a question every few minutes), this is usually simpler, and it reuses your existing API authentication, rate limiting, and idempotency design (Idempotency and Idempotency Keys post). WebSocket’s real advantage is in scenarios where both sides send often, such as collaborative editing and multiplayer games.

Long-lived connections change the shape of the server

A short-polling request finishes in a few milliseconds; SSE and WebSocket connections stay open for tens of minutes. That brings a few problems that are not obvious with an ordinary API:

  • The connection count becomes the capacity limit: 20,000 people online means 20,000 connections open at the same time. Servlet async processing (SseEmitter) and WebFlux do not hold a thread per connection, but every connection still costs memory, a file descriptor, and load balancer resources
  • Idle timeouts on intermediate devices: load balancers and reverse proxies cut connections that carry no data for a while (the AWS ALB default is 60 seconds, and nginx’s proxy_read_timeout also defaults to 60 seconds). The server has to send heartbeats at an interval shorter than the shortest idle timeout
  • Proxy buffering: a reverse proxy may buffer the response and forward it only once it reaches a certain size, so SSE events arrive late. In nginx, the response header X-Accel-Buffering: no turns off buffering for a single response
  • The browser’s connection limit: under HTTP/1.1, browsers allow very few simultaneous connections to the same domain (commonly 6), shared by all tabs. If a user opens 6 lecture tabs, the 7th cannot connect. HTTP/2 multiplexing solves this
  • A deploy is a mass disconnect: during a rolling update, every connection on the server being shut down drops at once and reconnects at once. Add a random delay to reconnects (jitter, covered in Part 6), and before a server shuts down it should first stop accepting new connections, then close the existing ones in batches

Fan-out across many servers

User A’s SSE connection is on server 1, and user B’s sign-up request lands on server 2. Server 2 decrements the seats, but it does not hold A’s connection. Every server needs to know about every change, and then push it to the connections it holds:

flowchart LR
    R[Sign-up request] --> S2[Server 2]
    S2 -->|publish after commit| P[(Redis Pub/Sub<br/>or broker)]
    P --> S1[Server 1] --> A1[10,000 connections]
    P --> S2 --> A2[10,000 connections]
Fan-out method Characteristics
Redis Pub/Sub Simple, low latency; at-most-once, so messages sent while a subscriber is disconnected are lost
Message broker (e.g. RabbitMQ with the STOMP plugin, relayed by Spring’s broker relay) The broker manages subscriptions and the app servers only relay; one more component to operate
Kafka Can replay; every server must receive every event, so each server uses its own consumer group instead of sharing one (Pub/Sub post)

Because the fan-out channel can lose messages, real-time push should be treated as a hint, not as the source of truth. The database is the truth:

  • State data (seats left): on every connect or reconnect, send the full current state first, then push changes. If one change is missed, the next one overwrites it
  • Event data (questions): every event has an increasing ID. On reconnect, use Last-Event-ID or an after= cursor to recover the missed events from the database

Conflating updates

In the first second after sign-ups open there are 500 sign-ups, and each one changes the seat count. Pushing every change to 20,000 connections means 500 × 20,000 = 10 million messages per second, and a browser that receives 500 numbers in one second only shows the last one.

State data can be conflated: keep only the latest value for each lecture and push once a second. That brings the volume down to 20,000 messages per second, and users see at most one extra second of delay. Event data cannot be conflated, but it can be batched: put several questions from the same second into one message.

Slow clients

The server decides how fast it pushes; the client’s network decides how fast it receives. When a phone on the MRT cannot keep up, the server has to hold the messages in that connection’s buffer. Without a limit, a few slow clients will eat all of the server’s memory. So every connection needs a buffer limit and a send timeout. When either is exceeded, drop that connection and let the client reconnect and fetch the full state again.

Comparing options

Option Direction Reconnect and resume Infrastructure Good for
Short polling Client pulls Not needed Ordinary HTTP, cacheable Few users, relaxed latency needs
Long polling Close to push Handle it yourself with a cursor Ordinary HTTP, but requests hang for a long time Environments that cannot use SSE or WebSocket
SSE Server → browser Built-in browser reconnection and Last-Event-ID Ordinary HTTP; watch proxy buffering and the HTTP/1.1 connection limit Notifications, dashboards, live numbers, progress
WebSocket Two-way All on you Protocol upgrade; load balancers and proxies must support it Collaborative editing, chat, games

The lecture platform’s choice: SSE for seats left, and WebSocket plus STOMP for live questions, because speakers and listeners interact often (asking, liking, marking as answered).

In Java

1. Seats left: SSE with conflated pushes

java
public record SeatChanged(long lectureId, int remaining, long version) {
}

@Component
public class SeatStreamHub {

    private final Map<Long, Set<SseEmitter>> subscribers = new ConcurrentHashMap<>();
    private final Map<Long, SeatChanged> pending = new ConcurrentHashMap<>();

    /** Called on connect or reconnect: send the full current state first, then push changes. */
    public SseEmitter subscribe(SeatChanged snapshot) {
        long lectureId = snapshot.lectureId();
        SseEmitter emitter = new SseEmitter(Duration.ofMinutes(30).toMillis());
        subscribers.compute(lectureId, (id, set) -> {
            Set<SseEmitter> emitters = set != null ? set : ConcurrentHashMap.newKeySet();
            emitters.add(emitter);
            return emitters;
        });
        emitter.onTimeout(emitter::complete);                    // complete normally on timeout; the browser reconnects on its own
        emitter.onCompletion(() -> unsubscribe(lectureId, emitter));
        send(lectureId, emitter, event(snapshot));
        return emitter;
    }

    /** Triggered by a Redis message: record only the latest state of each lecture, do not push yet. */
    public void offer(SeatChanged change) {
        pending.merge(change.lectureId(), change,
                (current, incoming) -> incoming.version() > current.version() ? incoming : current);
    }

    @Scheduled(fixedRate = 1_000)
    public void flush() {
        for (Long lectureId : pending.keySet()) {
            SeatChanged latest = pending.remove(lectureId);
            Set<SseEmitter> emitters = subscribers.get(lectureId);
            if (latest != null && emitters != null) {
                emitters.forEach(emitter -> send(lectureId, emitter, event(latest)));
            }
        }
    }

    @Scheduled(fixedRate = 15_000)
    public void heartbeat() {                                    // shorter than the load balancer's idle timeout
        subscribers.forEach((lectureId, emitters) ->
                emitters.forEach(emitter -> send(lectureId, emitter, SseEmitter.event().comment("ping"))));
    }

    private static SseEmitter.SseEventBuilder event(SeatChanged change) {
        return SseEmitter.event()
                .id(String.valueOf(change.version()))
                .name("seats")
                .data(change);
    }

    private void send(long lectureId, SseEmitter emitter, SseEmitter.SseEventBuilder event) {
        try {
            emitter.send(event);
        } catch (IOException | IllegalStateException disconnected) {
            unsubscribe(lectureId, emitter);                     // the client is gone; the container ends this request
        }
    }

    private void unsubscribe(long lectureId, SseEmitter emitter) {
        subscribers.computeIfPresent(lectureId, (id, set) -> {
            set.remove(emitter);
            return set.isEmpty() ? null : set;
        });
    }
}
java
@RestController
public class SeatStreamController {

    private final SeatStreamHub hub;
    private final LectureQueryService lectures;

    public SeatStreamController(SeatStreamHub hub, LectureQueryService lectures) {
        this.hub = hub;
        this.lectures = lectures;
    }

    @GetMapping(path = "/v1/lectures/{lectureId}/seats/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter stream(@PathVariable long lectureId) {
        // Seats are state: on reconnect, send the latest full state; no need to replay from Last-Event-ID
        return hub.subscribe(lectures.currentSeats(lectureId));
    }
}
  • Adding and removing both happen inside the compute family of methods on ConcurrentHashMap, and operations on the same key are atomic. You never get “one thread just removed the empty set while another thread adds a connection to that old set”
  • send throwing IOException means the client has already disconnected. Just remove the emitter then, and do not call completeWithError: Spring MVC ends the request through the container’s error notification
  • Conflated results from different seconds can arrive out of order because of message delays, so the browser should ignore events whose version is lower than the current one

2. Cross-server fan-out: Redis Pub/Sub

java
@Configuration
public class RealtimeRelayConfig {

    static final String SEAT_CHANNEL = "realtime:lecture-seats";
    static final String QUESTION_CHANNEL = "realtime:lecture-questions";

    @Bean
    RedisMessageListenerContainer realtimeListener(RedisConnectionFactory connectionFactory, JsonMapper jsonMapper,
                                                   SeatStreamHub seats, SimpMessagingTemplate stomp) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.addMessageListener(
                (message, pattern) -> seats.offer(jsonMapper.readValue(message.getBody(), SeatChanged.class)),
                new ChannelTopic(SEAT_CHANNEL));
        container.addMessageListener((message, pattern) -> {
            QuestionView question = jsonMapper.readValue(message.getBody(), QuestionView.class);
            stomp.convertAndSend("/topic/lectures/" + question.lectureId() + "/questions", question);
        }, new ChannelTopic(QUESTION_CHANNEL));
        return container;
    }
}

@Component
public class RealtimePublisher {

    private final StringRedisTemplate redis;
    private final JsonMapper jsonMapper;

    public RealtimePublisher(StringRedisTemplate redis, JsonMapper jsonMapper) {
        this.redis = redis;
        this.jsonMapper = jsonMapper;
    }

    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
    public void on(SeatChanged change) {
        redis.convertAndSend(RealtimeRelayConfig.SEAT_CHANNEL, jsonMapper.writeValueAsString(change));
    }

    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
    public void on(QuestionView question) {
        redis.convertAndSend(RealtimeRelayConfig.QUESTION_CHANNEL, jsonMapper.writeValueAsString(question));
    }
}
  • Every server subscribes to the same channel, so every server receives every change and pushes it to the connections it holds
  • Publish only after the transaction commits (the same approach as in the Message Queues post), so you never push a seat count that is later rolled back
  • Redis Pub/Sub is at-most-once. When a server briefly loses its connection to Redis, the connections it holds miss a few updates; the seat count is overwritten by the next change, and the browser recovers questions through its cursor when it reconnects

3. Live questions: STOMP over WebSocket

java
@Configuration
@EnableWebSocketMessageBroker
public class QnaWebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws").setAllowedOrigins("https://lectures.example.com");
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.setApplicationDestinationPrefixes("/app");     // messages the client sends to /app/** go to @MessageMapping
        registry.enableSimpleBroker("/topic");                   // each server keeps its own subscription table; Redis fans out across servers
    }

    @Override
    public void configureWebSocketTransport(WebSocketTransportRegistration registration) {
        registration.setMessageSizeLimit(16 * 1024)             // a question never needs a larger message
                .setSendTimeLimit(10_000)
                .setSendBufferSizeLimit(256 * 1024);             // a slow client over the limit is disconnected
    }
}
java
@Controller
public class QnaController {

    private final QuestionService questions;

    public QnaController(QuestionService questions) {
        this.questions = questions;
    }

    @MessageMapping("/lectures/{lectureId}/questions")
    public void ask(@DestinationVariable long lectureId, @Payload AskQuestion request, Principal principal) {
        // Validate length, rate limit, write to the database; after commit RealtimePublisher publishes to Redis and every server broadcasts
        questions.ask(lectureId, principal.getName(), request.text());
    }
}

The controller does not broadcast directly. It writes to the database, and only after the commit does the question fan out through Redis. That way, every question that gets pushed is already in the database, and on reconnect the browser can call GET /v1/lectures/42/questions?after={last question ID} to recover what it missed.

4. Per-message authorization

java
@Configuration
@EnableWebSocketSecurity
public class QnaWebSocketSecurityConfig {

    @Bean
    AuthorizationManager<Message<?>> messageAuthorizationManager(
            MessageMatcherDelegatingAuthorizationManager.Builder messages, AttendanceService attendance) {
        AuthorizationManager<MessageAuthorizationContext<?>> attendeeOnly = (authentication, context) -> {
            Authentication auth = authentication.get();
            OptionalLong lectureId = parseId(context.getVariables().get("lectureId"));
            boolean allowed = auth != null && auth.isAuthenticated() && lectureId.isPresent()
                    && attendance.isAttendee(lectureId.getAsLong(), auth.getName());
            return new AuthorizationDecision(allowed);
        };
        messages
                .nullDestMatcher().authenticated()                              // CONNECT, DISCONNECT, etc.
                .simpDestMatchers("/app/lectures/{lectureId}/questions").access(attendeeOnly)
                .simpSubscribeDestMatchers("/topic/lectures/{lectureId}/questions").access(attendeeOnly)
                .anyMessage().denyAll();                                        // deny everything else
        return messages.build();
    }

    private static OptionalLong parseId(String value) {
        try {
            return value == null ? OptionalLong.empty() : OptionalLong.of(Long.parseLong(value));
        } catch (NumberFormatException e) {
            return OptionalLong.empty();
        }
    }
}
  • Both subscribing and sending must check “is this person an attendee of this lecture”, not just “is this person logged in”
  • The final anyMessage().denyAll() matters: without it, a client can SEND straight to /topic/lectures/42/questions. Messages that start with /topic go straight to the broker for broadcast, bypassing the validation, rate limiting, and database in QnaController entirely
  • @EnableWebSocketSecurity requires a CSRF token on the STOMP CONNECT frame by default, which ensures that only same-origin pages can open a connection

The code above is written against the official documentation for Spring Framework 7, Spring Security 7.1, Spring Boot 4.1 (Jackson 3), and Spring Data Redis; it has not been compiled or run.

Pitfalls and gotchas

  • No heartbeat: the connection sits idle on the load balancer for 60 seconds and gets cut, so to the client it looks like “a disconnect every minute”. The server also cannot tell that the client has left, because the Servlet API has no notification for a client disconnect; it finds out only when a write fails
  • A proxy buffers SSE: it works in local testing, and after launch the events arrive in batches. Check the buffering settings on every proxy layer
  • Treating push as the truth: if the client updates the screen only from pushes, missing one leaves it wrong forever. On connect and on reconnect, fetch the full state or recover the events from the database
  • No conflation: every change to a popular lecture goes to everyone, so the push volume is the number of changes times the number of connections
  • A deploy causes a reconnect storm: every connection reconnects in the same second and queries the full state at once, and the database goes down. Add a random delay to reconnects, and cache the full state
  • Fan-out through a shared consumer group: when you fan out with Kafka and several servers share one consumer group, each event reaches only one of them, and users on the other servers never see it
  • Pub/Sub on Redis Cluster: a regular PUBLISH sends the message to every node in the cluster, which becomes a bottleneck at high volume. Since Redis 7 there is sharded Pub/Sub (SPUBLISH), where messages travel only within the shard that owns the channel
  • Monitoring connection counts: for an ordinary API you watch QPS; for long-lived connections you watch concurrent connections, how connections are spread across servers, and new connections per second. A load balancer assigns new connections round robin, but existing connections are never reassigned, so a newly added server can go a long time with no connections

Security

  • Cross-Site WebSocket Hijacking: browsers attach cookies automatically when opening a WebSocket, and the handshake is not protected by a CORS preflight. A malicious site can connect to your WebSocket with the user’s logged-in identity, read the live questions, and send messages in the user’s name. The server must check Origin: Spring accepts only same-origin requests by default; list only your own domains in setAllowedOrigins, never *; and add Spring Security’s CSRF check on CONNECT
  • Tokens in the URL: neither the browser’s WebSocket API nor EventSource can set custom headers, so a common approach is to put the token in the query string. But URLs end up in access logs, proxy logs, and browser history. Prefer a cookie plus an origin check; when you must use a token, send it in the STOMP CONNECT frame, or trade a single-use token that is valid for a few tens of seconds for the connection
  • Checking permissions only on connect: a long-lived connection can last for hours. After a user logs out, is removed from the lecture, or has their token expire, a connection that already subscribed keeps receiving messages. When permissions are revoked, actively close the affected connections, or re-verify periodically
  • Per-message authorization: every SUBSCRIBE must check whether the subscriber may see that destination; for example, /topic/speakers/7/registrations on the speaker dashboard can be subscribed to only by speaker 7 (the same problem as object-level authorization in a REST API, covered in Part 8). Finish with denyAll so nothing slips through
  • Stored XSS, amplified: one malicious question is pushed to 20,000 browsers in real time. The frontend must always display questions as plain text (textContent, not innerHTML), and the server should also limit their length and content
  • Connection exhaustion attacks: an attacker opens many connections but never reads from them, tying up the server’s connections and buffers. Limit the number of connections per user and per IP, the message size, and the send rate, and set a send timeout and a buffer limit
  • Keep public and private data apart: seats left is public information and can go without login; the speaker’s attendee list is personal data, so do not share an endpoint or a topic namespace with the public stream

When to use it, and when not to

  • Use SSE: one-way server push for notifications, live numbers, task progress, and dashboards, and for responses streamed token by token, such as from an LLM
  • Use WebSocket: interactions where both sides send messages often, such as chat, collaborative editing, and multiplayer games
  • Use short polling: when there are few users, updates are slow, or the infrastructure does not support long-lived connections, it is still the easiest option to operate
  • Use none of these: for notifications to users who are not online. A user who has closed the page receives neither SSE nor WebSocket messages; use email or a mobile push notification service

References

Comments