Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
WebSockets versus REST? (infoq.com)
94 points by DanielRibeiro on Feb 26, 2012 | hide | past | favorite | 54 comments


I think what lots of people are missing is that Websockets doesn't compete with REST or SOAP, it competes with HTTP. Until now, programs written in Javascript could only use one internet protocol: HTTP. Websockets brings low-level TCP socket programming to Javascript, enabling the use of any TCP-level protocol.

Of course, this happens within a sandbox that involves initiating the connection over HTTP and tunneling the protocol through a server over port 80. But that server can be a proxy that forwards the stream to any TCP service, on any TCP port. We're back to the days when anyone could and did develop their own protocols, and many of those became standards.

I suspect that we're going to see that kind of development again: people will initially create their own protocols to use over Websockets, then they'll recognize the benefit of tunneling existing standard TCP protocols to their Javascript programs (how about an IMAP client written in Javascript?) then finally someone will develop an HTTP client in Javascript.


The bigger picture is that WebSockets increases what's possible via the web. In theory REST isn't tied to HTTP although practically speaking, the two do go hand in hand. The natural REST application is also somewhat different from the natural WebSocket application.


I think it does compete with REST. I want my framework as simple as possible (and real-time as possible, of course), and I know that to reach 100% of the audience plus have a good SEO, I will certainly have to have 2 versions of my website: One low-tech, no-javascript, pure HTML 4. The other, thanks to the first one, can shoot very high. So I will get rid of REST, and have all my data being synchronized via WebSocket. Function calls will be RPC over WebSocket. The much-less-than 1% users without WebSocket or Flash support (which implements a fallback WebSocket client), or with a Flash or WebSocket behind a Proxy that won't let these through, will be defaulted to the low-level website, which has to be there anyway, because dynamic content is very badly indexable by search engines. I think I will be working on a Node.js micro-framework to accomplish this very soon. This of course will have to be backed by a fast in-memory database with pub-sub, like Redis. The other fallback transports for WebSocket, like JSONP or other hacks, aren't in my opinion worth it at all, given the proliferation of Flash and WebSocket-supporting browsers.

Time for a plug too: my https://github.com/ypocat/ws-rpc and https://github.com/ypocat/ws-flash-client extensions for the mean and lean "ws" Node.js WebSocket server. (Reason for creating both of these was very simple - socket.io did not work out for me.)


Yes, ok, you will use WebSockets for your API. But what will it look like to book a ticket on your API? "{'action': 'book', 'from': 'Chicago', 'to': 'Moscow'}"? It's still junk without REST style.

The point of REST is operating with resources as building bricks of your API, and using only four CRUD operations on them (or on their collection). Besides, for testing purposes it is good to still have REST API to test it with curl or some web client in your code.

So what I'd suggest is to continue building REST API, but create a smooth REST2WebSocket layer to make your REST requests through WebSockets. Like "{'method': 'PUT', 'resource': '/api/users/john', 'data': '\{\'name\': \'Paul\'...".


(maybe the examples I provided are not ugly enough to show difference, so I'll try to do that here)

On non-rest API you can get in trouble mixing actions and resources, so you can get things like {'action': 'list_users'}, {'action': 'rename_user'}, {'action': 'user_ban'}, {'action': 'rename_user_and_email'}, {'action': 'list_active_users'}

While on REST API you are at least consistent that user-resource is /users/, that concrete user is /users/<user_id> and that only operations are CRUD on either all users -> /users/ or on concrete user /users/<user_id>. That gives so much more clarity (+ caching reads, + only open transactions on POST/PUT/DELETE).


No, WebSockets doesn't complete with HTTP. It complements HTTP.

SPDY competes with HTTP.


No, SPDY competes with TCP[1].

[1] http://www.chromium.org/spdy/spdy-whitepaper


Unfortunately, there will be no UDP protocols. So we're not quite back to where we were in 1970 yet.


UDP will be coming as a part of the WebRTC effort. The current spec draft and prototypes don't include arbitary data channels, but they are currently being specced on the mailing list.


Excellent. Someone else pointed this out. This is good news.


I think you have missed the mark by such a wide margin that I need to call you on your bullshit.

> I think what lots of people are missing is that Websockets doesn't compete with REST or SOAP, it competes with HTTP.

Websockets of any reference are implentations of HTTP, your lack of knowledge is not a badge of authority.

"Of course, this happens within a sandbox that involves initiating the connection over HTTP and tunneling the protocol through a server over port 80."

I am sure that you have no clue about what your talking about, I will bring this forward with the following statement:

"We're back to the days when anyone could and did develop their own protocols, and many of those became standards."

Your name is not on any IETF bodies or standards, who are you exactly?


Websockets of any reference are implentations of HTTP

As parent said, they only implement HTTP for handshaking. Then you switch to the websocket protocol.

To quote websocket.org:

    The protocol switch from HTTP to WebSocket is referred to as
    a the WebSocket handshake. (...) The browser sends a request
    to the server, indicating that it wants to switch protocols from
    HTTP to WebSocket. (...) At this point the HTTP connection breaks
    down and is replaced by the WebSocket connection over the
    same underlying TCP/IP connection.
The rest of your post is just argument-free personal attacks, therefore I'll refrain from replying to it.


I think you have missed the mark by such a wide margin that I need to call you on your bullshit.

Not a good start :-|


yeah, it's a bad thing when tech beats bullshit :(


He was right. Who are you exactly?


So, in a nutshell, we're seeing a swing back to RPC. I think that's great, bidirectional RPC is much nicer than REST.

REST is great, but a good portion of the time proper rest begins to feel like square peg round hole, that's why we see endless discussions of 'proper' rest.


bidirectional RPC is much nicer than REST.

I don't see why - REST seems extremely elegant to me.

In any case, they solve completely different problems. REST is a set of constraints that ensure your architecture will be scalable, reliable, efficient (by allowing multiple levels of caching), easy to evolve (by being extremely decoupled) and linkable.

WebSockets throw away all that to ensure you can have low latency realtime bidirectional communications.


They don't throw it away, they just don't add the unnecessary cruft and overhead to get their stellar latency and response times.

There will never be an enviable end-user Single Page Application built on a purely REST architecture style since REST/HATEOS promotes the idea of dumb clients driven by a single server view, in a page-by-page mode Netscape 4 would be proud of. This is great if you're building one of the turn-based games of the 90s but the REST of the world has moved - and the talented kids who can cut stellar client side apps aren't doing it with a restricted HATEOS mindset.

So while Google makes arguably the best REST client with Chrome, they're not wasting their time trying to restrict their Single Page Apps around HATEOS constraints. Instead they're investing heavily in trying to move the web forward with technologies that actually improve end-user experience like WebSockets and SPDY - rather than wasting their time chasing REST compliance badges, that's what REST cults do.


They don't throw it away

Of course they do. WebSockets are stateful - immediately less scalable and reliable, since a client is tied to a server during the session -, they can't be cached - much less efficient for images, videos, etc -, are tied to particular implementations instead of standards and aren't linkable.

they just don't add the unnecessary cruft and overhead to get their stellar latency and response times.

REST doesn't have any "cruft". In fact, REST only restricts, it doesn't add anything.

There will never be an enviable end-user Single Page Application built on a purely REST architecture style since REST/HATEOS promotes the idea of dumb clients driven by a single server view, in a page-by-page mode Netscape 4 would be proud of. This is great if you're building one of the turn-based games of the 90s but the REST of the world has moved - and the talented kids who can cut stellar client side apps aren't doing it with a restricted HATEOS mindset.

You're mistaken. Nothing about REST or HATEOAS prevents a web application from serving Javascript that then calls a RESTful API dynamically, using PushState to change the current resource URI locally.

In fact, pushing and running code on the client (code-on-demand) is one of the constraints (albeit optional) of REST, as specified in Fielding's dissertation. Your claim that REST promotes dumb clients is wrong.

So while Google makes arguably the best REST client with Chrome, they're not wasting their time trying to restrict their Single Page Apps around HATEOS constraints. Instead they're investing heavily in trying to move the web forward with technologies that actually improve end-user experience like WebSockets and SPDY

What Google service uses Websockets, exactly?

And there's nothing unRESTful about SPDY. You don't seem to understand what REST means. REST is not HTTP.


You seem to be infected with the mindset that you can only develop scalable and high-performance cached services with REST - you really need to step outside of your comfort zone.

>> Of course they do. WebSockets are stateful - immediately less scalable and reliable, since a client is tied to a server during the session -,

And so does every other persistent TCP service but you don't see Spotify or Skype failing unreliably to handle their own scalability. You don't need a single server to handle every connection, you can load balance TCP servers just like everything else.

>> they can't be cached

Of course they can, web sockets just provide a client/server tunnel - you can cache on the server like any other RPC service. You can also cache in the browser with javascript vars or localStorage.

>> much less efficient for images, videos, etc -, are tied to particular implementations instead of standards and aren't linkable.

This makes no sense - how exactly is it less efficient when you can make the same request/response with less overhead. You can still use HTTP/SPDY for asset retrieval and web sockets for bi-directional data/comms. Trying to force bi-directional comms with HTTP is ladded with in-efficient hacks.

>> You're mistaken. Nothing about REST or HATEOAS prevents a web application from serving Javascript that then calls a RESTful API dynamically, using PushState to change the current resource URI locally. >> In fact, pushing and running code on the client (code-on-demand) is one of the constraints (albeit optional) of REST, as specified in Fielding's dissertation. Your claim that REST promotes dumb clients is wrong.

Alright genius and which popular SPA app downloads an entire page with on-demand scripts inside? Most SPAs combine and minify most their scripts upfront and when they are fetching external .js, they're just fetching CDN-cached .js and not a '.js scripts in a REST-infected HTML page with enhanced scripts' that you seem to suggest.

>> What Google service uses Websockets, exactly?

Gmail. Heard of it?

>> And there's nothing unRESTful about SPDY. You don't seem to understand what REST means. REST is not HTTP.

The protocol themselves don't, but the infectious sheeps who can't ship XML back without being stuffed in some ATOM-like format or their own custom half-assed re-impl of HTML complete with semantic metadata and urls that they want to call 'Resource States' because they like the sound of their own voice.


You seem to be infected with the mindset that you can only develop scalable and high-performance cached services with REST - you really need to step outside of your comfort zone.

Nope. I just understand what makes REST scalable.

And so does every other persistent TCP service but you don't see Spotify or Skype failing unreliably to handle their own scalability. You don't need a single server to handle every connection, you can load balance TCP servers just like everything else.

Skype uses a P2P distributed system, it's a very different system. And yes, I see them fail to connect regularly. I don't have access to Spotify, so I can't comment on it.

Of course they can, web sockets just provide a client/server tunnel - you can cache on the server like any other RPC service. You can also cache in the browser with javascript vars or localStorage.

My university uses a proxy that caches TBs to improve performance and reduce outside traffic. Websockets don't work with it.

This makes no sense - how exactly is it less efficient when you can make the same request/response with less overhead. You can still use HTTP/SPDY for asset retrieval and web sockets for data/comms.

It's less efficient because it can't be cached. It wasn't a new argument, just an explanation of the previous.

Alright genius and which popular SPA app downloads an entire page with on-demand scripts inside? Most SPAs combine and minify most their scripts upfront and when they are fetching external .js, they're just fetching CDN-cached .js and not a '.js scripts in a REST-infected HTML page with enhanced scripts' that you seem to suggest.

Where the fuck have I suggested that? You're making up stuff. Yes, loading a single .js and then calling a REST API (asking for JSON) is a great example of a RESTful website.

By the way, "REST-infected HTML" makes no sense, unless you mean HTML shouldn't have links, because that's the only thing that can be considered RESTful.

Gmail. Heard of it?

Your Gmail must be special, since I'm on a Websockets enabled browser (FF10) and it's clearly using XHR, making dozens of HTTP calls. No Websockets to be seen on the source, anywhere.

The protocol themselves don't, but the infectious sheeps who can't ship XML back without being stuffed in some ATOM-like format or their own custom half-assed re-impl of HTML complete with semantic metadata and urls that they want to call 'Resource States' because they like the sound of their own voice.

You're making stuff up again. REST doesn't mean XML or ATOM, nor have I ever defended that. Your own blog is a perfectly RESTful service.


I don't know about "dumb clients" as it specifically talks about scriptable agents.


Unfortunately, during our circle back to the 1970's we lost UDP, which is essential for real time protocols.


Exactly. Flash sockets are TCP only (proprietary Adobe protocols aside), and it seems WebSockets ended up without any UDP support either.

The overhead of TCP is just ridiculous when you're trying to implement real-time game movements with dead reckoning, etc.


Unity has UDP sockets and yes all good games that require fast real-time action need UDP. Adobe had it partially in their latest Flash Media Server RTMFP protocol but it was very limited.

RUDP or Reliable UDP is the best of both.

Here's some great info on UDP vs TCP and only using one or the other:

UDP vs TCP http://gafferongames.com/networking-for-game-programmers/udp...

Characteristics of UDP Packet Loss: Effect of TCP Traffic http://www.isoc.org/INET97/proceedings/F3/F3_1.HTM


RUDP sounds very weird... why would you use it instead of TCP? At a glance, it looks like the only difference is RUDP doesn't enforce packets being received in-order (being a message-based protocol), while TCP does (being a stream-based protocol).


The great thing about UDP with a reliable layer on top is you can choose if you want an ACK back for any 'critical' data. Otherwise you can just ignore order or whether the endpoint receives it or not. It is a broadcast rather than a hard line essentially.

For instance let's say you have some physics update and for some reason you needed it networked, with many objects, receiving only 70% of those for many different elements may be just fine (discarding any you receive after that are older maybe for this example)...you may not need reliable acknowledgement that they received for most of them if any. But you definitely need to know when an enemy is killed so you make that a critical message to the server RPC'd to the clients and use a reliable flag which then will expect validation. Same with ordering... use when needed with RUDP or custom layer on UDP for reliability.

TCP does all this for you and works great for files/http etc. but doing this for all messages is great overkill in real-time games lower than turn based. And mixing TCP/UDP arguably causes some slowdown to UDP due to TCP queuing. RUDP solves all these issues and is flexible to reliable messages and just firehose broadcast.

http://en.wikipedia.org/wiki/Reliable_User_Datagram_Protocol Designed by none other than Bell Labs...

Also SCTP was created to solve RUDP like issues as an official standard (RUDP is a draft) but standards take time: http://en.wikipedia.org/wiki/Stream_Control_Transmission_Pro...


Enforcing order is hugely important. With TCP, if you lose a packet, all incoming data to the app stops until it's recovered. This is disastrous for an app which can withstand some data being late but needs most of it to show up fast.


I think people would probably build their own communication protocol on top of UDP but not at the level of TCP, if they were given UDP support.

I'm not saying that's good or bad.

Back in college on a distributed systems course, one of the projects was exactly to build that because the professor wanted to produce somewhere between UDP (more than) to TCP (less than).


On the one hand there are tons off applications that don't need UDP and will do just fine with WebSockets. Lots of AJAX based sites can be made much more responsive through WebSockets. Email sites, sites like Google Docs, etc. Chat sites like Meebo or Google Talk. Even many types of games will do just fine with WebSockets. A WoW style game, a Diablo style game, etc.

On the other hand they, the w3c and the browser vendors, are working on unreliable (ie, UDP) peer to peer standard based off the WebRTC stuff so for those applications that can tolerate the unreliableness (ie, voip, video and real time games) it's not far off.


Thanks! I didn't know about WebRTC, so this seems like good news. Is it tailored to video/audio or are we talking about something you can design a protocol on top of?


Apples vs. Oranges: discuss!

(I'm quite happy with my RESTful API that allows subscription to resources via Websockets. This works very nicely when your resource representations include their own href)


I had been thinking of something similar... Use WebSockets for pub-sub/broadcast notifications, but keep REST/XHR for all the normal request-reply operations. It seems like they could be very complementary.

In your API, does the WebSocket subscription deliver the full content of the updated resource? Or does it just provide a change notification which triggers a GET to pull the full content?


Full content. I have a layer over Backbone.JS on the client side that provides an identity map for models (all of which are identified by uri). When a representation is recieved it grabs the relevant model and updates it which makes any views listening on that model also update themselves in the normal backbone way. I think it's kind of neat :)


I've done exactly this before. It works really well. For endpoints that support it, you can put a subscription channel id in the normal REST resource. If the client sees the pubsub channel, and understands what to do with it, it can subscribe for updates via websockets; if it cant/chooses not to, if can just refresh the resource via standard http GET.


What's especially nice is Websockets have their own url type (ws://) you can just include a link to the Websocket's endpoint for the resource for the API client to follow. Reductions in the amount of custom stuff that has to be done is always good :)


I belive that this is the future. With things such as Backbone.Sync written to communicate with websockets(via Socket.io). We can Keep Backbone models in sync easily.

https://github.com/logicalparadox/backbone.iobind

Fog Creek's new Trello syncs data using websockets as well. Its quite effective and works well. Trello also falls back to a regular short-polling system if it needs to.


The Trello team loves WebSockets for push, and we did all of our initial prototyping and a lot of the first version doing RPC over the socket for writes and gets. However, now that we're supporting a REST API for other services to integrate with, we're moving everything other than pushing updates over to that so that we only have to support one API as we grow Trello's feature set. If we decide to go back to making requests over the socket, my best guess is we'll use the REST semantics and just send method, URI, and args in a WebSocket message and expect a response.


It's 2012 and we just finished a project using SOAP, within budget and time-frame, and the client is more than happy.

No, I refuse to believe the future is determined by some cool startup.


If anything, this is understating the problem that authors just aren't doing the design work to provide addressable, reusable resources to the rest of the world. They either haven't noticed or don't care that siloed javascript apps are destroying the web.


I think both can coexist. WebSockets, common comet long poll, and even the "internal" AJAX APIs of web applications are one thing, addressable URIs to resources another.

E.g. Gmail has history navigation and bookmarkable URIs for emails, but no such thing for chat or other page state, which is totally fine.

REST with its addressable resources has clear advantages over RPC style apps for many applications, it won't go away. Bookmarks, navigation, the overall simplicity.


My experience tells me that WebSockets will absolutely dominate in web apps using private API's. They're just so much easier to work with, and superior performance. But REST will still be the preferred way to build public API's because Websockets require a certain amount of resource per user that you probably don't want in a public API.


The web was never a set of "addressable, reusable resources".


Would you please explain? What is the web, in your view, if not that?


I dispute the existence of "resources" in the abstract sense people are trying to achieve with respect to REST. The web is just a collection of stuff with ephemeral links to go from thing to thing. Obviously, these could be called "resources", but not in the coherent sense implied by REST.


Then what is the web?


http://stackoverflow.com/questions/6806263/websocket-api-to-...

One of the main practical problems is that websockets take a second or 2 to start up, clearly too slow.


Where does this article talk about >1s connect times for websocket? The websocket handshake is a single network round trip (discounting any added by TLS if you are using it) and the initial client message frames can be sent in the same TCP packet as the handshake. A websocket connection should not add any more latency than HTTP(S) connections.


WebSockets don't have much startup time at all really. If you're using Socket.io or another Flash-based abstraction you can expect long lead/start up times due to the Flash policy file, but plain old WebSockets should be as fast as any other TCP connection.


Where did people get the notion that WebSockets have anything to do with REST or http?? websockets are a simple tcp connection, you know... like the one that CARRIES http!

So when people say stuff like this:

> First and foremost, how do you represent a URI? Second, how do you represent the HTTP methods (GET, PUT, POST, …)? A

How do we represent HTTP? Well, how about using HTTP ?!?!

(is everybody taking crazy pills, or am I missing some HUGE part of this discussion?)


If you're not talking to web browsers, you could replace WebSockets with any bidirectional medium, e.g., zeromq.


Here's what Roy Fielding said on the REST mailing list when asked about what he thinks about Websockets.

http://tech.groups.yahoo.com/group/rest-discuss/message/1581...

"It would be a different style of interaction. Generally speaking, REST is designed to avoid tying a server's connection-level resources to a single client using an opaque protocol that is indistinguishable from a denial of service attack. Go figure."

I think Websockets relaxes the client-server constraint (and maybe some others). As long as developers understand the consequences, it should be fine I guess.


None of them has to 'win' since they satisfy different needs. There is a place for REST services - where data was introduced in the past and needs to be queried or manipulated. Just like there is a place for Websocket services - data is realtime. One service (like Facebook) could use the best of both. REST for serving user details and Websockets for the chat.


Why focus on client vs. webserver communication layer? Think about using websockets between your app and database api. REST wouldn't do there, but websockets opens up new opportunities for dynamic languages.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: