NodeJS How To Handle Concurrent Request To MySQL
You need to lock the row that you are reading so that you can update this row before anyone else can read it. Look at innodb-locking-reads, specifically for update
From docs
Locking of rows for update using SELECT FOR UPDATE only applies when autocommit is disabled (either by beginning transaction with START TRANSACTION or by setting autocommit to 0. If autocommit is enabled, the rows matching the specification are not locked.
Going off of your provided info, and not knowing more about NodeJS or your OS, Versions, setup etc. This is my thought process as what each issue I see.
Check The Basics
As silly as this may actually be, there are so many unknown factors.
- I see you are running this on your own computer,
- If you run this 10+ times in a row, is the behaviour the same?
- If the end result is different, Check processes running close.
- If possible,
- please do your basic computer check (reboot, close other programs)
- if possible, check it on another computer too
After that is out of the way check:
Check saveBalance Function
- Your
saveBalance',async function
Maybe the cause of the doubleSELECT...SELECT
doubleINSERT...INSERT
- My Gut tells me this is the issue based on the images, the order is wrong.
Check Database Settings
If the
saveBalance',async function
is fine. I would check yourDatabase settings
as based on your MySQL Console Logs & that you are usinglocalhost
- Your image shows SELECT...SELECT...INSERT...INSERT...
- But it should be SELECT...INSERT...**SELECT...**INSERT...
This Might be due to an issue with your MySQL Database Settings.
- Please check your Isolation Level. To Check this run this in your MySQL
SQL Code:
SELECT @@GLOBAL.TX_ISOLATION;
It also, might interest you to use START TRANSACTIONS;
But be sure to enable multistatements in your config. and this is also directly tied to the TX_ISOLATION
as well.
My example would modify your Query like so:
let SQL2="START TRANSACTION; INSERT INTO t_account(no,balance) VALUES('"+req.body.no+"',"+newBalance+"); COMMIT;";
Try Other Accepted Code as your own
Lastly, I also recommend reading 'Approach to multiple MySQL queries with Node.js - One should avoid the pyramid of doom'
I hope this helps.