Home > Back-end >  socket.io | are asynchronous responses stacked up in order?
socket.io | are asynchronous responses stacked up in order?

Time:10-30

  1. Client emits newdataFromClient to sever

  2. server starts processing new data:

socket.on('newdataFromClient', async(newdataFromClient) => {
  let result = await doSomething(newdataFromClient)
  socket.emit('response', result)
})
  1. while server is not done processing, client sends more data

Server will eventually emit 2 results and send them back to the client. One for each newdataFromClient it received.

Will the results be sent back in order or is whichever one finishes faster the one that will be sent back first ?

I'm running a basic node server on a Macbook Pro. If the server starts getting multiple newdataFromClient one after another, will it start handling each on separate threads and when it runs out of threads it will start stacking them up in order?

I assume that my server will crash anyway if it can't handle too many calls but that's a separate issue.

Here I'm only interested in the order of the server responses.

CodePudding user response:

socket.io events will arrive in the order they were sent from the server. The underlying transport here is TCP which keeps packets in order.

Now, if the server itself is handling the individual arriving requests and in its processing to send a result, it has asynchronous operations, there may be no guarantee on the server for what order it will send the responses. In fact, it is likely that the completion order on the server is unpredictable.

Will the results be sent back in order or is whichever one finishes faster the one that will be sent back first ?

Whichever one finishes first on the server and sends a message back is the one that will be received first in the client. These are independent messages that simply go on the transport en-route to the client whenever they are emitted at the server. And the TCP transport which underlies the webSocket protocol which underlies the socket.io engine will keep these packets in the order they were originally sent from the server.


Ack feature in socket.io

socket.io does have a means of getting a specific "ack" back from a specific message. If you look at the socket.emit() doc, you will see that one of the optional arguments is an ack callback. That can be used (in conjunction with the server sending an ack response) to get a specific response to this specific message. For the details on how to implement, see both the client and server-side doc for that "ack" feature.

Absent using that built-in feature, you would have to build your own messageID based system so you can match a given response coming back from the server to the original request (that's what the "ack" feature does internally) because socket.io is not natively a request/response protocol (it's a message protocol).

  • Related