eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Overview

In this tutorial, we’ll go through the basics of client-server communication and explore this through two popular options available today. We’ll see how WebSocket, which is a new entrant, fares against the more popular choice of RESTful HTTP.

2. Basics of Network Communication

Before we deep-dive into the details of different options and their merits and demerits, let’s quickly refresh the landscape of network communication. This will help to put things in perspective and understand this better.

Network communications can be best understood in terms of the Open Systems Interconnection (OSI) model.

OSI model partitions the communication system into seven layers of abstraction:

OCI-Model

At the top of this model is the Application layer which is of our interest in this tutorial. However, we’ll discuss some aspects in the top four layers as we go along comparing WebSocket and RESTful HTTP.

The application layer is closest to the end user and is responsible for interfacing with the applications participating in the communication. There are several popular protocols which are used in this layer like FTP, SMTP, SNMP, HTTP, and WebSocket.

3. Describing WebSocket and RESTful HTTP

While communication can happen between any number of systems, we are particularly interested in client-server communication. More specifically, we’ll focus on communication between a web browser and a web server. This is the frame we’ll use to compare WebSocket with RESTful HTTP.

But before we proceed any further, why not quickly understand what they are!

3.1. WebSockets

As the formal definition goes, WebSocket is a communication protocol which features bi-directional, full-duplex communication over a persistent TCP connection. Now, we’ll understand each part of this statement in detail as we go along.

 

WebSocket was standardized as a communication protocol by IETF as RFC 6455 in 2011. Most modern web browsers today support the WebSocket protocol.

3.2. RESTful HTTP

While we all are aware of HTTP because of its ubiquitous presence on the internet, it is also an application layer communication protocol. HTTP is a request-response based protocol, again we’ll understand this better later in the tutorial.

REST (Representational State Transfer) is an architectural style which puts a set of constraints on HTTP to create web services.

4. WebSocket Subprotocol

While WebSocket defines a protocol for bi-directional communication between client and server, it does not put any condition on the message to be exchanged. This is left open for parties in the communication to agree as part of subprotocol negotiation.

It’s not convenient to develop a subprotocol for non-trivial applications. Fortunately, there are many popular subprotocols like STOMP available for use. STOMP stands for Simple Text Oriented Messaging Protocol and works over WebSocket. Spring Boot has first class support for STOMP, which we’ll make use of in our tutorial.

5. Quick Setup in Spring Boot

There’s nothing better than seeing a working example. So, we’ll build simple use-cases in both WebSocket and RESTful HTTP to explore them further and then compare them. Let’s create a simple server and client component for both.

We’ll create a simple client using JavaScript which will send a name. And, we’ll create a server using Java which will respond with a greeting.

5.1. WebSocket

To use WebSocket in Spring Boot, we’ll need the appropriate starter:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

We’ll now configure the STOMP endpoints:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketMessageBrokerConfig implements WebSocketMessageBrokerConfigurer {
 
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws");
    }
 
    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.setApplicationDestinationPrefixes("/app");
        config.enableSimpleBroker("/topic");
    }
}

Let’s quickly define a simple WebSocket server which accepts a name and responds with a greeting:

@Controller
public class WebSocketController {
 
    @MessageMapping("/hello")
    @SendTo("/topic/greetings")
    public Greeting greeting(Message message) throws Exception {
        return new Greeting("Hello, " + HtmlUtils.htmlEscape(message.getName()) + "!");
    }
}

Finally, let’s build the client to communicate with this WebSocket server. As we are emphasizing browser-to-server communication, let’s create a client in JavaScript:

var stompClient = null;
function connect() {
    stompClient = Stomp.client('ws://localhost:8080/ws');
    stompClient.connect({}, function (frame) {
        stompClient.subscribe('/topic/greetings', function (response) {
            showGreeting(JSON.parse(response.body).content);
        });
    });
}
function sendName() {
	stompClient.send("/app/hello", {}, JSON.stringify({'name': $("#name").val()}));
}
function showGreeting(message) {
    $("#greetings").append("<tr><td>" + message + "</td></tr>");
}

This completes our working example of a WebSocket server and client. There is an HTML page in the code repository which provides a simple user interface to interact with.

While this just scratches the surface, WebSocket with Spring can be used to build complex chat clients and more.

5.2. RESTful HTTP

We’ll go through a similar set-up for RESTful service now. Our simple web service will accept a GET request with a name and responds with a greeting.

Let’s use Spring Boot’s web starter instead this time:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

Now, we’ll define a REST endpoint leveraging powerful annotation support available in Spring:

@RestController
@RequestMapping(path = "/rest")
public class RestAPIController {
    @GetMapping(path="/{name}", produces = "application/json")
    public String getGreeting(@PathVariable("name") String name)
    {
        return "{\"greeting\" : \"Hello, " + name + "!\"}";
    }
}

Finally, let’s create a client in JavaScript:

var request = new XMLHttpRequest()
function sendName() {
    request.open('GET', 'http://localhost:8080/rest/'+$("#name").val(), true)
    request.onload = function () {
    	var data = JSON.parse(this.response)
    	showGreeting(data.greeting)
    }
    request.send()
}

function showGreeting(message) {
    $("#greetings").append("<tr><td>" + message + "</td></tr>");
}

That’s pretty much it! Again, there’s an HTML page in code repository to work with a user interface.

Although profound in its simplicity, defining production grade REST API can be much more extensive task!

6. Comparison of WebSocket and RESTful HTTP

Having created minimal, but working, examples of WebSocket and RESTful HTTP, we’re now ready to understand how do they fare against each other. We’ll examine this against several criteria in the next sub-sections.

It is important to note that while we can directly compare HTTP and WebSocket as they are both application layer protocols, it’s not natural to compare REST against WebSocket. As we saw earlier REST is an architectural style which leverages HTTP for communication.

Hence our comparison to WebSocket will mostly be regarding the capabilities, or lack thereof, in HTTP.

6.1. URL Scheme

A URL defines the unique location of a web resource and mechanism to retrieve it. In a client-server communication, more often than not we’re looking to get static or dynamic resources through their associated URL.

We’re all familiar with the HTTP URL scheme:

http://localhost:8080/rest

WebSocket URL scheme is not much different either:

ws://localhost:8080/ws

At the outset, the only difference seems to be the characters before the colon, but it abstracts a lot which happens under the hood. Let’s explore further.

6.2. Handshake

Handshake refers to the automatic way of negotiating communication protocol between communicating parties. HTTP is a stateless protocol and works in a request-response mechanism. On every HTTP request, a TCP connection is established with the server over the socket.

The client then waits until the server responds with the resource or an error. The next request from the client repeats everything as if the previous request never happened:

HTTP Connection

WebSocket works very differently compared to HTTP and starts with a handshake before actual communication.

Let’s see what comprise a WebSocket handshake:

WebSocket Connection

In case of WebSocket, the client initiates a Protocol Handshake request in HTTP and then waits until the server responds accepting an upgrade to WebSocket from HTTP.

Of course, since Protocol Handshake happens over HTTP, it follows the sequence from the previous diagram. But once the connection is established, from there on client and server switches over to WebSocket for further communication.

6.3. Connection

As we saw in the previous subsection, one stark difference between WebSocket and HTTP is that WebSocket works on a persistent TCP connection while HTTP creates a new TCP connection for every request.

Now obviously creating new TCP connection for every request is not very performant and HTTP has not been unaware of this. In fact, as part of HTTP/1.1, persistent connections were introduced to alleviate this shortcoming of HTTP.

Nevertheless, WebSocket has been designed from the ground up to work with persistent TCP connections.

6.4. Communication

The benefit of WebSocket over HTTP is a specific scenario that arises from the fact that the client can server can communicate in ways which were not possible with good old HTTP.

For instance, in HTTP, usually the client sends that request, and then the server responds with requested data. There is no generic way for the server to communicate with the client on its own. Of course, patterns and solutions have been devised to circumvent this like Server-Sent Events (SSE), but these were not completely natural.

With WebSocket, working over persistent TCP communication, it’s possible for server and client both to send data independent of each other, and in fact, to many communicating parties! This is referred to as bi-directional communication.

Another interesting feature of WebSocket communication is that it’s full-duplex. Now while this term may sound esoteric; it simply means that both server and client can send data simultaneously. Compare this with what happens in HTTP where the server has to wait until it receives the request in full before it can respond with data.

While the benefit of bi-directional and full-duplex communication may not be apparent immediately. we’ll see some of the use-cases where they unlock some real power.

6.5. Security

Last but not least, both HTTP and WebSocket leverage the benefits of TLS for security. While HTTP offers https as part of their URL scheme to use this, WebSocket has wss as part of their URL scheme for the same effect.

So the secured version of URLs from the previous subsection should look like:

https://localhost:443/rest
wss://localhost:443/ws

Securing either a RESTful service or a WebSocket communication is a subject of much depth and can not be covered here. For now, let’s just say that both are adequately supported in this regard.

6.6. Performance

We must understand that WebSocket is a stateful protocol where communication happens over a dedicated TCP connection. On the other hand, HTTP is inherently a stateless protocol. This has an impact on how these will perform with the load but that really depends on the use case.

Since communication over WebSocket happens over a reusable TCP connection, the overhead per message is lower compared to HTTP. Hence it can reach higher throughput per server. But there is a limit to which a single server can scale and that is where WebSocket has issues. It’s not easy to horizontally scale applications with WebSockets.

This is where HTTP shines. With HTTP each new request can potentially land on any server. This implies that to increase overall throughput we can easily add more servers. This should potentially have no impact on the application running with HTTP.

Obviously an application may itself need state and session stickiness which can make it easier said than done.

7. Where Should We Use Them?

Now, we have seen enough of RESTful service over HTTP and simple communication over WebSocket to form our opinion around them. But where should we use what?

It’s important to remember that while WebSocket has emerged out of shortcomings in HTTP, it’s not, in fact, a replacement of HTTP. So they both have their place and their uses. Let’s quickly understand how can we make a decision.

For the bulk of the scenario where occasional communication is required with the server like getting the record of an employee, it’s still sensible to use REST service over HTTP/S. But for newer client-side applications like a stock-price application which requires real-time updates from the server, it’s much convenient to leverage WebSocket.

Generalizing, WebSocket is more suitable for cases where a push-based and real-time communication defines the requirement more appropriately. Additionally, WebSocket works well for scenarios where a message needs to be pushed to multiple clients simultaneously. These are the cases where client and server communication over RESTful services will find it difficult if not prohibitive.

Nevertheless, the use of WebSocket and RESTful services over HTTP needs to be drawn from the requirements. Like there are no silver bullets, we can’t just expect to pick one to solve every problem. Hence, we must use our wisdom coupled with knowledge in designing an efficient communication model.

8. Conclusion

In this tutorial, we reviewed the basics of network communication with an emphasis on application layer protocols HTTP and WebSocket. We saw some quick demonstrations of WebSocket and RESTful API over HTTP in Spring Boot.

And finally, we compared the features of HTTP and WebSocket protocols and briefly discussed when to use each.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – LS – NPI (cat=REST)
announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

eBook Jackson – NPI EA – 3 (cat = Jackson)