Websocket VS Rest API for Real Time Data

websocket vs rest API for real time data?

The most efficient operation for what you're describing would be to use a webSocket connection between client and server and have the server send updated price information directly to the client over the webSocket ONLY when the price changes by some meaningful amount or when some minimum amount of time has elapsed and the price has changed.

This could be much more efficient than having the client constantly ask for new price changes and the timing of when the new information gets to the client can be more timely.

So, if you're interested in how quickly the information on a new price level gets to the client, a webSocket can get it there much more timely because the server can just send the new pricing information directly to the client the very moment it changes on the server. Whereas using a REST call, the client has to poll on some fixed time interval and will only ever get new data at the point of their polling interval.

A webSocket can also be faster and easier on your networking infrastructure simply because fewer network operations are involved to simply send a packet over an already open webSocket connection versus creating a new connection for each REST/Ajax call, sending new data, then closing the connection. How much of a difference/improvement this makes in your particular application would be something you'd have to measure to really know.

But, webSockets were designed to help with your specific scenario where a client wants to know (as close to real-time as practical) when something changes on the server so I would definitely think that it would be the preferred design pattern for this type of use.


Here's a comparison of the networking operations involved in sending a price change over an already open webSocket vs. making a REST call.

webSocket

  1. Server sees that a price has changed and immediately sends a message to each client.
  2. Client receives the message about new price.

Rest/Ajax

  1. Client sets up a polling interval
  2. Upon next polling interval trigger, client creates socket connection to server
  3. Server receives request to open new socket
  4. When connection is made with the server, client sends request for new pricing info to server
  5. Server receives request for new pricing info and sends reply with new data (if any).
  6. Client receives new pricing data
  7. Client closes socket
  8. Server receives socket close

As you can see there's a lot more going on in the Rest/Ajax call from a networking point of view because a new connection has to be established for every new call whereas the webSocket uses an already open call. In addition, in the webSocket cases, the server just sends the client new data when new data is available - the client doens't have to regularly request it.

If the pricing information doesn't change super often, the REST/Ajax scenario will also frequently have "do-nothing" calls where the client requests an update, but there is no new data. The webSocket case never has that wasteful case since the server just sends new data when it is available.

How different between WebSocket and REST API

A REST API uses HTTP as the underlying protocol for communication, which in turn follows the request and response paradigm. However, with WebSockets, although the communication still starts off over HTTP, it is further elevated to follow the WebSockets protocol if both the server and the client are compliant with the protocol (not all entities support the WebSockets protocol).

Now with WebSockets, it is possible to establish a full duplex and persistent connection between the client and a server. This means that unlike a request and a response, the connection stays open for as long as the application is running, and since it is full duplex, two way simultaneous communication is possible i.e now the server is capable of initiating a communication and 'push' some data to the client.

This is the primary concept use in the realtime technology where you are able to get new updates in the form of server push without the client having to request (refresh the page) repeatedly. Examples of such applications are Uber car's location tracking, Push Notifications, Stock market prices updating in realtime etc.

Here's a video from a presentation I gave earlier this month about websockets and how they are different than using the regular REST APIs: https://www.youtube.com/watch?v=PJZ06MLXGwA&list=PLZWI9MjJG-V_Y52VWLPZE1KtUTykyGTpJ&index=2

Websocket API to replace REST API?

Not to say that the other answers here don't have merit, they make some good points. But I'm going to go against the general consensus and agree with you that moving to websockets for more than just realtime features is very appealing.

I am seriously considering moving my app from a RESTful architecture to more of an RPC style via websockets. This is not a "toy app", and I'm not talking about only realtime features, so I do have reservations. But I see many benefits in going this route and feel it could turn out to be an exceptional solution.

My plan is to use DNode, SocketIO, and Backbone. With these tools, my Backbone models and collections can be passed around from/to client and server by simply calling a functions RPC-style. No more managing REST endpoints, serializing/deserializing objects, and so forth. I haven't worked with socketstream yet, but it looks worth checking out.

I still have a long way to go before I can definitively say this is a good solution, and I'm sure it isn't the best solution for every application, but I'm convinced that this combination would be exceptionally powerful. I admit that there are some drawbacks, such as losing the ability to cache resources. But I have a feeling the advantages will outweigh them.

I'd be interested in following your progress exploring this type of solution. If you have any github experiments, please point me at them. I don't have any yet, but hope to soon.

Below is a list of to-read-later links that I've been collecting. I can't vouch that they are all worthwhile, as I've only skimmed many of them. But hopefully some will help.


Great tutorial on using Socket.IO with Express. It exposes express sessions to socket.io and discusses how to have different rooms for each authenticated user.

  • http://www.danielbaulig.de/socket-ioexpress/

Tutorial on node.js/socket.io/backbone.js/express/connect/jade/redis with authentication, Joyent hosting, etc:

  • http://fzysqr.com/2011/02/28/nodechat-js-using-node-js-backbone-js-socket-io-and-redis-to-make-a-real-time-chat-app/
  • http://fzysqr.com/2011/03/27/nodechat-js-continued-authentication-profiles-ponies-and-a-meaner-socket-io/

Tutorial on using Pusher with Backbone.js (using Rails):

  • http://blog.pusher.com/2011/6/21/backbone-js-now-realtime-with-pusher

Build application with backbone.js on the client and node.js with express, socket.io, dnode on the server.

  • http://andyet.net/blog/2011/feb/15/re-using-backbonejs-models-on-the-server-with-node/
  • http://addyosmani.com/blog/building-spas-jquerys-best-friends/
  • http://fzysqr.com/2011/02/28/nodechat-js-using-node-js-backbone-js-socket-io-and-redis-to-make-a-real-time-chat-app/
  • http://fzysqr.com/2011/03/27/nodechat-js-continued-authentication-profiles-ponies-and-a-meaner-socket-io/

Using Backbone with DNode:

  • http://quickleft.com/blog/backbone-without-ajax-part-ii
  • http://quickleft.com/blog/backbone-without-ajax-part-1
  • http://sorensen.posterous.com/introducing-backbone-redis
  • https://github.com/cowboyrushforth/minespotter
  • http://amir.unoc.net/how-to-share-backbonejs-models-with-nodejs
  • http://hackerne.ws/item?id=2222935
  • http://substack.net/posts/24ab8c

Best practices for building a chat app? (REST vs Websockets)

In my experience, To mix the two is the best way to do that.
I did that in many projects and it worked well.
I surely think that modularity is the best way to make code clean and qualified.
So, to use both of regular REST API and websocket is more professional.
Thank you.

What could be the drawbacks of replacing API calls with WebSockets?

WebSockets are preferable if you are writing a messaging app or a game.
If your app hits the db frequently you can consider Server Sent Events

WebSockets have a bidirectional communication between a client & a server. You may not necessarily require websockets.

WebSockets may look like HTTP but only at the start. It isn't HTTP. There might be possible side effects that haven't been considered in the design of the protocol.
They keep the connection open on the server for the duration of the time the user is interacting with the page. This will increase the demand on the server, and means that you will always have to scale OUT rather than UP.
If don't have a msging app or a game, I believe WebSockets is a less economical choice.

Related links

https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events

Twitter's method for streaming API on w3c

WebSockets vs. Server-Sent events/EventSource

REST API or websocket?

Asynchronous technology is definitely the way to go if you want to support large number of clients. Async gives the ability to the server to send data to the clients at any moment. Rest is only client to server. So you need to poll which is really costly and inefficient.

Websocket is also better as it uses less data on the network. It does not rely on HTTP after connection. A TCP connection is actually established. If there are some proxies, you may have to be careful.

Websocket alone is a simple wire with no added protocol other than send/receive. So you need something above to manage channels and subscriptions. STOMP is usually used for that. You may look at stomp.js.

You may also consider SSE. It is less complicated than web-socket, relies on HTTP, so more chatty. Well web-socket is not really complicated, there are libs to help.

You may also mix websocket for part of your api and keep REST for another part. You have to evaluate what makes sense.

Some resources:

  • http://caniuse.com/#feat=websockets
  • http://caniuse.com/#feat=eventsource
  • https://github.com/jmesnil/stomp-websocket (I did not test it but there are quite some stars so it should be ok :-) )


Related Topics



Leave a reply



Submit