9 ms·
Node.js race conditions
- SparkyMcUnicorn 6y agoChromium is rendering the code blocks as single-line, and they're impossible to read. Is it just me? Firefox seems to load them just fine.
- chrisseaton 6y ago> A race condition is a type of programming error I don't think a race condition is inherently an error. If you can design your program to accommodate races, including even data races, then allowing them and not spending time on protecting against them can be a useful performance optimisation. It's only a bug if the race causes you to get into a state that you don't want.
- dimitrios1 6y agoI seriously doubt people writing web software are planning for intentional races in their system designs the way an OS dev does to avoid synchronization overhead.
- kube-system 6y agoI don't await promises if I don't need to. Don't think that's a super unusual pattern.
- rileymat2 6y agoI feel a bit ignorant, although you don't need to await on assignment, don't you need to await to "unwrap" it when needed?
- thecopy 6y agoSometimes you dont need the result.
- rileymat2 6y agoRight, if you don't need it, you don't need to unwrap it.
- IggleSniggle 6y agoAs the article is making a round-about way of pointing out, you might need to "block" (unwrap) due to a side-effect in order to make the sequencing correct for downstream logic that touches the same thing. Shouldn't be necessary if things are coded appropriately in the first place, and maybe better to just refactor, but...
- hexsprite 6y agoIt’s just a function that returns a promise object. The await keyword triggers the wait and unwrap functionality, but in cases where you don’t care you can just call it as a regular function
- aaomidi 6y agoYou should however, catch it. If you're doing nothing with a promise (awaiting, or catching), then you have bad code. You can read more about that here: https://palantir.github.io/tslint/rules/no-floating-promises/ https://palantir.github.io/tslint/rules/no-floating-promises...
- chrisseaton 6y agoThat guide says that you should do this because it can cause race conditions: > This can cause unexpected and/or non-deterministic behavior depending on external timing factors. But, as this whole thread is about, sometimes you don't mind race conditions. So it can ok to acknowledge but ignore this advice if you are aware of how this race conditions matters to your codebase. Learn the rules, but know when to break them.
- mfbx9da4 6y agoCool article! Fun programming assignment - implement a Mutex using promises.
- cryptica 6y agoIt's important to figure out ahead of time which features of your system can be executed in parallel and which features should be executed serially.
- applepple 6y agoCallbacks (including those passed to Promise then methods) are a dangerous primitive. I would recommend using awaitable streams like those used in https://socketcluster.io/ https://socketcluster.io/ - Or https://github.com/SocketCluster/writable-consumable-stream https://github.com/SocketCluster/writable-consumable-stream for general purpose. The philosophy of SC and WritableConsumableStream is that the main trunk logic of your system/module should declared as a single serial stream and any parallel logic should explicitly branch off from it. With traditional event listeners, there is no such thing as a 'main trunk' of the logic... The entry points (event listeners) are scattered all over the place and this can cause a lot of possible state permutations when business logic is executed inside those listeners (since you can't control the timing of when those event handlers are called). This kind of programming is a good alternative to functional programming as it offers a safe way to asynchronously mutate state.
- hyeomans 6y agoNice, are you using it in production? First time I hear about SocketCluster
- golergka 6y agoTo have a race condition, you first have to have a shared state. And in my experience, for almost all applications where NodeJS is a good fit (usually a CPU-light application that is serving web requests, each of them independent of others, and waiting for a long time on IO, usually different database requests and other external services), shared state is already a bad pattern.
- chrisseaton 6y ago> To have a race condition, you first have to have a shared state. I think you're possibly confusing 'race condition' with 'data race'. You need shared state for a data race, but not for a race condition. For example if you send a request to two web services, then wait for responses from either, then that's a race condition on which result comes back first, because the non-deterministic timing can change program behaviour. And that's not even necessarily a problem or a bug. You can easily get race conditions even in a system that tries to minimise shared state, such as Erlang, even though they protect you from data races.
- dnautics 6y agoTechnically in your example the shared state is the network.
- chrisseaton 6y agoNo the situation still holds if you send two requests on different network cards to entirely different networks that share nothing.
- dnautics 6y agoIn that case the shared state is the observer.
- chrisseaton 6y agoI don't think that's really a meaningful or useful definition of shared state for these purposes.
- jkrems 6y agoNice reminder that different kinds of race conditions exist, even without shared mutable data! One thing I wish the article mentioned: In the given example, another solution would have been to make the balance change safe. E.g. `addBalance()` or `updateBalanceIfEqual(old, new)`. Requiring a mutex around each call site that needs to be used correctly (and keeps being used correctly over time) seems like a pretty fragile way out.
- piterrro 6y agoMutex in Nodejs, ROTFL. This kind of bad programming leads to overuse of synchronization primitives. Nodejs is single threaded and doesnt need locks and mutexes. In any application. Properly writing code will make synchronization unnecessary. In the provided example, the saveBalance function should not overwrite the values of balance variable but rather increment its value (increment with negative too). That's it your problem is solved, one line of code to change.
- aaomidi 6y agoRace conditions are in the nature of concurrent code. Not just parallel code. Take go, use gomaxprocs and set it to 1. Spawn a bunch of goroutines that share memory. And easily you'll have race conditions if you're not careful.
- piterrro 6y agoI didnt say race conditions are impossible in Nodejs. Just highlighted that good program engineering is enough to avoid it and programmers should do that in the first place.
- aaomidi 6y agoSure but at the same time there is a reason synchronization primitives exist. Readability of code > everything else.
- paxys 6y agoIn a real world use case you are going to have multiple instances of your application running at the same time anyways, so the mutex solution is pointless. Use a DB transaction or something.
- tored 6y agoDB transaction will not save you in this case. As the article hinted you have to either update the balance in one query or use a lock, like an optimistic lock. Optimistic lock could have also been used instead of the mutex.
- lostcolony 6y agoIf you have multiple instances, a lock of any sort won't work; you have to update the query. If you update the query, a lock is unnecessary. I think it's fair to assume the parent was inferring that if you were using a DB transaction, you'd rewrite the logic to use it, rather than keeping the read and the write separate from each other, and therefore make a transaction pointless.
- tored 6y agoNo, locks work. Lock is needed if you need to do some sort of complex computation before writing, like updating a JSON blob.
- lostcolony 6y agoAs both I and the parent said, "If you have multiple instances". In which case, locks (like those mentioned in the article) don't work. Because instance A reads 0, instance B reads 0, instance A writes 50, instance B writes 50. Totally serialized on each instance, totally unpredictable in when they hit the DB. Just like you have a lock serving as a synchronization point on an instance, in the case of multiple instances, you want to push the synchronization point down into a single instance at the data layer (which you often have when using a traditional RDBMS). But RDBMS' don't have locks, per se, for that synchronization; they have transactions that serve a similar purpose. But, regardless of where that synchronization is, you have to ensure the update logic stays there. Having an interface that loads data, and saves data, at the application layer, ensures that a DB layer lock won't work, either. You have to change it to have the DB actually read and update the data to benefit from the synchronization the DB transaction provides you. So, as I said before...a lock (at the application layer) is neither sufficient nor necessary. A DB transaction (with the implied update of the query necessary to make a transaction mean anything) is both.
- divs1210 6y agoMutexes in a single threaded event loop? Wut? This problem requires a compare-and-swap primitive, not mutexes.
- moocowtruck 6y agoi feel like this post creates the problem, and then solves the wrong problem
- xsmasher 6y agoYep - in order for this solution to work, all of the calls need access to the same mutex; they all need to be in the same process (this is noted toward the end). If you can do that, just share an "account" object. Calling account.balance+=50 doesn't require a mutex.