0

I'm writing an express/socket.io-powered game server for a web game. I have a central map of game state objects, each representing an ongoing match, like so:

// map of gameId -> game (primary holding place of games)
const activeGames = new Map<string, ActiveGame>();

Each game is an object like so:

 {
   players: {
     player1: {
       cardsInHand: [ ... ],
       cardsInPlay: [ ... ],
       cardsInLibrary: [ ... ]
     },
     player2: { ... }
 }

My plan is for the server endpoints to modify these arrays in-memory and send out updated game state to all connected clients with each change. I am wondering, however, if in the long run there is some danger here in case I ever have functionality that lets one player modify another player's cards, for example removing one from play. Then multiple connections could be modifying the same aspect of a game object at the same instant.

Is it wise or necessary to set up a queue and add state changes to this queue to ensure they are done one after another rather than potentially having multiple connections making concurrent calls like this one?

 game.players.player1.cardsInHand = newCardsInHand;

If two different connections ran that at once, with different values for newCardsInHand, my state logic could break down.

How is something like this normally handled? Is this premature optimization?

5
  • node.js is "single threaded" and uses a event loop therefore you will never have the problem that two request can modify the same object at the same time.
    – Darem
    Commented Sep 30, 2021 at 5:54
  • Does that mean one API request will start and finish before another one begins execution though? I was concerned that handling of requests might be interleaved in execution such that they would start from the same game state but arrive at differing end states. Commented Sep 30, 2021 at 5:58
  • 1
    if your request is fully synchronous then yes. But for example if you call another API and await this response another request will be processed until the API response arrives. But there will be always just one request that is actively processed.
    – Darem
    Commented Sep 30, 2021 at 6:01
  • I won't be doing that, so that answers my question. Thank you! This still leaves the issue of "what if I have to add additional servers" if the game were popular -- no idea how to share state across multiple instances. But that's a problem for another day I suppose. Commented Sep 30, 2021 at 6:09
  • You could use distributed caches like Redis. But I have no idea how latency sensitiv your game is. So yes it would be a problem of its own.
    – Darem
    Commented Sep 30, 2021 at 6:18

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.