39

From what I read, race conditions occur when different threads try to change a shared variable, which can result in a value that's not possible with any serial order of execution of those threads.

But code in node.js runs in a single thread, so, does that mean code written in node.js is free of race conditions?

1

7 Answers 7

36

Yes, race conditions (in the sense of a shared resource having an inconsistent value due to order of events) can still happen anywhere that there's a point of suspension that could lead to other code being run (with threads its at any line), take for example this piece of async code that is entirely single threaded:

var accountBalance = 0;

async function getAccountBalance() {
    // Suppose this was asynchronously from a database or something
    return accountBalance;
};

async function setAccountBalance(value) {
    // Suppose this was asynchronously from a database or something
    accountBalance = value;
};

async function increment(value, incr) {
    return value + incr;
};

async function add$50() {
    var balance, newBalance;
    balance = await getAccountBalance();
    newBalance = await increment(balance, 50);
    await setAccountBalance(newBalance);
};

async function main() {
    var transaction1, transaction2;
    transaction1 = add$50();
    transaction2 = add$50();
    await transaction1;
    await transaction2;
    console.log('$' + await getAccountBalance());
    // Can print either $50 or $100
    // which it prints is dependent on what order
    // things arrived on the message queue, for this very simple
    // dummy implementation it actually prints $50 because
    // all values are added to the message queue immediately
    // so it actually alternates between the two async functions
};

main();

This code has suspension points at every single await and as such could context switch between the two functions at a bad time producing "$50" rather than the expected "$100", this is essentially the same example as Wikipedia's example for Race Conditions in threads but with explicit points of suspension/re-entry.

Just like threads though you can solve such race conditions with things like a Lock (aka mutex). So we could prevent the above race condition in the same way as threads:

var accountBalance = 0;

class Lock {
    constructor() {
        this._locked = false;
        this._waiting = [];
    }

    lock() {
        var unlock = () => {
            var nextResolve;
            if (this._waiting.length > 0) {
                nextResolve = this._waiting.pop(0);
                nextResolve(unlock);
            } else {
                this._locked = false;
            }
        };
        if (this._locked) {
            return new Promise((resolve) => {
                this._waiting.push(resolve);
            });
        } else {
            this._locked = true;
            return new Promise((resolve) => {
                resolve(unlock);
            });
        }
    }
}

var account = new Lock();

 async function getAccountBalance() {
    // Suppose this was asynchronously from a database or something
    return accountBalance;
};

async function setAccountBalance(value) {
    // Suppose this was asynchronously from a database or something
    accountBalance = value;
};

async function increment(value, incr) {
    return value + incr;
};

async function add$50() {
    var unlock, balance, newBalance;

    unlock = await account.lock();

    balance = await getAccountBalance();
    newBalance = await increment(balance, 50);
    await setAccountBalance(newBalance);

    await unlock();
};

async function main() {
    var transaction1, transaction2;
    transaction1 = add$50();
    transaction2 = add$50();
    await transaction1;
    await transaction2;
    console.log('$' + await getAccountBalance()); // Now will always be $100 regardless
};

main();
5
  • 2
    For the first code, you are introducing the race condition intentionally. transaction1 = add$50(); transaction2 = add$50(); await transaction1; await transaction2; is like Promise.all(transaction1, transaction2) You should do this to avoid it: await add$50(); await add$50();
    – grant sun
    Commented Mar 8, 2019 at 20:44
  • 11
    The point is to demonstrate that if things happen concurrently then yes you can still result in similar race conditions as with threads. So yes I have introduced a race condition intentionally to demonstrate the point. You might say have an API in which you do something transactional as a different example but I didn't want the example to be even more complex. Commented Mar 10, 2019 at 3:12
  • Isn't there still a race condition in this code? The state could change in between when you check if (this._locked) and the action you take, so you think it's safe to get a lock but the other thread grabbed the lock rather after you determined there was not one.. Two threads could be trying to get locks at almost the exact same time. Let me know if I'm misunderstanding something. I'm new to concurrency and that's why I found this article. Commented Jan 15, 2022 at 13:50
  • 1
    No, this code isn't multithreaded at all, in fact it runs entirely in a single thread. Concurrency and threading are actually different concepts, effectively concurrency is the ability for multiple tasks to interleave their work. Threading/paralellism though is where things run actually at the same time. My example purely concerns concurrency and does not suffer threading problems because interleaving points are explicit (wherever there is an "await"). While some environments do add real threads to Javascript, most expose it via concurrency so thread-style race conditions can't occur Commented Feb 14, 2022 at 12:58
  • 2
    As a particular example, threads in web browsers running Javascript are exposed using Worker objects. There are only two ways to communicate with Worker, either the SharedArrayBuffer object or MessageChannels. When using SharedArrayBuffer real race conditions can absolutely occur, however their scope is limited to those objects and can't interrupt arbitrary code. When using MessageChannel responses to work are queued to be fired as events, these events only fire when no JS is currently running, so no thread-based race conditions can occur when using MessageChannel. Commented Feb 14, 2022 at 13:03
28

Yes. Node.js can run into race conditions as soon as you start sharing resources.

I mistakenly also thought you couldn't get race conditions in Node.js because it's single threaded nature, but as soon as you use a shared resource outside of node (e.g. a file from the file system) you can get into a race condition. I posted an example of this issue in this question when I was trying to understand this: node.js readfile woes

What is different in Node.js from other environments is that you have a single thread of JavaScript execution so there is only one JavaScript instance running your code (as oppossed to a threaded environment in which there are many threads executing your app code at the same time.)

24

No. That's true you cannot have race condition on a single threaded, non I/O doing program.

But node.js is mainly fast because of its non blocking way of programming. Non blocking means that setting a listener to a response event, you can do something else while waiting this response.

Why ? Because the work for getting the response is done on another thread. Database, filesystem, run on other thread, client obviously runs on another computer and you program workflow can depend on its response.

So strictly speaking, node.js runs on one thread, but your program workflow, wich include I/O (database, filesystem), client and everything, runs on many thread.

So there still can be race condition if you do a request to add something to a database, and then just send a request to delete it without waiting for the response of the first request. There would be no race condition if the database was running in the same thread as node.js, and the request was just a function call executed immediatly.

4
  • 5
    A race condition has nothing to do with threads. Threads result in race conditions because they interleave the execution of the code. Async calls also do the same, so race conditions are possible.
    – AbiusX
    Commented Jun 3, 2019 at 16:56
  • 1
    Async calls without unpredictable I/O cannot result in race conditions. If single-threaded async code results in race conditions, it is always because external ressources are involved.
    – jillro
    Commented Jun 4, 2019 at 17:15
  • @AbiusX Would be nice if you can give a code example of this!
    – basickarl
    Commented Jul 25, 2019 at 12:37
  • @jillro Same for you, would be nice with a code example!
    – basickarl
    Commented Jul 25, 2019 at 12:37
10

Race conditions can still happen as they really have nothing to do with threads, but on making assumptions about event timing and sequence, so threads are just an example of that.

Node.js is single-threaded, but still concurrent, and race conditions are possible. For example:

var http = require('http');

var size;

http.createServer(function (req, res) {
  size = 0;

  req.on('data', function (data) {
    size += data.length;
  });

  req.on('end', function () {
    res.end(size.toString());
  })

}).listen(1337, '127.0.0.1');

This program is supposed to send clients a size of their request. If you test it, will seem to work correct. But it is actually based on implicit assumption, that nothing happens between request start and end events. If there are 2 or more concurrent clients it will not work.

This happens here because size variable is shared, a lot like when two threads share a variable. You can think about an abstract "asynchrnous context", which is a lot like thread, but it can only be suspended at certain points.

5
  • okay! However, in this case, if the size variable is inside the createServer callback, then each user gets a separate copy of size, right?
    – Jatin
    Commented Jan 29, 2014 at 17:55
  • I do not agree. They have to do with threads and I/O which is conceptually equivalent to sharing the workflow of the programm on many threads. You cannot have race conditions on a single-thread , non I/O doing program (I mean a program just accpeting parameter and returning exit value).
    – jillro
    Commented Jan 29, 2014 at 18:07
  • Here there is another thread acting on the workflow wich are clients. If you put all your programm in a main loop checking for new request queue, and then nest a loop checking for new data in the request, there will be no race condition anymore. That is because another thread can call (through event) a small step of the request processing workflow that whenever it wants that there is concurrency and race condition.
    – jillro
    Commented Jan 29, 2014 at 18:27
  • 6
    What you describe is not a race condition. You are describing shared state and the misunderstanding of it in Node.js. Commented Jan 29, 2014 at 18:28
  • 1
    In a certain way we could say there is a race condition between clients because of the shared state in the server, but there is indeed no race condition in the server itself.
    – jillro
    Commented Jan 29, 2014 at 18:32
9

No. Node.js is free of race conditions that would be caused by context switching; however, you can still write a node.js program where asynchronous events happening in an unexpected order result in an inconsistent state.

For example, suppose you have two functions. The first sends a message through a WebSocket and, in a callback, saves the reply. The second function deletes all saved replies. Calling the functions in order does not guarantee an empty message list. It is important to consider all possible event orderings when doing asynchronous programming.

EDIT: Here's some example code

var messages = [];

...

io.sockets.on('connection', function (socket) {
    socket.emit('ask', { question: 'How many fish do you have?' });
    socket.on('reply', function (data) {
        messages.push(data);
    });
    ...
    wipe();
});

function wipe() {
    setTimeout(function() {
        messages = [];
    }, 500);
}
4
  • The race condition is indeed between client and node.js program. Note that given the client behaviour, output of node.js program is known.
    – jillro
    Commented Jan 30, 2014 at 17:59
  • 1
    @Guilro That's a good point. I interpreted the question to mean "Can a Node.js program exhibit race conditions?" The answer is yes. If the intended question was "Can a pure JS application with no I/O have race conditions?" the answer is no. I think the former is a more useful question because most Node.js applications will have I/O.
    – aebabis
    Commented Jan 30, 2014 at 18:05
  • @Guilro Wait a minute. Since sockets use the Internet, knowing client behavior isn't sufficient. You would also have to know network and OS behavior.
    – aebabis
    Commented Jan 30, 2014 at 18:49
  • Yep, of course :) anyway you are right about what was the intended question, and that is why I voted your answer. It was just to give precisions.
    – jillro
    Commented Jan 30, 2014 at 21:07
5

Yes. It can.

Race condition in Nodejs is feasible when you use cluster module to initialise multiple workers.

The case

var cluster = require('cluster');
var fs = require('fs');
if(cluster.isMaster){
    for(var i=0;i<4;i++){
        cluster.fork();
    }
}else{
    fs.watch('/path/to/file',function(){
        var anotherFile = '/path/to/anotherFile';
        fs.readFile(anotherFile,function(er,data){
             if(er){
                 throw er;
             }
             data = +data+1;
             fs.writeFile(anotherFile,data,function(er){
                 if(er){
                     throw er;
                 }
                 fs.readFile(anotherFile,function(er,newData){
                     if(er){
                         throw er;
                     }
                     console.log(newData); //newData is now undetermined
                 });
             });
        });
    });
}

Whenever you change the watched file, 4 workers will execute the handler at the same time. This behaviour causes the undetermined newData.

The solution

if(cluster.isMaster){
    var lock = {};
    var timer = setInterval(function(){
        if(Object.keys(cluster.workers).length >= 4){
            return clearInterval(timer);
        }
        //note that this lock won't 100% work if workers are forked at the same time with loop.
        cluster.fork().on('message',function(id){
             var isLocked = lock[id];
             if(isLocked){
                 return console.log('This task has already been handled');
             }
             lock[id] = 1;
             this.send('No one has done it yet');
        });
    },100);
}else{
     process.on('message',function(){
        //only one worker can execute this task
        fs.watch('/path/to/file',function(){
            var anotherFile = '/path/to/anotherFile';
            fs.readFile(anotherFile,function(er,data){
                 if(er){
                     throw er;
                 }
                 data = +data+1;
                 fs.writeFile(anotherFile,data,function(er){
                     if(er){
                        throw er;
                     }
                     fs.readFile(anotherFile,function(er,newData){
                         if(er){
                             throw er;
                         }
                         console.log(newData); //newData is now determined
                     });
                 });
            });
        });
     });
     //ask the master for permission
     process.send('watch');
}
0

Any JavaScript asynchronous code is vulnerable to race conditions:

'use strict';

const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

const transfer = async (sender, receiver, amount) => {
  const initialBalance = receiver.balance;
  sender.balance -= amount;
  await pause(32);
  receiver.balance = initialBalance + amount;
};

const alex = { name: 'Alex', balance: 1000 };
const jordan = { name: 'Jordan', balance: 1000 };

const displayBalances = () => console.log(alex, jordan);

displayBalances();
transfer(alex, jordan, 150);
transfer(jordan, alex, 200);
transfer(alex, jordan, 250);
transfer(jordan, alex, 300);
transfer(alex, jordan, 350);
setTimeout(displayBalances, 1000);

// { name: 'Alex', balance: 1000 } { name: 'Jordan', balance: 1000 }
// { name: 'Alex', balance: 900 } { name: 'Jordan', balance: 850 }
// Where's the money?

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.