← All topics
Start ▶
WebSocket and real-time
WebSocket, STOMP, SSE and real-time systems.
100 questions
Level:
No questions match — try other words or turn a level back on.
1
What is WebSocket, and how does it differ from a plain HTTP request-response?
WebSocket is a two-way, long-lived channel over a single TCP connection. With HTTP the client asks, the server answers, and that's the end of it. With WebSocket the server can also send a message on its own at any time.
2
How is a WebSocket connection opened between a browser and a server?
The client sends a normal HTTP GET with the Upgrade: websocket and Connection: Upgrade headers. If the server agrees, it returns 101 Switching Protocols and that same TCP connection switches to the WebSocket protocol.
3
What is the difference between ws:// and wss://, and which one do you use in production?
ws:// is unencrypted WebSocket, wss:// is WebSocket over TLS, just like http and https. In production, only wss://: the traffic is encrypted and corporate proxies are less likely to break the connection.
4
How do you tell short polling, long polling and WebSocket apart?
Short polling: the client asks every N seconds and often gets an empty answer. Long polling: the server holds the response until new data appears. WebSocket: one persistent connection, and either side can write at any time.
5
What is Server-Sent Events (SSE) and how does it work?
SSE is a standard where the server sends a stream of events to the client inside a normal HTTP response, without closing the connection. It is one-way only: server to client. The browser has the EventSource API for it.
6
For a notification feed, would you pick SSE or WebSocket? What do you base the decision on?
The main question is whether data flows in both directions often. If it's only server to client, SSE is simpler: plain HTTP and automatic reconnect. If the client also writes constantly (chat, games), use WebSocket.
7
What is a frame in WebSocket, and how do text frames differ from binary frames?
A frame is the smallest unit of data in WebSocket: a small header (opcode, length, mask) and a payload. In a text frame the payload must be UTF-8 text; in a binary frame it can be any bytes.
8
What are the main events of the browser WebSocket API?
Four: onopen (the connection is ready), onmessage (a message arrived), onerror (an error), onclose (the connection closed). You send with send() and close with close().
9
How do you write the simplest possible WebSocket endpoint in Spring Boot without STOMP?
Add spring-boot-starter-websocket, write a handler that extends TextWebSocketHandler, and register it on a URL through @EnableWebSocket plus WebSocketConfigurer.
10
What is STOMP, and why is it used on top of WebSocket?
STOMP is a simple text-based messaging protocol with commands like CONNECT, SUBSCRIBE, SEND and MESSAGE, plus headers. WebSocket only "delivers bytes"; STOMP adds destinations, subscriptions and routing on top.
11
What do the @MessageMapping and @SendTo annotations do in Spring?
@MessageMapping routes a STOMP message from the client to a method by destination; it's the messaging equivalent of @RequestMapping. @SendTo sends the value the method returns to all subscribers of the given topic.
12
Why was SockJS needed, and is it still mandatory to enable it today?
SockJS is a fallback layer that automatically switches to HTTP streaming or long polling where WebSocket doesn't work (old browsers, proxies that cut WebSocket). Today almost every browser and piece of infrastructure supports WebSocket, so in many projects it isn't required.
13
How is a WebSocket connection closed, and what do the close codes 1000, 1001 and 1006 mean?
One side sends a close frame, the other answers with a close frame too, and then TCP is closed. 1000 is a normal close, 1001 means a side is going away (tab closed, server shutting down), 1006 means no close frame arrived at all and the connection dropped abruptly.
14
What are ping and pong frames in WebSocket for?
Ping/pong are control frames that check the connection is still alive. One side sends a ping, and the other must answer with a pong. This both detects dead connections and stops proxies from closing the connection on their idle timeout.
15
What does WebSocket being stateful mean for the server side?
From the moment a client connects until it disconnects, it is tied to one specific server instance, which holds its session, buffers and socket. So the simple REST model, "every request can go to any instance", doesn't work.
16
How do you send a message from the server to a client using SimpMessagingTemplate?
Inject the SimpMessagingTemplate bean and call convertAndSend("/topic/...", payload). This sends the message to every client subscribed to that destination, and you can call it from any service or scheduled job.
17
What do the /app and /topic prefixes mean in a Spring STOMP configuration?
/app is the application destination prefix: messages starting with it go to your @MessageMapping methods. /topic (and /queue) are broker prefixes: those messages go straight to the broker and are distributed to subscribers.
18
What is the logical difference between sending to a topic and to a queue in STOMP?
By convention, /topic is broadcast: one message goes to all subscribers. /queue is point-to-point: the message is for a single recipient, usually sent to a specific user as /user/queue/....
19
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.
20
How do you test a WebSocket endpoint by hand?
The quickest way is the wscat or websocat CLI tools and the Network → WS tab in the browser DevTools. Postman also supports WebSocket requests. For STOMP you have to write the frames by hand, or connect through stomp.js from a small HTML page.
21
What are the Sec-WebSocket-Key and Sec-WebSocket-Accept headers in the handshake for? Do they provide security?
The server appends a fixed GUID to Sec-WebSocket-Key, takes the SHA-1, Base64-encodes it, and returns it as Sec-WebSocket-Accept. This is only proof that "the server really understands WebSocket". It is neither authentication nor encryption.
22
Why are WebSocket frames sent by the client masked, while the ones sent by the server are not?
Masking means every client frame is XORed with a random 4-byte key. It is not encryption. The point is that a malicious page can't use WebSocket to trick intermediary caching proxies into poisoning their cache.
23
What happens if two threads call sendMessage() on the same WebSocketSession at the same time?
A standard JSR-356 session doesn't support concurrent sending: you get an IllegalStateException (with a state like "TEXT_FULL_WRITING") or the frames get interleaved. In Spring the fix is to wrap the session in a ConcurrentWebSocketSessionDecorator, or to funnel all sends through a single thread.
24
When an SSE connection drops, how does EventSource reconnect, and what is Last-Event-ID for?
If the connection drops, EventSource reconnects automatically and sends the id of the last event it received in the Last-Event-ID header. The server can use that value to resend the events that were missed, but the server has to do that itself; it isn't automatic.
25
Why is the client not receiving any messages with this STOMP setup?
The client subscribed to /app/news, but /app is the prefix for sending messages to controllers, and the broker distributes nothing there. The subscription has to go to the destination in @SendTo, which is /topic/news.
26
The browser WebSocket API doesn't let you add an Authorization header. How do you authenticate the connection then?
There are three common ways: a session or token in a cookie (it goes with the handshake automatically), a short-lived one-time ticket in a query parameter, or, with STOMP, the token in the CONNECT frame header. Putting a long-lived JWT in the URL is a bad idea.
27
How do convertAndSendToUser() and @SendToUser deliver a message to exactly the right user?
Spring has a UserDestinationMessageHandler: it translates an address like /user/{name}/queue/x into a unique destination for each of that user's sessions (for example /queue/x-user{sessionId}). For this to work, the Principal must be established when the connection is made.
28
Why is setAllowedOrigins("*") on a WebSocket endpoint dangerous?
The browser's same-origin policy (CORS) doesn't apply to the WebSocket handshake, but cookies are sent automatically. If the Origin isn't checked, any foreign site can connect as the user and read their data. This is Cross-Site WebSocket Hijacking.
29
What happens if you don't give a timeout when you create an SseEmitter?
new SseEmitter() gets the server's default async timeout, which on Tomcat is about 30 seconds. After that the connection is closed, AsyncRequestTimeoutException shows up in the logs, and the client reconnects every half minute.
30
WebSocket works locally, but behind Nginx the handshake fails or the connection drops after 60 seconds. What is the cause?
By default Nginx doesn't forward the Upgrade and Connection hop-by-hop headers to the backend and uses HTTP/1.0, so the upgrade never happens. The 60-second drop is the default proxy_read_timeout: if there's no traffic on the connection, Nginx closes it.
31
What is the difference between Spring's simple broker and an external broker relay (for example the RabbitMQ STOMP plugin), and when do you switch?
The simple broker is an in-memory broker inside Spring: fast and needs no setup, but it works only within a single instance and doesn't store messages. The broker relay forwards messages to an external STOMP broker, so several instances see one shared space of subscriptions.
32
How do you validate a JWT in the STOMP CONNECT frame in Spring and bind the user to the session?
You add a ChannelInterceptor to the clientInboundChannel: on the CONNECT command it takes the token from the header, validates it and calls accessor.setUser(authentication). After that every message in that session carries a Principal.
33
How is the STOMP heartbeat negotiated, and why is it set separately for each direction?
The CONNECT and CONNECTED frames carry a heart-beat: cx,cy header: the first number is how often I can send, the second is how often I want to hear from you. For each direction the larger of the two sides' values is used, and 0 means "off".
34
How do you write reconnect logic on the client when a WebSocket drops?
Retry with a delay that grows on every drop (exponential backoff), add random jitter on top, and cap it at a maximum. After a successful connection the counter resets, and subscriptions and, if needed, the lost state are reloaded.
35
How do you write an SSE endpoint in Spring WebFlux, and how does it differ from SseEmitter in Spring MVC?
In WebFlux the controller returns a Flux<ServerSentEvent<T>> and the framework sends each element as an event. You don't store emitters by hand or catch send and IOException; when the client leaves, the subscription is cancelled automatically.
36
How do you track who is online on the site using WebSocket connections?
Spring STOMP publishes connection lifecycle events: SessionConnectedEvent, SessionSubscribeEvent, SessionDisconnectEvent. You listen to them with @EventListener and maintain a map of user to session count; with several instances, this state is kept in a shared place such as Redis.
37
If an exception is thrown in a @MessageMapping method, how does the client find out?
By default there is no reply at all: the exception is logged and the client stays silent. To return the error to the client, use @MessageExceptionHandler and @SendToUser("/queue/errors"), and the client subscribes to that queue.
38
How do you check a STOMP endpoint with an integration test?
With @SpringBootTest(webEnvironment = RANDOM_PORT) a real server starts. You connect with WebSocketStompClient, subscribe to a topic, send a message, and wait for the reply with a timeout through a BlockingQueue or CompletableFuture.
39
Which limits do you configure in Spring for WebSocket message size and send buffers?
Three main ones: the maximum size of an incoming message (setMessageSizeLimit), the send buffer for one session (setSendBufferSizeLimit), and the maximum time one send may take (setSendTimeLimit). The last two protect against slow clients.
40
How do you do long polling in Spring MVC without using WebSocket?
The controller returns a DeferredResult<T> and stores it in a map, so the servlet thread is freed immediately. When data appears, another thread calls setResult() and the response goes out. On timeout an empty response (for example 204) is returned and the client asks again.
41
STOMP messages are reaching clients late. How do you find the problem in Spring's internal channels and thread pools?
Spring STOMP uses three channels: clientInboundChannel, clientOutboundChannel and brokerChannel, each with its own executor. WebSocketMessageBrokerStats logs their queue sizes and active threads every 30 minutes (more often if configured); that shows which one is jammed.
42
Can one slow client make the server run out of memory? How do you handle backpressure in WebSocket?
Yes. The server writes fast, the client reads slowly, and messages pile up in the session buffer on the server. The defense: a buffer and time limit per session, closing the session or dropping old messages when it fills up, and sending data as "the latest state" rather than "every change".
43
The app was scaled to two instances, and some chat messages aren't reaching some users. How do you explain the cause, and what do you do?
The simple broker lives in each instance's memory. A message goes only to subscribers on the instance the writer is connected to; those on other instances never see it. The fix is a shared channel between instances: a STOMP broker relay, or fan-out to every instance through Redis pub/sub or Kafka.
44
Do you need sticky sessions on the load balancer for WebSocket? What about when SockJS is used?
For pure WebSocket, usually not: the connection is a single TCP connection, so it stays on the server where it was opened. With SockJS's HTTP fallback transports, one session consists of many separate HTTP requests, and they must land on the same server, so sticky sessions are required.
45
In Spring STOMP, is the order of messages from or to one client preserved?
By default there is no guarantee: clientInboundChannel and clientOutboundChannel use thread pools, and consecutive messages from one session can be processed in parallel on different threads. Since Spring 5.1 setPreservePublishOrder(true), and since 6.1 setPreserveReceiveOrder(true), keep the order per session.
46
A client drops for 20 seconds and reconnects. What do you design so the messages from that time aren't lost?
WebSocket itself doesn't store messages, so every message gets a monotonic seq within the channel, and messages are stored (DB, Redis Stream, Kafka). On reconnect the client says "the last one I saw was N", the server sends everything after N, then switches the client to the live stream.
47
You want to hold 100,000 open WebSocket connections on one Linux server. Which resources run out first?
Usually the file descriptor limit first (ulimit -n, often 1024 or 65535), then the memory of each connection (socket buffers, session object, application buffers), then the thread model. The connections themselves use little CPU; the load mostly comes from heartbeats and broadcasts.
48
A WebSocket connection opened with a JWT lives for hours, but the token expires in 15 minutes. How do you handle this?
If the token is checked only at the handshake or CONNECT, an expired or revoked user keeps receiving messages for hours. The usual solution is to store the token's expiry in the session, ask the client for a new token when it expires, and close the connection if none arrives.
49
During a deploy, 40,000 clients drop at once and reconnect to the new instances, and the instances fall over. How do you soften this?
This is a "thundering herd": everyone does the handshake, authentication and initial state load at the same time. The mitigation is backoff with jitter on the client, closing connections gradually on the server (graceful drain), a handshake rate limit, and making the initial load cheaper.
50
The number of open WebSocket sessions on the server is far higher than the number of users and keeps growing. What could be going on?
Probably half-open connections: the client vanished from the network (a phone entered a tunnel, Wi-Fi changed), but no FIN arrived over TCP, and the server doesn't know because it isn't writing. Or the code doesn't remove sessions from the registry when they close. The fix is a server-side heartbeat/idle timeout and checking the cleanup in afterConnectionClosed.
51
What is the Sec-WebSocket-Protocol header for, and how does a Spring STOMP endpoint negotiate the subprotocol?
The client sends a list of subprotocols it supports in the handshake, and the server picks one and returns it in the response. A Spring STOMP endpoint knows v10.stomp, v11.stomp and v12.stomp and picks the best match for what the client asked for.
52
How does fragmentation (one message split into several frames) work in WebSocket, and how does a Spring handler receive the pieces?
The first frame of a message arrives with a text or binary opcode, the following ones with continuation (0x0), and the last one has the FIN bit set. By default Spring assembles the whole message; if supportsPartialMessages() returns true, the handler receives the pieces and checks isLast().
53
A Spring `WebSocketHandler` bean is a single instance for all connections. Where do you keep state that belongs to one connection (for example the room the user picked)?
The handler is a singleton, so its fields are shared by every session, and one user's state overwrites another's. I keep state in session attributes, in a ConcurrentHashMap keyed by sessionId, or give each connection its own handler with PerConnectionWebSocketHandler.
54
The SSE endpoint works in real time locally, but behind Nginx the events arrive late, several at once. What is the cause?
Almost always proxy buffering: by default Nginx collects the upstream response in a buffer and passes it on in chunks. The fix is proxy_buffering off in the SSE location, or returning the X-Accel-Buffering: no header from the app; also check compression.
55
The server computes and sends a price every second for every quote topic, even if nobody is subscribed to it. How do you do work only for topics that have subscribers?
You have to track subscriptions: either query SimpUserRegistry.findSubscriptions(), or listen to SessionSubscribeEvent/SessionUnsubscribeEvent and SessionDisconnectEvent and keep a counter per destination. When the counter drops to zero, the producer stops.
56
Which arguments can a `@MessageMapping("/room.{id}.send")` method take, and how do you validate the incoming payload?
The payload (with or without @Payload), @DestinationVariable, @Header/@Headers, Principal, SimpMessageHeaderAccessor and the Message itself. For validation you put @Valid or @Validated on the payload, and the error arrives as a MethodArgumentNotValidException in your @MessageExceptionHandler.
57
`@PreAuthorize` in a service called from a `@MessageMapping` method fails with "An Authentication object was not found", yet the `Principal` is there. Why?
The Principal is bound to the STOMP session, but SecurityContextHolder isn't populated automatically on the clientInboundChannel thread. When @EnableWebSocketSecurity is on, Spring Security's channel interceptor sets the context for each message and method security starts to work.
58
The interceptor below validates a JWT on STOMP CONNECT. What is wrong with it, and how do you fix it?
The interceptor looks for the token on every frame and rejects the frames after CONNECT because they have no header. Also, although it writes the user to the accessor, the message isn't rebuilt with the modified accessor.
59
You need to send a private message to a user who isn't logged in (anonymous), for example because their cart was updated. There's no Principal and convertAndSendToUser doesn't work. What do you do?
During the handshake you assign a Principal to every anonymous connection yourself: extend DefaultHandshakeHandler, override determineUser, and return a Principal with a random ID or one taken from a cookie. After that the /user/queue/... mechanism works as usual.
60
How do you test an SSE endpoint automatically when its response never ends?
I start the app with RANDOM_PORT, send a text/event-stream request with WebTestClient, take the response as a Flux, and in StepVerifier cancel the subscription once the expected events arrive. A timeout is a must, otherwise the test hangs.
61
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.
62
When is it worth moving WebSocket messages from JSON to a binary format like Protobuf or MessagePack?
When messages are very numerous and small (quotes, telemetry, game state) and the traffic and the CPU spent on serialization become noticeable. For an ordinary chat or notifications, JSON is more convenient: it's readable in DevTools, debugging is cheap, and permessage-deflate narrows the gap a lot.
63
Can WebSocket run over HTTP/2? What does RFC 8441 change, and will you run into it in practice?
Yes. RFC 8441 lets you open a WebSocket inside an HTTP/2 stream via extended CONNECT: no separate TCP connection is needed, and the handshake ends with 200, not 101. But support in servers and proxies is uneven, and in many places the HTTP/1.1 upgrade is still used.
64
The app uses an HTTP session (Spring Session, Redis). A user who works only over WebSocket gets logged out after 30 minutes. Why, and what do you do?
WebSocket messages aren't HTTP requests, so the HTTP session's lastAccessedTime isn't updated and it expires and is deleted. Spring Session's AbstractSessionWebSocketMessageBrokerConfigurer keeps the HTTP session alive on WebSocket messages and closes the WebSocket when the session is deleted.
65
Autoscaling a WebSocket service in Kubernetes with a CPU-based HPA isn't working well. Why, and what do you scale on?
Connections live long: only new connections go to a new pod, old ones stay on the old pods, and scale-down cuts connections and causes a reconnect wave. CPU also correlates poorly with the number of connections. Scale on a custom metric like open connections per pod, with slow scale-down.
66
When does the permessage-deflate extension speed up WebSocket traffic, and when does it hurt?
On large, repetitive JSON messages it cuts traffic several times over. But the compression context takes memory for every connection and burns CPU, so it can hurt in systems with many connections and small messages.
67
What is wrong in the WebFlux WebSocketHandler below? The client receives messages, but what it sends doesn't appear in the server log.
The subscribe() on the receive() stream is done separately, and handle returns only the send Mono. The framework waits only for the returned Mono to complete; both streams must be combined into a single Mono.
68
What is `@SubscribeMapping`, and how does it differ from a plain `@MessageMapping` and from a broker subscription?
@SubscribeMapping runs once when a client SUBSCRIBEs to a /app/... address, and sends the returned value straight to that session, bypassing the broker. It's handy for request-reply like "I subscribed, give me the initial state", while later updates still come through /topic.
69
How do you get the client's IP address, User-Agent or a handshake query parameter inside a WebSocket or STOMP handler?
These exist only during the handshake (the HTTP request), so a HandshakeInterceptor reads them and writes them to the session attributes. Afterward you get them with session.getAttributes() in a raw handler, or SimpMessageHeaderAccessor.getSessionAttributes() in STOMP.
70
How do you use Spring Security to stop a user from SUBSCRIBEing to a STOMP topic they aren't allowed to?
In Spring Security 6 you enable @EnableWebSocketSecurity and write rules by destination and message type in an AuthorizationManager<Message<?>> bean. For dynamic checks (for example, is the user a room member) you write your own AuthorizationManager.
71
A real-time dashboard sends the full state of 2000 rows to every client every second, and egress traffic has jumped. How do you reduce it?
Instead of the full state, a snapshot + delta model: one snapshot on connect, then only the changed fields with a version. On top of that: conflation, the client subscribing only to the part it is looking at, a compact format and compression. A client that notices a version gap asks for the snapshot again.
72
Order status is currently fetched by polling every 5 seconds. How do you migrate it to WebSocket safely, step by step?
I add WebSocket alongside polling without turning it off: first the push only gives an "updated" signal and the client fetches the data from the same REST endpoint. I raise the share gradually with a feature flag, stretch the polling interval for clients connected over WebSocket, and once I'm confident, polling stays only as a fallback.
73
You need request/response (RPC) style operations over WebSocket, for example "add to cart" and a reply. How do you design the protocol?
The client gives each request a correlation ID, the server returns the response with that ID, and the client keeps pending requests in a map with a timeout. On top of that you need an error format, an idempotency key (for resending after a drop) and an envelope that tells requests apart from events.
74
A user was removed from a group chat, but messages from that group keep arriving in their open tab. How do you cancel an active subscription?
Subscription permission is checked only at SUBSCRIBE time; after that the broker delivers messages without asking. Reliable solutions: when membership changes, close the user's sessions and force a resubscribe, or build the room not as a shared topic but with per-user delivery where membership is checked at publish time.
75
A user opens the app in 10 tabs, and each tab opens its own WebSocket connection. How do you move to one connection per browser, and is it worth it?
A single "leader" tab or a SharedWorker holds the connection, and the other tabs receive messages through a BroadcastChannel or the worker port. This cuts server connections several times over, but leader switching, tab closing and browser support add complexity.
76
All traffic goes through an API gateway (for example Spring Cloud Gateway). What do you watch for when routing WebSocket through the same gateway?
The gateway holds two connections per client (client side and backend side), so its memory, file descriptors and idle timeouts must be sized for the number of connections. Auth happens only at the handshake, and a gateway deploy cuts every WebSocket.
77
For a chat, order status notifications and a real-time analytics dashboard, which of WebSocket, SSE and long polling would you choose, and why?
WebSocket for chat, which needs fast two-way exchange. SSE is simpler for notifications and dashboards where data comes only from the server, and it fits the HTTP infrastructure well. Long polling only in environments where the others don't work.
78
What do you monitor in a WebSocket-based service, and where do you get those metrics in Spring?
The number of open connections, connect/disconnect rate and reasons, message counts, thread pool queues, send latency and slow clients. Spring has WebSocketMessageBrokerStats, and you add the rest yourself with Micrometer.
79
You want to release a new version of the WebSocket server as a canary. How does that differ from a canary of an HTTP service?
Splitting traffic by percentage affects only new connections, while old ones stay on the old version for hours. So the canary fills up slowly, and a rollback means cutting connections. The protocol has to work in both directions, and metrics have to be split by version.
80
The client must confirm that every event sent to it was delivered. How do you build an ack mechanism on top of STOMP?
STOMP has an ack:client-individual mode and ACK/NACK frames, but Spring's simple broker doesn't support them. So in practice you build your own ack at the application level: an ID on every message, the client confirms, and unconfirmed ones are resent.
81
Design a notification platform for 5 million concurrent connections. What are the main layers?
A thin gateway layer that holds the connections is separated from business logic, with a message bus and a routing table ("which gateway is this user on") between them. State lives not in the gateway but in the storage layer.
82
Explain the trade-offs between moving WebSocket connections into a separate "edge" layer (such as Centrifugo or Pushpin) and holding them in the Spring app itself.
A separate edge layer makes backends stateless, decouples deploys from connections, and gives many teams one platform. The cost is a new component, coupling to its protocol and limits, and one more hop when debugging.
83
How do you design "user is online" (presence) in a system that runs in several regions?
Presence is a fast-changing, approximate state: each region tracks its own connections locally and sends condensed, delayed updates to the other regions. Don't aim for strong consistency; rely on TTL and heart-beat.
84
A user is connected to a gateway in Frankfurt, and the event they care about appeared in a service in Singapore. How do you build routing in a multi-region real-time system?
Each region has its own gateways and routing table, and the event is routed to the user's "home" region or to the region they're currently connected to. Global routing is done either by sending to all regions, or through a light global index that stores the user's location.
85
You want to use Kafka to deliver real-time events to clients. Can you make a separate topic for each user, and if not, how do you build it?
A topic or partition per user is unfit for Kafka: it breaks under metadata and the number of open files. The right way is a small number of topics, partitioning by userId, and splitting out to the user in the gateway or delivery layer.
86
How do you guarantee message ordering and idempotency in a multi-device chat system?
Ordering isn't global; it's needed within each conversation: the server assigns a single sequence number per conversation, and that number is the source of truth. Idempotency is handled by the client-generated clientMsgId and a unique constraint.
87
For a channel or group chat with 200,000 members, which do you choose: fan-out on write or fan-out on read?
In small groups, fan-out on write (writing to each member's inbox) is simple and reads are fast. In large channels the write cost explodes, so for those the message is stored once and members get it at read time. In practice a hybrid is used.
88
How do you evolve and version a WebSocket-based API when it has to work with web and old mobile app versions?
Mobile clients can't be force-updated, so message formats only grow in a backward-compatible way, the protocol version is negotiated in the handshake, and there is an explicit shutdown plan for old versions.
89
How do you plan capacity and organize load testing for a real-time platform? How does it differ from HTTP load testing?
The main measures aren't RPS but concurrent connections, connection setup rate, and broadcast fan-out. The test must hold connections for a long time, simulate a reconnect storm, and measure latency on the client side.
90
During a football final, one score update has to reach 3 million viewers within 1 to 2 seconds. How do you build such a global broadcast?
I take the broadcast onto a separate path from per-user delivery: the event is serialized once, tree-shaped fan-out sends one copy to each gateway, and the gateway distributes it locally to its own subscribers. On top of that: conflation, pre-scaling, and routing the follow-up "load the full state" requests to a CDN cache.
91
For a new real-time gateway, would you choose the plain blocking model with Java 21 virtual threads, or the reactive WebFlux/Netty model?
For a gateway where connections are mostly idle and every message involves blocking I/O, virtual threads simplify the code. When you need a huge number of connections, strict backpressure and stream operators, the Netty/reactive model is still stronger.
92
For a new platform you have to choose between WebSocket, SSE over HTTP/2 and WebTransport (HTTP/3). What criteria do you use to evaluate them?
Today the reliable choices are WebSocket (two-way) or SSE over HTTP/2 (one-way). WebTransport offers streams without head-of-line blocking and datagrams, but browser and server support isn't complete yet.
93
You're building a Google Docs-style collaborative editing feature. Which of OT and CRDT do you choose to resolve conflicts, and what does the transport look like?
OT relies on a central server to order operations and is well studied for text, but it's hard to implement correctly. CRDT merges without a center and supports offline mode well, but it has a metadata and memory cost. The transport is WebSocket and an operation log in both cases.
94
How do you protect a public WebSocket endpoint from abuse and DDoS?
Protection works at several levels: L3/L4 and the edge (connection count, per-IP rate), the handshake (auth, origin, connection quota), and inside the connection, limits on message rate, size and number of subscriptions. For those who exceed them, an explicit policy: slow down, reject or disconnect.
95
Eight teams in the company want real-time features. How do you provide real-time as a shared platform service?
The platform team takes on connections, auth, routing and delivery, and gives the teams a simple contract: a "send an event to this channel/user" API. For multi-tenancy you need namespaces, quotas and separate metrics.
96
How do you trace an event from a backend service through Kafka, the delivery service and the gateway until it reaches the browser?
You pass the trace context (W3C traceparent) in message headers at every hop, and create OpenTelemetry spans in Kafka, delivery and the gateway. The last step is the client's ack, so end-to-end latency and the places where messages are lost become visible.
97
How do you compare RabbitMQ, Redis Pub/Sub, Kafka and NATS when choosing a message broker for real-time push?
Redis Pub/Sub and NATS core are fast but "fire-and-forget": if there's no subscriber, the message is lost. Kafka gives storage and replay, but it doesn't suit latency-sensitive paths or many small channels. RabbitMQ supports routing and STOMP, but gets heavy as the number of connections and queues grows.
98
For a mobile app, should real-time updates go over a persistent WebSocket, or be combined with push notifications (FCM/APNs)?
The mobile OS cuts a background app's connections quickly, so WebSocket works only while the app is open. You need a hybrid model: FCM/APNs for delivery in the background, WebSocket while open, and both relying on one inbox and seq.
99
In prod, the connection between the STOMP broker relay and RabbitMQ is lost. What does the Spring app do, what do users see, and how do you prepare the system for this?
The Spring "system" connection tries to reconnect, BrokerAvailabilityEvent is published, and while the broker is unavailable client frames are rejected; clients may get an ERROR and be disconnected. Preparation: a broker cluster, a degraded mode, and limiting the blast radius when one component goes down.
100
In a B2B SaaS, several customer companies share one real-time infrastructure. How do you ensure isolation and security between tenants?
The tenant identifier is taken from the token and added on the server as a mandatory prefix of every channel name; the client can't set it itself. On top of that you need per-tenant quotas, audit, and a key/rotation policy.
Sign up — studied questions get marked and your progress is saved.