Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

190
Views
SQL banking race condition

I am building a banking system in NodeJS and an SQL database. The two main functionalities I need are deposit and withdraw. I want to make sure that there are no race conditions.

Ex: User has 100$ balance and withdraws 100$ twice quickly and ends up with -100$.

Can the following query have race conditions?

update account set balance = balance - x where balance > x

If this does not solve the problem:

If I use PostgreSQL, will a check constraint on my balance column suffice to eliminate all race conditions?

If I use MySQL, what are my options?

I am curious on what are the different ways to achieve this in both PostgreSQL and MySQL

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

So, you can do the following:

  • Set autocommit to false inside withdraw() function, i.e. start a new transaction.
  • Use SELECT .. FOR UPDATE to read the record
  • Perform checks on value (i.e. whether amount is sufficient enough to perform the operation)
  • UPDATE the value
  • End the transaction

Now, when user tries to withdraw twice quickly, one of the call will start the transaction and issue SELECT.. FOR UPDATE call, that will block the other thread from reading the data. It will be only unblocked once first thread will finishes, i.e. it will prevent race condition.

Here's MySQL's documentation about it.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!