Ayush Gupta
Ayush Gupta

Reputation: 9285

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

So I am planning on building a Single Page Application. In that application, there will be a lot of API calls, and very frequent from what we expect.

So we were thinking of foregoing API calls and replacing it with WebSockets totally. So how we're planning to make this work is as follows:

  1. We designate a special code(or socket message type) for each resouce the client can request.
  2. Client connects to the server via a websocket.
  3. For each resource/data the client wants, it send a message to the server with the predefined code.
  4. Server processes the request and sends the response back to the client.
  5. Client and server keep the connection open, and any future requests are communicated over the same socket.

We expect to reduce overhead and latency with this approach, but is that a right assumption? Also, what could be the pitfalls of using this mechanism?

Upvotes: 0

Views: 970

Answers (1)

techPackets
techPackets

Reputation: 4504

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

Upvotes: 1

Related Questions