REST Top

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE

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:

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:

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

Let's see what comprise a WebSocket handshake:

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.

As always, the code for the examples is available over on GitHub.

REST bottom

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE
newest oldest most voted
Notify of
Mark Wonsil
Guest
Mark Wonsil

The problem with REST is people don’t understand REST. REST is NOT a protocol. It does NOT depend on http. REST is about state management – period.

Eric Martin
Member
Eric Martin

True, but 95+% of the time, developers are talking about RESTful HTTP.

Kfir
Guest
Kfir

Thank you for very interesting article.
One thing that need to take under consideration when we compare those architectures is the ability of the server to serve many client.
I don’t know the answer, but seems that when you serve ws, the server is much more limited in the number of clients.
Do you have any information about it?

Eric Martin
Member
Eric Martin

Hey Kfir,
Thanks for your observation. We’ll update the article soon to include that.
Cheers.

Marco Ghisellini
Guest

Great article.
I’d add only one note from your already complete analysis: the scalability of both solution.
What about the performance in term of system scalability? I’d say WebSocket is much more “resource consuming” than HTTP Rest; it should be considered when you’re going to make a choice between the two solutions.

Eric Martin
Member
Eric Martin

Hey Marco,
Thanks for your observation. We’ll update the article soon to include that.
Cheers.

Saad Benbouzid
Guest
Saad Benbouzid

You forgot to mention the inconvenient of non-stateless WebSocket for client-server data exchanges, in case of clustered (multiple) servers (that is also : desynchronized and stateless servers as well).

Eric Martin
Member
Eric Martin

Hey Saad,
Thanks for your observation. We’ll update the article soon to include that.
Cheers.

Comments are closed on this article!