Domanda What strategies do you use for managing concurrent operations in a Node.js application?

urooj

Utente Iron
20 Dicembre 2022
9
5
0
9
I attended a NodeJS coding interview. Our solution needs to lock the execution of a function if the update by ID is the same, but called from a different place (eg browser). Once the request is complete, the lock should be released and the next request should be allowed to execute.
No changes need to be made to the code below.
JavaScript:
async function update(id, data) {
    console.log(`start --> id:${id}, data:${data}`);
    await randomDelay(); //update is happening here
    console.log(`end --> id:${id}, data:${data}`);
}

//================================================= = ==============================
//================= Don't change anything below ========================= ======
//================================================= = ==============================

//---- update() is getting called from many places ----
update(1, "browser 1");
update(1, "browser 2");

//========================= Utility functions ======================= == ==============
//========================= Don't change any here================== = ===============

async function sleep(ms) {
    return new Promise((resolve, reject) => {
        setTimeout(() => resolve(), ms);
    });
}

async function randomDelay() {
    const randomTime = Math.round(Math.random() * 1000);
    return sleep(randomTime);
}

This will give an output below.

JavaScript:
start --> id:1, data:browser 1
start --> id:1, data:browser 2
end --> id:1, data:browser 1
end --> id:1, data:browser 2

The expected answer:

JavaScript:
start --> id:1, data:browser 1
end --> id:1, data:browser 1
start --> id:1, data:browser 2
end --> id:1, data:browser 2
Please note the comments in code "Don't change anything below". What would be the possible solution?
 
While user code in NodeJS is single-threaded, the async/await system is event based, if you sleep for a random delay there's no way to tell which is the expected answer, as both calls will run in sequence, immediately logging start, but the event will be triggered first by which has a smaller random delay, causing one end log to be shown before the other in an unpredictable way. To respect the lock mechanism described you must implement a Semaphore or a Mutex which locks operations only for same ID parameter, I am not a nodejs developer, so I can just point you in the right direction.