Home > Enterprise >  How to handle concurrent request with socket io while joining room
How to handle concurrent request with socket io while joining room

Time:06-20

I'm trying to create/join a room with limit of 2 user per room everything is working fine but when 2 users make a concurrent request to create/join a room all 3 users are added to same room. i have tried using

  1. simple mongodb insert/update
  2. using transaction
  3. now storing in memory

    here is the code
const rooms = {};
module.exports = function ({ io, socket }) {
  socket.on("/createJoinPublicRequest", async ({ user }) => {
    let title = `${user._id}.${Date.now()}`;
    let foundRoom = Object.keys(rooms).find((room) => {
      return rooms[room].roomLimit > rooms[room].users.length;
    });

    if (!foundRoom) {
      //create a room if not found
      rooms[title] = {
        title,
        users: [
          {
            _id: user._id,
          },
        ],
        roomLimit: 2,
        roomType: "public",
        status: "open",
      };
      socket.join(title);
    } else {
      // join existing room
      room = rooms[foundRoom];
      room.users.push({ _id: user._id });
      if (room.users.length == room.roomLimit) {
        room.status = "full";
        if (await storeToMongoDB(room)) {
          delete rooms[foundRoom];
        }
      }
      socket.join(room.title);
    }

    await User.findByIdAndUpdate(user, {
      joinedRoom: title,
    });

    return;
  });

CodePudding user response:

you should use mutex lock to prevent adding more Users to Room.

For Single Instance : https://www.npmjs.com/package/async-mutex

For Multi Instance : Redis Mutex Lock

  • Related