REST API
WebSockets
Spring Boot
Java Development
Software Architecture

REST API with websocket using Spring boot

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

REST and WebSocket are not competing replacements in a Spring Boot application. They solve different communication problems. REST is excellent for request-response operations such as loading resources or submitting commands. WebSocket is useful when the server needs to push updates to connected clients in real time. Many Spring Boot systems use both at once.

Use REST for Resource Operations

A normal REST controller is still the right tool for:

  • loading initial page data
  • creating or updating resources
  • retrieving historical records
  • authenticated CRUD-style operations

Example:

java
1import org.springframework.web.bind.annotation.GetMapping;
2import org.springframework.web.bind.annotation.PathVariable;
3import org.springframework.web.bind.annotation.RestController;
4
5@RestController
6public class OrderController {
7
8    @GetMapping("/api/orders/{id}")
9    public OrderDto getOrder(@PathVariable Long id) {
10        return new OrderDto(id, "PROCESSING");
11    }
12}
13
14record OrderDto(Long id, String status) {}

This is simple, cacheable in the right scenarios, and easy to reason about.

Use WebSocket for Server Push

If the client needs live updates, polling a REST endpoint repeatedly is often wasteful. That is where WebSocket helps.

Spring Boot commonly uses STOMP over WebSocket for app-level messaging:

java
1import org.springframework.context.annotation.Configuration;
2import org.springframework.messaging.simp.config.MessageBrokerRegistry;
3import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
4import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
5import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
6
7@Configuration
8@EnableWebSocketMessageBroker
9public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
10
11    @Override
12    public void configureMessageBroker(MessageBrokerRegistry config) {
13        config.enableSimpleBroker("/topic");
14        config.setApplicationDestinationPrefixes("/app");
15    }
16
17    @Override
18    public void registerStompEndpoints(StompEndpointRegistry registry) {
19        registry.addEndpoint("/ws").setAllowedOriginPatterns("*");
20    }
21}

Now clients can connect to /ws and subscribe to topics.

Sending Updates to Connected Clients

Spring can publish events to subscribed clients using SimpMessagingTemplate:

java
1import org.springframework.messaging.simp.SimpMessagingTemplate;
2import org.springframework.stereotype.Service;
3
4@Service
5public class OrderNotificationService {
6    private final SimpMessagingTemplate messagingTemplate;
7
8    public OrderNotificationService(SimpMessagingTemplate messagingTemplate) {
9        this.messagingTemplate = messagingTemplate;
10    }
11
12    public void publishStatus(Long orderId, String status) {
13        messagingTemplate.convertAndSend(
14            "/topic/orders/" + orderId,
15            new OrderDto(orderId, status)
16        );
17    }
18}

A browser or mobile client that subscribes to /topic/orders/42 can now receive live status changes without polling.

A Good Combined Design

A common and clean pattern is:

  1. client fetches initial state through REST
  2. client opens a WebSocket connection
  3. server pushes incremental changes over WebSocket

For example:

  • REST loads the current order
  • WebSocket delivers later status updates

This keeps each protocol doing what it is good at.

That is usually better than trying to force WebSocket to replace every ordinary API call.

Do Not Turn WebSocket into CRUD by Default

WebSocket is stateful and connection-oriented. REST is naturally aligned with resource operations, retries, and stateless infrastructure.

So while you can send commands over WebSocket, ask whether the command is really better expressed as:

  • 'POST /api/orders'
  • 'PUT /api/orders/{id}'

and then use WebSocket only for follow-up events.

This separation often makes the system easier to secure, document, and test.

Security Still Matters on Both Sides

If you use both REST and WebSocket, secure both. That usually means:

  • authentication on HTTP endpoints
  • authenticated WebSocket handshake
  • authorization for subscriptions and message destinations

A system is not secure just because its REST endpoints are locked down. A permissive subscription endpoint can leak live data just as easily.

A Minimal Client Example

Using a STOMP JavaScript client, the browser flow often looks like:

javascript
const socket = new WebSocket("ws://localhost:8080/ws");

In practice, most Spring STOMP clients use a STOMP wrapper rather than raw WebSocket frames, but the underlying idea is the same: open one persistent connection and receive pushed messages as events happen.

The important architectural point is that this complements REST. It does not remove the need for well-designed HTTP endpoints.

Common Pitfalls

The biggest mistake is trying to replace every REST endpoint with WebSocket. That usually makes simple resource operations harder to debug, cache, and document.

Another issue is using WebSocket when the product does not actually need server push. If updates are infrequent, ordinary REST polling may be simpler and entirely sufficient.

Developers also often forget authorization on subscriptions and destinations, focusing only on the initial handshake.

Finally, do not overload WebSocket with the initial full-state fetch if REST already models that cleanly. Use REST for baseline state and WebSocket for live changes.

Summary

  • REST and WebSocket solve different communication problems and often belong together in one Spring Boot app.
  • Use REST for ordinary request-response resource operations.
  • Use WebSocket when the server needs to push real-time updates to clients.
  • A common pattern is REST for initial state and WebSocket for subsequent live events.
  • Secure both the HTTP endpoints and the WebSocket messaging layer.

Course illustration
Course illustration

All Rights Reserved.