Join queue nodeJS

23 Views Asked by At

So I'm trying to do a NodeJS code to allow a certain number of people to join a gym session. Issue here is when, for example, I have a session with 1 empty spot and two persons try to join at the exact same time. The checks that I run to know if the sesion is full do not work as none of them has already filled the spot so the app ends up letting both of them join.

I have tried bull queue system but I'm not sure if I'm in a good path or if it's the best option so far.

Any suggestion will help!

Thanks

1

There are 1 best solutions below

0
Abdelrhman Elsayed On

In order to tackle­ this issue of simultaneous operations, you'll imple­ment a scheme using a mix of me­thods like tool lock mechanisms, atomic processe­s, and queue structures. A pote­nt strategy is to use a distributed lock manage­r, for example, Redlock, to e­nsure mutual exclusion during the updating of se­ssion availability.

const Redlock = require('redlock');
const redlock = new Redlock([/* Redis clients */]);

async function joinGymSession(sessionId) {
    const lock = await redlock.lock(`session:${sessionId}:lock`, 1000);
    
    // Check session availability and allow joining if spot is available
    
    lock.unlock();
}