WebSocket & GraphQL Dependencies
Learn spring-boot-starter-websocket for real-time bidirectional communication with STOMP, and spring-boot-starter-graphql for building GraphQL APIs.
Introduction
Not every API fits the classic request/response REST model. Sometimes the server needs to push updates the instant they happen (real-time chat, live notifications), and sometimes clients need the flexibility to ask for exactly the fields they want in one round trip (GraphQL). This lesson covers the dependency for each.
spring-boot-starter-websocket
Use case: real-time, bidirectional communication between server and client over a single long-lived connection — chat applications, live dashboards, collaborative editing, or trading price feeds. It supports raw WebSockets as well as STOMP (Simple Text Oriented Messaging Protocol) messaging on top of WebSocket, which adds routing (like `/topic/...` destinations) similar to a message broker.
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId></dependency>@Configuration@EnableWebSocketMessageBrokerpublic class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/ws-chat").withSockJS(); }
@Override public void configureMessageBroker(MessageBrokerRegistry registry) { registry.setApplicationDestinationPrefixes("/app"); registry.enableSimpleBroker("/topic"); }}A STOMP Chat Example
With the broker configured, a controller method annotated with `@MessageMapping` receives messages sent to `/app/chat.send` and broadcasts them to every client subscribed to `/topic/messages`.
@Controllerpublic class ChatController {
@MessageMapping("/chat.send") @SendTo("/topic/messages") public ChatMessage sendMessage(ChatMessage message) { return message; // broadcast to every subscriber }}Click Run to see what this code prints.
spring-boot-starter-graphql
Use case: building a GraphQL API, where clients specify exactly which fields they need in a single query, avoiding the over-fetching or under-fetching that is common with fixed REST endpoints. It builds on GraphQL Java and Spring for GraphQL, wiring up an `/graphql` endpoint automatically.
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-graphql</artifactId></dependency>A GraphQL API is defined by a schema file (by convention placed at `src/main/resources/graphql/schema.graphqls`) describing the available types and queries.
type Query { product(id: ID!): Product}
type Product { id: ID! name: String! price: Int!}A GraphQL Query Example
Each field in the schema is backed by a `@QueryMapping` (or `@SchemaMapping`) method, similar in spirit to a REST controller method but resolved per-field.
@Controllerpublic class ProductGraphQlController {
@QueryMapping public Product product(@Argument Long id) { return new Product(id, "Wireless Mouse", 799); }}Click Run to see what this code prints.
Notice the client only asked for `name` and `price`, and only got those two fields back — even though the `Product` type also has an `id`. This client-driven shape is the core benefit GraphQL offers over a fixed REST response.
Common Mistakes
- Using WebSocket for something that is really just occasional updates — a well-cached REST endpoint may be simpler and sufficient.
- Forgetting to enable SockJS fallback for browsers or proxies that block raw WebSocket connections.
- Writing a GraphQL resolver that triggers a separate database query per field per row (the "N+1" problem) — batch loading (e.g. via DataLoader) is needed at scale.
Best Practices
- Use STOMP destinations (/topic, /queue) rather than raw WebSocket frames once your messaging needs more than a single channel.
- Keep GraphQL schema files under version control and treat schema changes with the same care as a REST API contract.
- Add authentication/authorization checks explicitly in WebSocket and GraphQL handlers — they do not automatically inherit typical HTTP filter-chain security the same way a REST controller does.
Frequently Asked Questions
No, spring-boot-starter-websocket includes a simple in-memory broker sufficient for basic use cases; you can optionally relay to a full external broker for production-scale fan-out.
Not necessarily — many teams run both, using GraphQL where flexible client-driven queries add real value and REST for simpler, more standard endpoints.
Yes, GraphQL subscriptions (a third GraphQL operation type alongside queries and mutations) are commonly implemented over WebSocket for real-time GraphQL updates.
Key Takeaways
- spring-boot-starter-websocket enables real-time, bidirectional communication, often using STOMP for topic-based routing.
- @MessageMapping and @SendTo let a controller method receive and broadcast STOMP messages.
- spring-boot-starter-graphql exposes a /graphql endpoint driven by a schema file and @QueryMapping methods.
- GraphQL lets clients request exactly the fields they need, avoiding REST's over/under-fetching.
Summary
WebSocket and GraphQL solve two different limitations of classic REST: WebSocket removes the need for the client to keep asking, and GraphQL removes the need for the server to guess exactly what shape of data the client wants. Next, the course turns to the dependencies behind data and persistence.