BT

WebSockets versus REST?

by Mark Little on Feb 26, 2012 |

For the past few years WebSockets has been gaining in popularity and availability. At the end of last year it moved one step closer to a standard by becoming a W3C Candidate Recommendation. Oracle and others have also recently submitted a request to start a standardisation effort around WebSockets (JSR 356) in the next version of Java Enterprise Edition. All of the major browsers, such as Chrome, Firefox, Safari and IE, support one of the WebSockets revisions and will ultimately adopt whatever the standard eventually becomes. In a relatively short period of time, WebSockets has almost become an integral part of the Web. However, there remains a segment of developers who are uncertain as to how or whether WebSockets fits into the architectural style of the Web: REST. Some, such as Nathan Evans, go so far as to suggest that WebSockets could overshadow REST:

After reading up about the standard in detail and absorbing the various online discussion around it, it is becoming increasingly clear to me that this standard is going to steal a large chunk of mind share from RESTful web services. What I mean is that there will come a stage in product development where somebody will have to ask the question:

"Right guys, shall we use WebSockets or REST for this project?"

I expect that WebSockets will, within a year or two, begin stunting the growth of RESTful web services – at least as we know them today.

In his article Nathan believes that based on his experiences of using REST, it is not the "silver bullet" that some other people portray it as, although he admits that WebSockets is also not perfect. He then outlines a number of reasons why WebSockets is a threat to REST, including "sub-par" REST frameworks reliance on text-based protocols. Some of the important benefits that WebSockets offers over REST include bi-directional interactions:

The true bi-directional capability offered by WebSockets is a first for any HTTP-borne protocol. It is something that neither SOAP nor REST have. And which Comet/push/long-polling can only emulate, inefficiently. The bi-directional capability is inherently so good that you could tunnel a real-time TCP protocol such as Remote Desktop or VNC over a WebSocket, if you wanted.

Nathan believes that the benefits of WebSockets outweigh those of REST (HTTP) and that developers will migrate towards WebSockets in preference to it.

REST will probably remain the default choice for projects that need highly visible and cross-platform interoperable web services. Projects without those requirements will probably opt for WebSockets instead and either run JSON over it, or use a bespoke wire protocol. [...] Even though they are competing, the good thing is that REST and WebSockets can actually co-exist with one another. In fact, because they are both built upon HTTP fundamentals they will actually complement each other.

However, Nathan isn't the only one to raise the question of "WebSockets or/versus REST". For instance, Shay Bannon wondered in 2010 whether it is even possible to use the principles of REST with WebSockets:

First and foremost, how do you represent a URI? Second, how do you represent the HTTP methods (GET, PUT, POST, …)? And last, how do you represent HTTP uri parameters and headers? It seems like maybe a solution for this is to built some sort of schema into the content that goes into that text string. Something like a JSON string that has a “uri” field, and “params” and so on. But thats annoying, since with HTTP, you can create very simple gateways that simply use the headers or parameters without needing to parse the body…

He wonders why WebSockets does not have notion of URI or header, and as a result whether there is a need for a REST-over-WebSockets specification before people reinvent REST and end up doing so "not in a uniform manner"? At the time he received a mixed response to this article. For instance one respondant, who mentioned he worked for a WebSockets company, so perhaps not too objective, stated:

REST and WebSocket communication seems to be two different types of distributed computing plumbing. REST is the old-school, sit on top of HTTP, synchronous style of web rpc. WebSocket is the newer, sit along side HTTP, usually asynchronous style of web communication. Imho, in the long term, WebSocket will dramatically reduce the need for REST for WAN computing. With WebSocket, all the protocols we've known and loved for the past few decades can now be extended over the web without the clumsy and performance-sucking mapping to HTTP.

 And another:

My take is REST involves the conventional request/response paradigm. In contrast sockets cater for the comet/long polling scenario where the line of communication stays open for several communication cycles. Also, the initial handshake to WS still occurs from HTTP, so in reality they are not mutually exclusive. I also thought the whole point of the WS protocol was to get rid of the cruft in the HTTP Headers as it becomes redundant and just adds to the payload size.

However, while agreeing that REST and WebSockets can and should co-exist, several commenters disagreed with the notion of a REST-over-WebSockets specification at all, with one adding:

if you consider REST in the Fielding sense, with a web of addressable objects (or resources), then that doesn't really work in a duplex comms format. You don't expect the resources to initiate the conversation. WebSockets will transform the web (if they take off), but not as a protocol for REST-style communications.

 And another giving a more detailed point of view:

WebSockets are like a conversation between two people with ADD. It's full duplex, so both sides can talk at the same time, and both sides have to keep their listening caps on *while* they're talking. REST is stateless and synchronous, dealing only with request->response. You would have to expand the concept of REST to get the benefit of unprompted server->client communication. I could see there being a library that implements REST in WebSockets, but it would only be useful for applications that already have a RESTful API and want to get the benefit of reduced overhead that a single connection would afford without refactoring their code.

Then there are some in the REST community, such as Jim Webber, who believe that WebSockets are not right for the Web:

Jim Webber tweet

With WebSockets almost at the point of becoming a standard, as well as being supported and used in browsers, mobile and in the cloud, it is interesting to wonder how much of an impact they will have on developers who are currently using REST and HTTP, or do they address a different developer segment? Worse still, are we at risk as some believe, of "breaking the Web"?

Hello stranger!

You need to Register an InfoQ account or to post comments. But there's so much more behind being registered.

Get the most out of the InfoQ experience.

Tell us what you think

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread

WebSockets by Mark Nottingham

... is nothing more than TCP for Web browsers; it's a very low-level protocol. If you need it, you'll use it, but it's not competing with HTTP (I don't say REST because it's apples and oranges).

Re: WebSockets by Peter Moskovits

Agree that HTTP and WebSockets don't compete. We will keep using HTTP what it's good at: document traversal/retrieval. What WebSocket gives us is that finally we can get rid of the workarounds and hacks like Ajax, Reverse Ajax, Comet, and alike that we invented to bring interactivity to the Web. Finally we have the right "tools" designed specifically for full duplex low latency communication in a Web friendly fashion.
With the advancement of HTML5 (canvas, local storage, web workers, ...) and CSS3, full blown applications can be run in the browser. Along with the always-on connectivity, we can build apps very similar to the ones that we used to build in a thick client/server world.
About WebSocket being low-level: agree with one comment: just like in the TCP world developers were not coding at the TCP frame level, but were using higher level business protocols; WebSocket was designed to be the transport layer as well. There are implementations of higher level business protocols, such as XMPP, JMS, AMQP, VNC (RFB) that you can use directly from your browser-based HTML5 apps.

Peter Moskovits - Kaazing Developer Evangelist
blog.kaazing.com

Re: WebSockets by Roopesh Shenoy

Does it work directly on TCP or on HTTP? The request headers seem to have HTTP in them if you refer wikipedia.

Re: WebSockets by Greg Wiley

Does it work directly on TCP or on HTTP? The request headers seem to have HTTP in them if you refer wikipedia.


A WebSocket connection starts live out as an HTTP connection which goes through a protocol upgrade to a WebSocket. When the initial request is made it is made over HTTP with an additional header requesting the upgrade. A WebSocket capable server will respond with HTTP 101 - switching protocol response and a WebSocket handshake will take place. Once the WebSocket is established the HTTP protocol is no longer active and the WebSocket runs directly over the established TCP connection.

WebSocket & REST by Greg Wiley

Initially I don't think it will be a case of WebSocket versus REST but WebSocket and REST. I have seen and even facilitated discussions around how to use REST together with WebSockets. REST is not going to go away overnight with the invention of WebSockets as there has been significant investment in developing the services and APIs. WebSockets can add significant value to those existing infrastructures though by providing a much more efficient mechanism for communicating real-time data, whether it's uni-directional push from server to clients, for example FX currency prices, or push from clients to servers, e.g. seismic sensors, or full-duplex bi-directional real-time data.

Overtime it may be that, as developers get used to WebSockets, those REST services may be retired in favour of implementing the same or newer services over WebSockets using a messaging system that supports request/response, queueing and publish/subscribe.

Re: WebSocket & REST by Ben Ford

There's no reason at all not to use WebSockets with REST.

I use the pattern of loading the initial (json) representation via a normal request and then pushing subsequent state changes over a websocket served from the same URL. All you need to implement this is a stack that enables you to mix both approaches from the same server. I use python/pyramid/eventlet and a small library on top of that called stargate: boothead.github.com/stargate/. I'm sure there are equivalents in most green thread based frameworks.

interesting when combined with cloud computing service end points by William Louth

hopefully in the future we will see more mobility of code and its execution in the context of cloud computing api's...adding in web socket support would be great as a means to send data & signals back up the service supply chain as described here:

www.jinspired.com/site/visions-of-cloud-computi...

HTTP should have allowed two-way communication from the get-go by Faisal Waris

Two-way communcation is definitely needed today (as evidenced by whole bunch of work arounds, e.g., Comet; smartphone 'push notification' infrastructures; AMQP; etc.)

If HTTP had allowed two-way communication, life would have been much easier today.

WebSockets is just a way of negotiating a plain old two-way socket connection using HTTP and then HTTP moves out of the way.

I don't see how WebSockets have any relevance to REST (unless you have a mindset that anything over HTTP is automatically REST).

BTW the only decent two-way, SOA stack that I know works well is Windows Communication Foundation (WCF) with its 'Duplex' binding.

WebSocket vs. Comet by Alessandro Alinone

Nice article. Regarding Nathan's comparison between WebSockets and Comet, I should add that the major difference is in the upstream link. If the Comet solution implements HTTP streaming well (and it's not easy), the downstream link is extremely efficient and reliable. But it's impossible to implement real streaming for the upstream link over HTTP. It can be simulated with advanced mechanisms that reduce latency a lot but, I agree, it is still not streaming. For most real-time Web applications, the downstream link has been much more important than the upstream link (in terms of message throughput), but there is now an increasing ecosystem of collaborative applications and games where the upstream link is important as well. So, a good real-time Web server must now be able to support WebSockets and fall back to HTTP Streaming and HTTP Long Polling dynamically.

I detailed my perspective on this topic a few months ago on Comet Daily: cometdaily.com/2011/07/06/push-technology-comet...

That would revolutionize the way multi-modal services are implemented by Shoaib Ali

WebSockets would revolutionize the way multimodal components are implemented. A protocol that is bi-directional, asynchronous and frame-based is all that you need in a multimodal architecture. To-day if one has to a push a map to users browser while she is talking to the IVR, there is a lot of plumbing and polling needed to make that happen.

Also, I think REST would evolve in different directions and not just fade out in favor of WebSockets. Some patterns of REST usage may become less attractive however other patterns may appear that become more appealing than ever. For example, I can already think in terms of a Transactional-REST whereby I can wrap REST calls in a transaction boundary - between beginTransaction/endTransaction. How about pushing distributed transactions real far - across webservices? Wouldn't it be nice to have T-REST that you can include within your regular distributed transaction scope? I don't think that's easily doable to-day.

Philosophically, the Web would acquire features that would enable it to become a first class Service rather than just a Resource. Exactly how that would affect technological evolution is beyond limits.

different definitions of 'the web' by gordon sim

REST takes 'the web' to be a 'distributed hypermedia system' and defines some valuable constraints for such a system with the accompanying benefits. Common use cases for websockets are driven by the desire to use web browsers as universal clients for more event oriented applications (by providing, as Peter Moskovits put it rather nicely, 'full duplex low latency communication'). As such I believe they address different use cases (as well as being concepts at quite different 'levels').

I believe that any widespread success with websockets will be based on asynchronous, message-oriented application layer protocols layered on top of this (e.g. AMQP, XMPP, STOMP etc). Having every system roll their own protocol would be a retrograde step.

Though there are cases where it seems to me that an asynchronous message oriented approach provides a more natural fit, I think the REST style covers a wider range of applications and I hope people continue to employ it where applicable. I think it is one of the more impressive feats of concrete, detailed analysis of architectural decisions I have seen. I do think that message-oriented systems can achieve many of the same benefits (and some additional ones!), but as yet the accumulated knowledge has not been encapsulated so clearly.

Re: WebSockets by Roopesh Shenoy

Thanks Greg for clarifying that.

Websockets, a disaster? by Bill Burke

From what I understand of Websockets, its bascially used to set up a two-way socket connection and not really an application protocol. What worries me the most is that you've basically rolled back 20 years of protocol consolidation, and we're now back to a free-for-all of everybody's pet protocol. Not so bad if your client and server are a tightly coupled, unreusable UI application. Really bad if you're writing a web service that is supposed to be reusable by unknown heterogenous clients. With Web Sockets, web services are not only going to ahve to negotiate the media type, but also the application protocol. Seems like a huge step backward to me in terms of integration.

Security? by Bill Burke

With an anything-goes socket protocol, isn't this a security nightmare for our operations folks?

God! I shouldn't be commenting on this... by William Martinez

1. WebSockets is FAR from being an architectural style, so no comparison is possible with REST.
2. If WebSockets is a protocol, the question would then be if REST can be implemented using that protocol instead of the widely used HTTP, and what are the consequences.
3. About services on the web, there are more than one implementation out there. The ones thinking that they have REST web services (when they really have HTTP ones) may fear the uprising of WebSocket Web Services, which may be possible, but each have different implementation cons and pros and makes no sense to compare them but to decide for one of them.

WebSockets Vs REST by Naresh Chintalcheru

Really nice article.

WebSockets, publish/subscribe, and REST constraints by Benjamin Carlyle

Web Sockets are primarily used as a means of publish-subscribe between a browser and web server. They are an alternative to comet, long polling, etc and allow a server to push out changes of state to a web page that is currently open. There are other use cases but I think this is clearly the core one.

The 100% RESTful approach to this same problem is polling, possibly polling of a delta resource. The REST alternative would periodically (say, once every few seconds) or on demand (say, when the user moves the mouse) send a request to a resource that either captures the total set of dynamic state for the page, or the list of recent changes. This results in a delay of up to the time that the page waits to send this request, plus the time that it takes to fulfil the request before the update can be displayed. The poll rate is therefore carefully chosen to ensure that it provides an adequate level of responsiveness to the user while not hammering the server too hard with requests.

The Web sockets approach is likely to have the following properties:
1. The server is able to send information to the client so long as the TCP connection is not blocked, so update latency is reduced
2. The server may handle fewer requests, because some of these requests will transformed into updates across the WebSockets TCP connection
3. It is likely that heartbeats will still be required on the TCP connection to ensure from the server side that a dead connection is eventually cleaned up (this heartbeat can be relatively slow) and from the client side that the server is still actively sending updates - otherwise it will need to reset its connection. The client will need to send heartbeats at a rate that is similar to what would have been required in the HTTP polling case, although they could be up to an order of magnitude longer. For example, a 1s poll might only need a 10s heartbeat because while the 1s poll has to ensure low latency in the normal case the 10s heartbeat only needs to ensure acceptable latency in the unusual "my server has failed" case.

Web Sockets break REST constraints as follows, as compared to the polling or polling + delta encoding approach.
Stateless: Web sockets maintain a TCP connection between requests that will cause the application to malfunction if it were to go away. This means that servers using this design will use more memory than stateless servers. It also means that a single server going down can have more impact than it would have had in the stateless approach, although the client may be able to reestablish the connection and continue working in this case so long as sufficient heartbeat messages are exchanged.
Cache: Web sockets cannot benefit from cache, so can't share updates between different clients easily. However, pub/sub can be used to replace the Cache constraint as a data replication strategy. If done right it produces a stateful but otherwise simple model. pub/sub if done right using standard protocols can even be visible to intermediaries and allow them to participate in notification distribution networks.
Uniform Contract: The information sent across web sockets does not comply with uniform contract. Intermediaries do not know what is going on over those connections, and can't do anything to help or hinder that communication. Firewalls cannot make sense of the data to enforce policy decisions and intermediaries cannot be transparently inserted to help in the dissemination of information.
Layered System: Layered System is largely broken because proxies and gateways cannot be transparently inserted. Instead the web socket is going to request a direct connection to the server itself. Again this has potentially negative security and performance impacts.
Code on demand: Code on demand partially replaces uniform contract regarding the content that is sent across a Web Socket. Javascript is downloaded from the server using the real uniform contract, and this logic is then used to determine what to send and interpret what is received over the socket.

My thoughts:
* Pub/sub can be an effective solution where the latency tolerance of an application is very low (such as applications where the end to end latency tolerance is less than a second or two).
* Web sockets for pub/sub only really make sense in relatively low latency-tolerant applications with information that is relevant to only a few clients. As compared to browsers polling at a low rate the websockets solution is hungry on server resources, is unable to use intermediaries to transparently distribute information and introduces new failure modes.
* Web sockets end up needing another protocol to be layered on top of them to be useful. It would be nice / would have been nice it if it were possible to have the web socket at least identify the protocol in use so that if an intermediary happens to understand it then that intermediary can get involved. As it stands the sockets have little inherent potential for protocol evolution - the client javascript and server implementation have to match, there is no inherent means to negotiate protocol.

Re: WebSockets, publish/subscribe, and REST constraints by Bill Burke

a REST alternative to pub-sub does not have to poll every few seconds or so, there's no reason a GET /myresource/feed can't block for a few seconds (or more depending on socket timeouts) and then receive an error response or a 202 Accepted with a Retry-After header. We have media types that support polling like this quite nicely (atom) and REST interface's like HornetQ REST interface if you want something more involved (yet simple to consume still).

Re: Security? by Peter Moskovits

Here are a couple of useful resources discussing WebSocket security - all of them pretty detailed:

o Delivering Security Over Native Full-duplex Web Connections - a free whitepaper from Kaazing's founder & CTO: blog.kaazing.com/2012/02/17/free-websocket-secu...
o HTML5 WebSocket Security is Strong - a generic WebSocket security overview: blog.kaazing.com/2012/02/28/html5-websocket-sec...
o Kaazing WebSocket Gateway Security is Strong - a security post on the Kaazing WebSocket Gateway: may be an interesting read, even if you don't use Kaazing: blog.kaazing.com/2012/02/29/kaazing-websocket-g...

JAMP (JSON messaging over WebSocket) Re: different definitions of 'the web' by Richard Hightower

I agree with this sentiment for the most part. I have been working on: JAMP.

Actually, quietly in the background, but after this post decided to make it more public and put up a github page, etc.

The primary goal of JAMP is to provide structure for a JSON-based messaging over a WebSockets connection. JAMP will support a next generation SOA/REST style communication.

Think of JAMP as SOAP on a strict diet and based on JSON and the interfaces of your programming languages instead of XML and WSDL+XML schema.
JSON Actor Message Protocol defines a bidirectional messaging protocol using JSON as a payload serialization format.

Messages are typed and addressed. Both unidirectional messages and bidirectional queries are supported. JAMP can be sent on messaging and framing protocols like WebSockets, HTTP (REST), AMQP, or STOMP.

JAMP is a very simple and easy to implement serialization protocol, coming from the JSON school of design.

JAMP is the logical next step in REST/SOA evolutionary architectures to fit WebSockets, STOMP and AMQP. It augments STOMP and AMQP by adding a common serialization that is easily available and marshalable to many different languages. It aguments REST by giving you many more verbs, and a async messaging architecture to build your services on top of.

It should be possible for a seasoned developers to write their own JAMP bindings for their programming language of choice in a couple of days or even less if they use an existing JSON parser.

One of the goals of this project is to write reference implementations in JavaScript, Java and Python with the hope that others will write Ruby, Objective C, C# et al.

Some links of note:
JAMP Visual Tutorial.


Language binding and routing



IETF JAMP Draft

It is not restful by jack jia

When it is not restful all the bad things will not rest. :-) But there is trade off and WebSockets will be really good for some types of applications.

Is Websockets just a way to workaround a firewall? by Fernando Lozano

It looks to me Websockets is just a way to allow a generic application protocol between an application and a server... just like old plain TCP sockets did. Most of the time you cannot do this on the web because either the server firewall won't allow connections to ports other than 80 and 443, or the client firewall won't. So Websockets become kinda of generic proxy/tunnel and we start reinventing the weel, doing again all we already have for TCP using websockets. :-( The web server becomes a proxy server, and you'll need a whole new generation of firewalls who can inspect the websockets traffic, while we already have this for regular TCP traffic.

Why don't provide a generic TCP sockets API for Browsers / Javascript? Why don't use already tried-and-true generic proxy protocols like Socks? All this websockets effort just so we don't need to configure our firewalls to allow incoming/outgoing connections to ports other than 80 and 443?

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread

22 Discuss

Educational Content

General Feedback
Bugs
Advertising
Editorial
InfoQ.com and all content copyright © 2006-2013 C4Media Inc. InfoQ.com hosted at Contegix, the best ISP we've ever worked with.
Privacy policy
BT