Search code examples
htmlnode.jssocket.iomultiplayer

Should a multiplayer game always request data from a database on each client request?


Well I don't know if the title for this question is appropriate or not, but I didn't know how to put this in few words.

I'm currently developing a multiplayer 2D game using NodeJS and Socket.io on the server side and HTML5 on the client side. This game doesn't need to save the players progress unless when they finish it. And I must make sure that all information about the players, such as, scores and helps are always valid. So I decided to centralize this information on the server, this way the clients never send a score to the server, instead based on the information sent the server calculates the scores and send them to all clients. Besides that, I can have different sessions of this game running with 2 players minimum and 4 players maximum.

At first I decided to implement this with the server always maintaing the games sessions data in memory, but now I'm questioning myself if I shouldn't have used a database to store this data instead. I'm using a database to store the sessions data only when they are finished because I have no use for unfinished sessions data. But should I instead maintain the sessions and players data on the database while they are playing? My problem here is that the clients communicate very frequently with the server, with this approach I would have to first request their data from the database, make the necessary changes, store it back into the database, and repeat this process on each client request. Maybe the answer to this is obvious, but should I use this approach instead?

It is the first time I'm developing a game, so I have no idea how things usually work. I just know that I want the server to be fast. I chose to maintain everything on memory mainly because all examples and tutorials I found about multiplayer games development never mentioned a database...

Thank you!


Solution

  • I am also developing a multiplayer game using node.js and socket.io. You should not access the database on each client request because,

    1) I/O operations are expensive.

    Reading/writing to database is "expensive" (slow). It is much faster to read and write from memory.

    2) I/O operations should be asynchronous in Node.js.

    function read_or_alter_database(input, function(callback){ update_the_client(); });
    

    This makes the database operation non-blocking: the rest of your application will still run, until the operation is done. Then, the callback function is executed. If the player's client rely on the database access to update the game state, then this becomes a blocking operation (since the game cannot proceed until the database operation is done), which negates the main purpose of Node.js.

    3) There will be a high volume of client requests in multiplayer games.

    This plus point 1 results in a big efficiency loss.