I'm developing an multiplayer turn based game (e.g chess), should support a lot of players (that's the idea). My question is about a service i'm developing, it's the pairing system, the responsible of pairing 2 players to start a room and start playing.
So, this is the pairing service:
matchPlayers() {
if (this.players.length >= 2) {
let player1 = this.players.shift();
let player2 = this.players.shift();
if (player1 !== undefined && player2 !== undefined) {
player1.getSocket().emit('opponent_found');
player2.getSocket().emit('opponent_found');
return this.createMatchInDataBaseApiRequest(player1, player2)
.then(function (data) {
let room = new RoomClass(data.room_id, player1, player2);
player1.setRoom(room);
player2.setRoom(room);
return room;
});
}
}
return false;
}
At the entrypoint of the server, each new socket connection I push it to an array "PlayersPool" this array is for players waiting to get matched up.
Right now my approach is to pair users when there are available, (FIFO - first in first out).
The problems (and question) I see with this pairing system is:
This depends on new users, this gets executed each time a new user is connected, The flow is: A user connects, get's added to the pool, and check if there are users waiting for being paired, if yes a room is created and they can play, if not he gets added to the waiting pool; Until a new user connects and the code get's executed and so on...
What would happen if in some weird case (not sure if this could happen) 2 players gets added to the waiting pool at the same exact time, this service would find the pool empty and would not create a room: To solve this maybe having another service running always and checking the pool? what would be the best approach? Could this even happen? in which scenario?
Thanks for the help.