Why use AJAX when WebSockets is available?

Ajaxnode.jsPerformanceWebsocket

Ajax Problem Overview


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?

Ajax Solutions


Solution 1 - Ajax

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.

Solution 2 - Ajax

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.

Solution 3 - Ajax

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.

Solution 4 - Ajax

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. :)

Solution 5 - Ajax

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.

Solution 6 - Ajax

> 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.

Solution 7 - Ajax

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).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJackView Question on Stackoverflow
Solution 1 - AjaxkanakaView Answer on Stackoverflow
Solution 2 - AjaxMystView Answer on Stackoverflow
Solution 3 - AjaxAlessandro AlinoneView Answer on Stackoverflow
Solution 4 - AjaxTim Lovell-SmithView Answer on Stackoverflow
Solution 5 - AjaxjliView Answer on Stackoverflow
Solution 6 - AjaxGaurav GandhiView Answer on Stackoverflow
Solution 7 - AjaxMike DView Answer on Stackoverflow