Search code examples
node.jsperformanceiosocket.ioprocessing-efficiency

Socket.IO: most efficient way to update clients with massively fluctuating data


Imagine Agar.io. Unlike a chat app, the list of users (or players) and other environment objects will be constantly changing, for each player, as players move around the map. That is because each client can't receive updates about every object, because the map is too large and the lag would be too much. So which of the following methods of updating clients, with Socket.IO, would be more efficient:

  1. Send an environment array containing data, which replaces the local arrays on each client.
  2. Send individual messages when objects appear/disappear in a players field of view, and tinker with the local arrays object by object.

If there is a better way than the above two, please outline it.


Solution

  • This is a multi-vector tradeoff decision so without some measuring and probably experimentation, we can't really tell you what situation is optimal. But, we can direct your thinking which you can hopefully use to finish the analysis.

    First off, to scale and reduce lag, you want to:

    1. Send fewer messages to each client.
    2. Send smaller payloads with each message as long as it doesn't make item #1 worse (e.g. as long as it doesn't cause you to send more messages).
    3. Have fewer times on the server where you are doing calculations and then sending messages.

    To send fewer messages to each client you want to:

    1. Reduce the scope of the map that the client gets sent updates about to only things that are closely in view (it sounds like you're already doing some of that).
    2. Combine as much information as you can in each message that you are going to send to a client - make sure that you're never sending more than one message to a given client for a particular update.

    To send smaller messages to each client you want to:

    1. Reduce the size of the data you send to each client. This means that if some data has not changed since that last time you communicated with this client, then don't resend that data. This would suggest that your second option (client updates its own local array) is a better way to do it because you only have to send deltas to the client and it remembers previous state.

    2. Carefully analyze the format of the data you're sending to the client and reduce its size wherever possible. Straight JSON is often not the most efficient way to send data if you're trying to optimize transmission size.