226

I've been using WebSockets for a while now, I have chosen to create an Agile project management tool for my final year project at University utilizing Node server and WebSockets. I found using WebSockets provided a 624% increase in the number of requests per second my application could process.

However since starting the project I've read of security loopholes, and some browsers choosing to disable WebSockets by default..

This leads me to the question:

Why use AJAX when WebSockets seems to do such a great job of lowering latency and resource overhead, is there anything that AJAX does better than WebSockets?

Ernst Robert
  • 2,037
  • 4
  • 25
  • 50
Jack
  • 15,614
  • 19
  • 67
  • 92
  • 2
    Here's a list of engines that support web sockets. http://en.wikipedia.org/wiki/Comparison_of_layout_engines_%28HTML_5%29#Related_specifications – Dante Apr 30 '12 at 01:08
  • Some numbers: http://blog.arungupta.me/rest-vs-websocket-comparison-benchmarks/ – Rune Jeppesen Jan 08 '18 at 10:20
  • It might worth noting that you need another (different) port to connect web sockets in addition to an already running web server. Depending on your circumstances this might or night be an issue. – nuala Nov 25 '20 at 12:23

7 Answers7

221

WebSockets isn't intended to replace AJAX and is not strictly even a replacement for Comet/long-poll (although there are many cases where this makes sense).

The purpose of WebSockets is to provide a low-latency, bi-directional, full-duplex and long-running connection between a browser and server. WebSockets opens up new application domains to browser applications that were not really possible using HTTP and AJAX (interactive games, dynamic media streams, bridging to existing network protocols, etc).

However, there is certainly an overlap in purpose between WebSockets and AJAX/Comet. For example, when the browser wants to be notified of server events (i.e. push) then Comet techniques and WebSockets are certainly both viable options. If your application needs low-latency push events then this would be a factor in favor of WebSockets. On the other hand, if you need to co-exist with existing frameworks and deployed technologies (OAuth, RESTful APIs, proxies, load balancers) then this would be a factor in favor of Comet techniques (for now).

If you don't need the specific benefits that WebSockets provides, then it's probably a better idea to stick with existing techniques like AJAX and Comet because this allows you to re-use and integrate with a huge existing ecosystem of tools, technologies, security mechanisms, knowledge bases (i.e. far more people on stackoverflow know HTTP/Ajax/Comet than WebSockets), etc.

On the other hand, if you are creating a new application that just doesn't work well within the latency and connection constraints of HTTP/Ajax/Comet, then consider using WebSockets.

Also, some answers indicate that one of the downsides of WebSockets is limited/mixed server and browser support. Let me just diffuse that a bit. While iOS (iPhone, iPad) still supports the older protocol (Hixie) most WebSockets servers support both Hixie and the HyBi/IETF 6455 version. Most other platforms (if they don't already have built-in support) can get WebSockets support via web-socket-js (Flash based polyfill). This covers the vast majority of web users. Also, if you are using Node for the server backend, then consider using Socket.IO which includes web-socket-js as a fallback and if even that is not available (or disabled) then it will fall back to using whatever Comet technique is available for the given browser.

Update: iOS 6 now supports the current HyBi/IETF 6455 standard.

Community
  • 1
  • 1
kanaka
  • 70,845
  • 23
  • 144
  • 140
  • 41
    And now at the dawn of 2014, WebSockets is practically a standard (RFC 6455) and only Opera mini does not support it. – Dirk Bester Jan 01 '14 at 21:40
  • 4
    True, Opera Mini does not support it but more embarrassing is the lack of support of the Android browser which makes is a bit more complex to use with webview based apps ( Cordova PhoneGap ) – Miles M. Mar 28 '14 at 17:54
  • 1
    @kanaka, Is sending files over WebSocket faster or slower compared to HTTP (ajax, comet)? – Pacerier May 03 '14 at 00:47
  • @Pacerier it depends (of course), but in general, doing large file transfers should be approximately the same as HTTP. The win for WebSockets is from latency, especially bi-directional latency. – kanaka May 06 '14 at 18:24
  • 2
    @kanaka, If both of them do large files equally well, then why not simply send everything via websockets? Why bother ajaxing pages/data when everything can be sent via WebSockets? (Let's assume it's already 2020 and all browsers have support for WebSockets) – Pacerier May 07 '14 at 03:14
  • 3
    @Pacerier a complete answer would be long, but it basically boils down to the fact that you are trying to re-implement things that the browser already does well (caching, security, parallelism, error handling, etc). Regarding performance, although from-scratch raw large file transfer speed would be similar, browsers have had years to finely tune caching of web content (much of which applies to AJAX requests) so in practice, switching from AJAX to WebSockets is unlikely to provide much benefit for existing functionality. But for low-latency bi-directional communication it's a huge win. – kanaka May 07 '14 at 16:21
  • 1
    @Pacerier Plz correct me if I'm wrong. **Full duplex** explained: "allows communication in both directions, and, unlike half-duplex, allows this to happen simultaneously". For example: your browser can send data to the server while the server is also sending data to your browser at the same time. – Adriano May 12 '16 at 11:12
  • 9
    I'm sorry but for me it does not answer the question. It basically just says that they aren't meant to replace each other and that WS isn't fully supported (it is now). It doesn't answer why you would prefer AJAX over websocket? Let's take Discord for example. Discord uses WS to push messages and events from the server to clients, meanwhile it uses HTTP requests from the client to the server (send message, request data, etc.). I've come to this question to actually get an answer why you would do that. Is there some sort of technical reason why you would put AJAX above the open WS connection? – Charlotte Dunois Jan 22 '17 at 23:05
  • I hope you can add this as an update to your question (if you are still around of course). – Charlotte Dunois Jan 22 '17 at 23:05
83

Fast forward to December 2017, Websockets are supported by (practically) every browser and their use is very common.

However, this does not mean that Websockets managed to replace AJAX, at least not completely, especially as HTTP/2 adaptation is on the rise.

The short answer is that AJAX is still great for most REST applications, even when using Websockets. But god is in the details, so...:

AJAX for polling?

The use of AJAX for polling (or long polling) is dying out (and it should be), but it still remains in use for two good reasons (mainly for smaller web apps):

  1. For many developers, AJAX is easier to code, especially when it comes to coding and designing the backend.

  2. With HTTP/2, the highest cost related to AJAX (the establishment of a new connection) was eliminated, allowing AJAX calls to be quite performant, especially for posting and uploading data.

However, Websocket push is far superior to AJAX (no need to re-authenticate or resend headers, no need for "no data" roundtrips, etc'). This was discussed a number of times.

AJAX for REST?

A better use for AJAX is REST API calls. This use simplifies the code base and prevents the Websocket connection from blocking (especially on medium sized data uploads).

There are a number of compelling reasons to prefer AJAX for REST API calls and data uploads:

  1. The AJAX API was practically designed for REST API calls and it's a great fit.

  2. REST calls and uploads using AJAX are significantly easier to code, both on the client and the backend.

  3. As data payload increases, Websocket connections might get blocked unless message fragmentation / multiplexing logic is coded.

    If an upload is performed in a single Websocket send call, it could block a Websocket stream until the upload had finished. This will reduce performance, especially on slower clients.

A common design uses small bidi messages transferred over Websockets while REST and data uploads (client to server) leverage AJAX's ease of use to prevent the Websocket from blocking.

However, on larger projects, the flexibility offered by Websockets and the balance between code complexity and resource management will tip the balance in favor of Websockets.

For example, Websocket based uploads could offer the ability to resume large uploads after a connection is dropped and re-established (remember that 5GB movie you wanted to upload?).

By coding upload fragmentation logic, it's easy to resume an interrupted upload (the hard part was coding the thing).

What about HTTP/2 push?

I should probably add that the HTTP/2 push feature doesn't (and probably can't) replace Websockets.

This had been discussed here before, but suffice to mention that a single HTTP/2 connection serves the whole browser (all the tabs/windows), so data being pushed by HTTP/2 doesn't know which tab/window it belongs to, eliminating it's capacity to replace Websocket's ability to push data directly to a specific browser tab / window.

While Websockets are great for small bi-directional data communication, AJAX still carried a number of advantages - especially when considering larger payloads (uploads etc').

And Security?

Well, generally, the more trust and control is offered to a programmer, the more powerful the tool... and the more security concerns that creep up.

AJAX by nature would have the upper hand, since it's security is built in to the browser's code (which is sometimes questionable, but it's still there).

On the other hand, AJAX calls are more susceptible to "man in the middle" attacks, while Websockets security issues are usually bugs in the application code that introduced a security flaw (usually backend authentication logic is where you'll find these).

Personally I don't find this to be that big of a difference, if anything I think Websockets are slightly better off, especially when you know what you're doing.

My Humble Opinion

IMHO, I would use Websockets for everything but REST API calls. Big data uploads I would fragment and send over Websockets when possible.

Polling, IMHO, should be outlawed, the cost in network traffic is horrid and Websocket push is easy enough to manage even for new developers.

Myst
  • 18,516
  • 2
  • 45
  • 67
  • 2
    Small grammar error ‘if anything I thing...’ think – spottedmahn Dec 24 '17 at 19:38
  • 2
    @spottedmahn - Thanks! I guess that's what happens I use my code editor to draft text – Myst Dec 24 '17 at 19:42
  • 1
    Apologies, I was absent when the bounty expired. Poor planning on my part. I've set another bounty which I'll award to you after the 23 hours expire. – Duncan Jones Jan 02 '18 at 12:44
  • @Myst thanks for this great explanation. What would you prefer for live notifications like fb/stackoverflow? I am designing a RestFull webservices for my web application, but very confused what should I use for notification feature? AJAX or WebSockets? – The Coder Feb 08 '18 at 20:35
  • @puspen notifications are (IMHO) a great fit for Websockets. There are a lot of decisions to make when you’re designing reconnection logic and offline notification queues, but the actual notification is both easy to code and performant with websockets. – Myst Feb 08 '18 at 21:04
  • @Myst Thanks for quick response. I am really struggling with the design. As per my understanding, suppose I wrote an Article and someone(xyz) commented on that. The time when xyz commented, that data get stored in Database. And the WebSocket is connected to the Database with some listeners, so the WebSocket is know to the changes happened and hence the client will get notified about the comment. Am I guessing it right? – The Coder Feb 08 '18 at 21:16
  • @Myst I have even asked a separate question for this. https://stackoverflow.com/questions/48688604/how-to-get-live-notification-updates-from-mysql-using-websockets – The Coder Feb 08 '18 at 21:18
19

In addition to issues with older browsers (including IE9, as WebSockets will be supported starting from IE10), there are still big problems with network intermediaries not yet supporting WebSockets, including transparent proxies, reverse proxies, and load balancers. There are some mobile carriers that completely block the WebSocket traffic (that is, after the HTTP UPGRADE command).

With years passing, WebSockets will be more and more supported, but in the meantime you should always have an HTTP-based fall-back method for sending data to the browsers.

Alessandro Alinone
  • 4,934
  • 2
  • 18
  • 22
  • Fortunately most WebSocket frameworks support said fallbacks, including using Flash for sockets. Socketn.IO and SignalR are both decent frameworks... though you're really limited, as you mention because of proxies and load balancers. Fortunately, both Node.JS and the next IIS do a decent job with this role as well. – Tracker1 Apr 30 '12 at 17:25
  • Curious: which carriers block WebSocket on port 80? Which block secure WebSocket (WSS) on port 443? The latter implies forced, transparent MITM web proxies .. never saw that in public networks (only corporate ones), since it requires installing new CA certs into browsers. – oberstet Jun 01 '12 at 14:45
  • Foe example, at present, Vodafone Italy blocks WS on port 80, but allows WSS on port 443. You can test any carrier quite easily via our home page, which you can access in both HTTP and HTTPS. It tries WebSockets and falls back to HTTP if they are blocked. Use this URL to display a widget in the middle that reports the current transport: http://www.lightstreamer.com/?s – Alessandro Alinone Jun 08 '12 at 13:21
16

Most of the complaining I have read about websockets and security is from security vendors of web browser security and firewall security tools. The problem is they don't know how to do security analysis of websockets traffic, because once it has done the upgrade from HTTP to the websocket binary protocol, the packet content and its meaning is application specific (based on whatever you program). This is obviously a logistic nightmare for these companies whose livelihood is based on analyzing and classifying all your internet traffic. :)

Tim Lovell-Smith
  • 15,310
  • 14
  • 76
  • 93
11

WebSockets don't work in older web browsers, and the ones that do support it often have differing implementations. That's pretty much the only good reason why they aren't used all the time in place of AJAX.

Community
  • 1
  • 1
jli
  • 6,523
  • 2
  • 29
  • 37
  • 8
    A better reason is that an AJAX request is a normal HTTP request which means it can retrieve HTTP resources; WebSockets can't do that. – Dan D. Apr 30 '12 at 01:10
  • @Dan What if for example image files are sent as base64, CSS as text, JavaScript also as text and then appended to the document? Would that be plausible? – Jack Apr 30 '12 at 01:12
  • @DanD. +1, I agree, I guess I was approaching the question more from the context of rapidly streaming data as in the question's example, but this is definitely correct. – jli Apr 30 '12 at 01:12
  • @Dan D - sometimes you don't want all that crap to go over the line, such as cookies and headers... – vsync May 15 '13 at 18:13
  • 8
    @DanD., HTTP and WebSocket are two distinct protocols, Of course we can't request HTTP resources using WebSocket protocol for the same reason we can't request WebSocket resources using HTTP protocol! **That doesn't mean that the client cannot request html and/or image files sent via the Websocket protocol.** – Pacerier May 03 '14 at 01:11
  • websockets are used for simultaneous requests from server and client like mailing,messaging,pushing events to other clients.while ajax is used to get response of rest api – Saurabh Jun 27 '16 at 09:55
1

I don't think we can do a a clear comparison of Websockets and HTTP as they're no rivals nor solve the same problems.

Websockets are a great choice for handling long-lived bidirectional data streaming in near real-time manner, whereas REST is great for occasional communications. Using websockets is a considerable investment, hence it is an overkill for occasional connections.

You may find that Websockets do better when high loads are present, HTTP is slightly faster in some cases because it can utilise caching. Comparing REST with Websockets is like comparing apples to oranges.

We should be checking which one provides better solution for our application, which one fits best in our use case wins.

Gaurav Gandhi
  • 3,041
  • 2
  • 27
  • 40
  • 1
    the question was about AJAX in general, not REST in particular. It's true that AJAX can be used for REST, but it's also used for polling and long-polling. Although I agree with your conclusion (as you can tell from my answer), I think your answer could reflect the distinction (note that Websockets can be used for REST as well, although not by using HTTP methods). – Myst Dec 27 '17 at 11:30
  • @Myst I agree with you. – Gaurav Gandhi Dec 28 '17 at 05:12
1

An example of the differences between HTTP and Websockets in the form of a client-size lib that can handle Websocket endpoint like REST APIs and RESTful endpoints like Websockets on the client. https://github.com/mikedeshazer/sockrest Also, for those who are trying to consume a websocket API on client or vice versa the way they are used to. The libs/sockrest.js pretty much makes it clear the differences (or rather is supposed to).

Mike D
  • 11
  • 3